diff --git a/CODE-TEMPLATES.md b/CODE-TEMPLATES.md new file mode 100644 index 00000000..9a3240b6 --- /dev/null +++ b/CODE-TEMPLATES.md @@ -0,0 +1,1395 @@ +# SecuBox Module Code Templates + +**Version:** 1.0.0 +**Date:** 2025-12-27 +**Purpose:** Ready-to-use code templates extracted from working SecuBox modules + +--- + +## Table of Contents + +1. [File Structure Template](#file-structure-template) +2. [API Module Template](#api-module-template) +3. [JavaScript View Template](#javascript-view-template) +4. [RPCD Backend Template](#rpcd-backend-template) +5. [Menu JSON Template](#menu-json-template) +6. [ACL JSON Template](#acl-json-template) +7. [CSS Styling Template](#css-styling-template) +8. [Complete Implementation Example](#complete-implementation-example) + +--- + +## File Structure Template + +Every SecuBox module follows this exact structure: + +``` +luci-app-/ +├── Makefile # OpenWrt package definition +├── README.md # Module documentation +├── htdocs/luci-static/resources/ +│ ├── / +│ │ ├── api.js # RPC API client (REQUIRED) +│ │ ├── theme.js # Theme helper (optional) +│ │ └── dashboard.css # Module-specific styles +│ └── view// +│ ├── overview.js # Main dashboard view +│ ├── settings.js # Settings view (if needed) +│ └── *.js # Additional views +└── root/ + ├── etc/config/ # UCI config (optional) + └── usr/ + ├── libexec/rpcd/ + │ └── luci. # RPCD backend (REQUIRED, must be executable) + └── share/ + ├── luci/menu.d/ + │ └── luci-app-.json # Menu definition + └── rpcd/acl.d/ + └── luci-app-.json # ACL permissions +``` + +**Critical Rules:** +1. RPCD script MUST be named `luci.` (with `luci.` prefix) +2. RPCD script MUST be executable (`chmod +x`) +3. Menu paths MUST match view file locations +4. CSS/JS files should be 644 permissions +5. All ubus objects MUST use `luci.` prefix + +--- + +## API Module Template + +**File:** `htdocs/luci-static/resources//api.js` + +```javascript +'use strict'; +'require baseclass'; +'require rpc'; + +/** + * [Module Name] API + * Package: luci-app- + * RPCD object: luci. + * Version: 1.0.0 + */ + +// Debug log to verify correct version is loaded +console.log('🔧 [Module Name] API v1.0.0 loaded at', new Date().toISOString()); + +// ============================================================================ +// RPC Method Declarations +// ============================================================================ + +// Simple method (no parameters) +var callStatus = rpc.declare({ + object: 'luci.', // MUST match RPCD script name + method: 'status', + expect: {} +}); + +// Method with return structure +var callGetData = rpc.declare({ + object: 'luci.', + method: 'get_data', + expect: { data: [] } // Expected return structure +}); + +// Method with parameters +var callPerformAction = rpc.declare({ + object: 'luci.', + method: 'perform_action', + params: ['action_type', 'target'], // Parameter names + expect: { success: false } +}); + +// Method with multiple parameters +var callUpdateConfig = rpc.declare({ + object: 'luci.', + method: 'update_config', + params: ['key', 'value', 'persist'], + expect: {} +}); + +// ============================================================================ +// Helper Functions (Optional) +// ============================================================================ + +/** + * Format bytes to human-readable string + */ +function formatBytes(bytes) { + if (bytes === 0) return '0 B'; + var k = 1024; + var sizes = ['B', 'KB', 'MB', 'GB', 'TB']; + var i = Math.floor(Math.log(bytes) / Math.log(k)); + return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]; +} + +/** + * Format timestamp to "X ago" string + */ +function formatTimeAgo(timestamp) { + if (!timestamp) return 'Never'; + var now = Math.floor(Date.now() / 1000); + var diff = now - timestamp; + if (diff < 60) return diff + 's ago'; + if (diff < 3600) return Math.floor(diff / 60) + 'm ago'; + if (diff < 86400) return Math.floor(diff / 3600) + 'h ago'; + return Math.floor(diff / 86400) + 'd ago'; +} + +/** + * Format uptime seconds to "Xd Xh Xm" string + */ +function formatUptime(seconds) { + var days = Math.floor(seconds / 86400); + var hours = Math.floor((seconds % 86400) / 3600); + var mins = Math.floor((seconds % 3600) / 60); + return days + 'd ' + hours + 'h ' + mins + 'm'; +} + +// ============================================================================ +// API Export +// ============================================================================ + +return baseclass.extend({ + // RPC methods - exposed via ubus + getStatus: callStatus, + getData: callGetData, + performAction: callPerformAction, + updateConfig: callUpdateConfig, + + // Helper functions + formatBytes: formatBytes, + formatTimeAgo: formatTimeAgo, + formatUptime: formatUptime, + + // Aggregate function for overview page (combines multiple calls) + getAllData: function() { + return Promise.all([ + callStatus(), + callGetData() + ]).then(function(results) { + return { + status: results[0] || {}, + data: results[1] || { data: [] } + }; + }); + } +}); +``` + +**Key Points:** +- Always use `'use strict';` +- Require `baseclass` and `rpc` +- Use `rpc.declare()` for each RPCD method +- Export from `baseclass.extend()` +- Helper functions can be included in the API module +- Aggregate functions are useful for views that need multiple data sources + +--- + +## JavaScript View Template + +**File:** `htdocs/luci-static/resources/view//overview.js` + +```javascript +'use strict'; +'require view'; +'require ui'; +'require dom'; +'require poll'; +'require /api as API'; + +/** + * [Module Name] - Overview Dashboard + * Main view for luci-app- + */ + +return view.extend({ + // ======================================================================== + // Data Properties + // ======================================================================== + + statusData: null, + componentData: null, + + // ======================================================================== + // Load Data + // ======================================================================== + + /** + * Called when view is loaded + * Return a Promise (can use Promise.all for parallel loading) + */ + load: function() { + return Promise.all([ + API.getStatus(), + API.getData() + ]); + }, + + // ======================================================================== + // Render View + // ======================================================================== + + /** + * Called after load() completes + * @param {Array} data - Results from load() Promise.all + */ + render: function(data) { + var self = this; + this.statusData = data[0] || {}; + this.componentData = data[1] || { data: [] }; + + // Main container + var container = E('div', { 'class': 'module-dashboard' }, [ + // Load CSS + E('link', { 'rel': 'stylesheet', 'href': L.resource('/dashboard.css') }), + + // Page Header + this.renderHeader(), + + // Stats Overview Grid + this.renderStatsOverview(), + + // Content Cards + this.renderContent() + ]); + + // Setup auto-refresh polling (30 seconds) + poll.add(L.bind(function() { + return Promise.all([ + API.getStatus(), + API.getData() + ]).then(L.bind(function(refreshData) { + this.statusData = refreshData[0] || {}; + this.componentData = refreshData[1] || { data: [] }; + this.updateDashboard(); + }, this)); + }, this), 30); + + return container; + }, + + // ======================================================================== + // Render Components + // ======================================================================== + + /** + * Render page header with title and stats badges + */ + renderHeader: function() { + return E('div', { 'class': 'sh-page-header' }, [ + E('div', {}, [ + E('h2', { 'class': 'sh-page-title' }, [ + E('span', { 'class': 'sh-page-title-icon' }, '🚀'), + 'Module Title' + ]), + E('p', { 'class': 'sh-page-subtitle' }, 'Module description and purpose') + ]), + E('div', { 'class': 'sh-stats-grid' }, [ + this.renderStatBadge('Active Items', this.statusData.active || 0), + this.renderStatBadge('Total Items', this.statusData.total || 0), + this.renderStatBadge('Status', this.statusData.status || 'Unknown'), + this.renderStatBadge('Version', this.statusData.version || '1.0.0') + ]) + ]); + }, + + /** + * Render a single stat badge + */ + renderStatBadge: function(label, value) { + return E('div', { 'class': 'sh-stat-badge' }, [ + E('div', { 'class': 'sh-stat-value' }, String(value)), + E('div', { 'class': 'sh-stat-label' }, label) + ]); + }, + + /** + * Render stats overview grid + */ + renderStatsOverview: function() { + return E('div', { 'class': 'stats-grid' }, [ + this.renderMetricCard('CPU', this.statusData.cpu), + this.renderMetricCard('Memory', this.statusData.memory), + this.renderMetricCard('Disk', this.statusData.disk) + ]); + }, + + /** + * Render a metric card with progress bar + */ + renderMetricCard: function(title, data) { + if (!data) return E('div'); + + var usage = data.usage || 0; + var status = usage >= 90 ? 'critical' : (usage >= 75 ? 'warning' : 'ok'); + var color = usage >= 90 ? '#ef4444' : (usage >= 75 ? '#f59e0b' : '#22c55e'); + + return E('div', { 'class': 'sh-metric-card sh-metric-' + status }, [ + E('div', { 'class': 'sh-metric-header' }, [ + E('span', { 'class': 'sh-metric-icon' }, this.getMetricIcon(title)), + E('span', { 'class': 'sh-metric-title' }, title) + ]), + E('div', { 'class': 'sh-metric-value' }, usage + '%'), + E('div', { 'class': 'sh-metric-progress' }, [ + E('div', { + 'class': 'sh-metric-progress-bar', + 'style': 'width: ' + usage + '%; background: ' + color + }) + ]), + E('div', { 'class': 'sh-metric-details' }, data.details || 'N/A') + ]); + }, + + /** + * Get icon for metric type + */ + getMetricIcon: function(type) { + switch(type) { + case 'CPU': return '🔥'; + case 'Memory': return '💾'; + case 'Disk': return '💿'; + default: return '📊'; + } + }, + + /** + * Render main content + */ + renderContent: function() { + return E('div', { 'class': 'content-grid' }, [ + this.renderCard('Active Components', this.renderComponentsList()), + this.renderCard('Quick Actions', this.renderQuickActions()), + this.renderCard('Recent Activity', this.renderActivityLog()) + ]); + }, + + /** + * Render a card container + */ + renderCard: function(title, content) { + return E('div', { 'class': 'sh-card' }, [ + E('div', { 'class': 'sh-card-header' }, [ + E('h3', { 'class': 'sh-card-title' }, title) + ]), + E('div', { 'class': 'sh-card-body' }, content) + ]); + }, + + /** + * Render components list + */ + renderComponentsList: function() { + var items = this.componentData.data || []; + + if (items.length === 0) { + return E('div', { 'class': 'sh-empty-state' }, [ + E('div', { 'class': 'sh-empty-icon' }, '📭'), + E('div', { 'class': 'sh-empty-text' }, 'No components found') + ]); + } + + return E('div', { 'class': 'component-list' }, + items.map(L.bind(function(item) { + return this.renderComponentItem(item); + }, this)) + ); + }, + + /** + * Render a single component item + */ + renderComponentItem: function(item) { + var statusClass = item.status === 'active' ? 'sh-card-success' : 'sh-card-warning'; + + return E('div', { 'class': 'component-item ' + statusClass }, [ + E('div', { 'class': 'component-name' }, item.name || 'Unknown'), + E('div', { 'class': 'component-status' }, item.status || 'unknown'), + E('div', { 'class': 'component-actions' }, [ + E('button', { + 'class': 'sh-btn sh-btn-primary sh-btn-sm', + 'click': L.bind(this.handleAction, this, item.id, 'view') + }, 'View'), + E('button', { + 'class': 'sh-btn sh-btn-secondary sh-btn-sm', + 'click': L.bind(this.handleAction, this, item.id, 'configure') + }, 'Configure') + ]) + ]); + }, + + /** + * Render quick actions + */ + renderQuickActions: function() { + return E('div', { 'class': 'quick-actions' }, [ + E('button', { + 'class': 'sh-btn sh-btn-primary', + 'click': L.bind(this.handleRefresh, this) + }, '🔄 Refresh'), + E('button', { + 'class': 'sh-btn sh-btn-success', + 'click': L.bind(this.handleAction, this, null, 'start_all') + }, '▶️ Start All'), + E('button', { + 'class': 'sh-btn sh-btn-danger', + 'click': L.bind(this.handleAction, this, null, 'stop_all') + }, '⏹️ Stop All') + ]); + }, + + /** + * Render activity log + */ + renderActivityLog: function() { + var activities = this.statusData.recent_activities || []; + + if (activities.length === 0) { + return E('div', { 'class': 'sh-empty-text' }, 'No recent activity'); + } + + return E('div', { 'class': 'activity-log' }, + activities.map(function(activity) { + return E('div', { 'class': 'activity-item' }, [ + E('span', { 'class': 'activity-time' }, activity.time || ''), + E('span', { 'class': 'activity-text' }, activity.message || '') + ]); + }) + ); + }, + + // ======================================================================== + // Event Handlers + // ======================================================================== + + /** + * Handle generic action + */ + handleAction: function(id, action, ev) { + var self = this; + + ui.showModal(_('Performing Action'), [ + E('p', {}, _('Please wait...')) + ]); + + API.performAction(action, id || '').then(function(result) { + ui.hideModal(); + + if (result.success) { + ui.addNotification(null, E('p', _('Action completed successfully')), 'success'); + self.handleRefresh(); + } else { + ui.addNotification(null, E('p', _('Action failed: %s').format(result.message || 'Unknown error')), 'error'); + } + }).catch(function(error) { + ui.hideModal(); + ui.addNotification(null, E('p', _('Error: %s').format(error.message || 'Unknown error')), 'error'); + }); + }, + + /** + * Handle refresh + */ + handleRefresh: function() { + var self = this; + + return Promise.all([ + API.getStatus(), + API.getData() + ]).then(function(data) { + self.statusData = data[0] || {}; + self.componentData = data[1] || { data: [] }; + self.updateDashboard(); + ui.addNotification(null, E('p', _('Dashboard refreshed')), 'info'); + }); + }, + + /** + * Update dashboard without full re-render + */ + updateDashboard: function() { + // Update specific DOM elements instead of full re-render + var statsGrid = document.querySelector('.sh-stats-grid'); + if (statsGrid) { + dom.content(statsGrid, [ + this.renderStatBadge('Active Items', this.statusData.active || 0), + this.renderStatBadge('Total Items', this.statusData.total || 0), + this.renderStatBadge('Status', this.statusData.status || 'Unknown'), + this.renderStatBadge('Version', this.statusData.version || '1.0.0') + ]); + } + + // Update components list + var componentsList = document.querySelector('.component-list'); + if (componentsList) { + var items = this.componentData.data || []; + dom.content(componentsList, + items.map(L.bind(function(item) { + return this.renderComponentItem(item); + }, this)) + ); + } + }, + + // ======================================================================== + // Required LuCI Methods (can be null if not used) + // ======================================================================== + + handleSaveApply: null, + handleSave: null, + handleReset: null +}); +``` + +**Key Points:** +- Extend `view` with `load()` and `render()` methods +- Use `E()` helper to build DOM elements +- Use `L.bind()` for event handlers to preserve `this` context +- Use `poll.add()` for auto-refresh functionality +- Use `dom.content()` for efficient partial updates +- Use `ui.showModal()`, `ui.hideModal()`, `ui.addNotification()` for user feedback +- Always handle errors in Promise chains + +--- + +## RPCD Backend Template + +**File:** `root/usr/libexec/rpcd/luci.` + +```bash +#!/bin/sh +# [Module Name] RPCD Backend +# Package: luci-app- +# Version: 1.0.0 + +# Source required libraries +. /lib/functions.sh +. /usr/share/libubox/jshn.sh + +# ============================================================================ +# RPC Methods +# ============================================================================ + +# Get status information +status() { + json_init + + # Example: Get system info + local hostname=$(cat /proc/sys/kernel/hostname 2>/dev/null || echo "unknown") + local uptime=$(awk '{print int($1)}' /proc/uptime 2>/dev/null || echo 0) + + json_add_string "hostname" "$hostname" + json_add_int "uptime" "$uptime" + json_add_string "version" "1.0.0" + json_add_string "status" "running" + + # Add nested object + json_add_object "cpu" + local cpu_load=$(awk '{print $1}' /proc/loadavg 2>/dev/null || echo "0") + json_add_string "load" "$cpu_load" + json_add_int "usage" "45" + json_close_object + + # Add timestamp + json_add_string "timestamp" "$(date '+%Y-%m-%d %H:%M:%S')" + + json_dump +} + +# Get data with array +get_data() { + json_init + json_add_array "data" + + # Example: List files + for file in /etc/config/*; do + [ -f "$file" ] || continue + local name=$(basename "$file") + + json_add_object "" + json_add_string "name" "$name" + json_add_string "path" "$file" + json_add_int "size" "$(stat -c%s "$file" 2>/dev/null || echo 0)" + json_close_object + done + + json_close_array + json_dump +} + +# Perform action with parameters +perform_action() { + # Read JSON input from stdin + read -r input + json_load "$input" + + # Extract parameters + local action_type target + json_get_var action_type action_type + json_get_var target target + json_cleanup + + # Validate parameters + if [ -z "$action_type" ]; then + json_init + json_add_boolean "success" 0 + json_add_string "message" "Action type is required" + json_dump + return 1 + fi + + # Perform action based on type + local result=0 + case "$action_type" in + start) + # Example: Start a service + /etc/init.d/"$target" start >/dev/null 2>&1 + result=$? + ;; + stop) + # Example: Stop a service + /etc/init.d/"$target" stop >/dev/null 2>&1 + result=$? + ;; + restart) + # Example: Restart a service + /etc/init.d/"$target" restart >/dev/null 2>&1 + result=$? + ;; + *) + json_init + json_add_boolean "success" 0 + json_add_string "message" "Invalid action: $action_type" + json_dump + return 1 + ;; + esac + + # Return result + json_init + if [ "$result" -eq 0 ]; then + json_add_boolean "success" 1 + json_add_string "message" "Action '$action_type' completed successfully" + else + json_add_boolean "success" 0 + json_add_string "message" "Action '$action_type' failed" + fi + json_dump +} + +# Update configuration +update_config() { + read -r input + json_load "$input" + + local key value persist + json_get_var key key + json_get_var value value + json_get_var persist persist + json_cleanup + + # Validate + if [ -z "$key" ] || [ -z "$value" ]; then + json_init + json_add_boolean "success" 0 + json_add_string "message" "Key and value are required" + json_dump + return 1 + fi + + # Update UCI config + uci set .general."$key"="$value" + + if [ "$persist" = "1" ]; then + uci commit + fi + + json_init + json_add_boolean "success" 1 + json_add_string "message" "Configuration updated" + json_dump +} + +# ============================================================================ +# Main Dispatcher +# ============================================================================ + +case "$1" in + list) + # List all available methods with their parameters + cat << 'EOF' +{ + "status": {}, + "get_data": {}, + "perform_action": { + "action_type": "string", + "target": "string" + }, + "update_config": { + "key": "string", + "value": "string", + "persist": 1 + } +} +EOF + ;; + call) + # Route to the appropriate method + case "$2" in + status) status ;; + get_data) get_data ;; + perform_action) perform_action ;; + update_config) update_config ;; + *) + # Unknown method + json_init + json_add_boolean "success" 0 + json_add_string "error" "Unknown method: $2" + json_dump + ;; + esac + ;; +esac +``` + +**Key Points:** +- Always start with `#!/bin/sh` +- Source `/lib/functions.sh` and `/usr/share/libubox/jshn.sh` +- Use `json_init`, `json_add_*`, `json_dump` for JSON output +- Read parameters from stdin using `read -r input` and `json_load` +- Always validate input parameters +- Return proper success/error status +- Implement `list` case to declare all methods and parameters +- Implement `call` case to route to method handlers + +--- + +## Menu JSON Template + +**File:** `root/usr/share/luci/menu.d/luci-app-.json` + +```json +{ + "admin/secubox//": { + "title": "Module Title", + "order": 10, + "action": { + "type": "firstchild" + }, + "depends": { + "acl": ["luci-app-"] + } + }, + "admin/secubox///overview": { + "title": "Overview", + "order": 1, + "action": { + "type": "view", + "path": "/overview" + } + }, + "admin/secubox///settings": { + "title": "Settings", + "order": 2, + "action": { + "type": "view", + "path": "/settings" + } + } +} +``` + +**Categories:** +- `security` - Security & monitoring modules (CrowdSec, Auth Guardian) +- `monitoring` - Monitoring modules (Netdata) +- `network` - Network modules (Netifyd, Network Modes, WireGuard) +- `system` - System modules (System Hub) +- `services` - Service modules (CDN Cache, VHost Manager) + +**Key Points:** +- Menu paths follow `admin/secubox//` +- First entry uses `"type": "firstchild"` to redirect to first child +- Subsequent entries use `"type": "view"` with `"path"` matching view file location +- Path MUST match: `"path": "/overview"` → `view//overview.js` +- Order determines menu position (lower numbers first) +- Depends on ACL entry matching package name + +--- + +## ACL JSON Template + +**File:** `root/usr/share/rpcd/acl.d/luci-app-.json` + +```json +{ + "luci-app-": { + "description": "Module Title - Brief Description", + "read": { + "ubus": { + "luci.": [ + "status", + "get_data", + "get_config", + "list_items" + ] + }, + "uci": [""] + }, + "write": { + "ubus": { + "luci.": [ + "perform_action", + "update_config", + "delete_item", + "restart_service" + ] + }, + "uci": [""] + } + } +} +``` + +**Key Points:** +- ACL entry name MUST match package name +- `read` section lists methods that can be called without write permissions +- `write` section lists methods that modify state +- ubus object names MUST match RPCD script name (`luci.`) +- UCI config access can be granted separately +- All method names MUST exactly match those defined in RPCD script + +--- + +## CSS Styling Template + +**File:** `htdocs/luci-static/resources//dashboard.css` + +```css +/** + * [Module Name] Dashboard Styles + * Extends system-hub/common.css design system + * Version: 1.0.0 + */ + +/* ============================================================================ + IMPORTANT: Import common.css for design system variables + ============================================================================ */ +@import url('../system-hub/common.css'); + +/* ============================================================================ + Module-Specific Styles + ============================================================================ */ + +/* Container */ +.module-dashboard { + padding: 24px; + background: var(--sh-bg-primary); + min-height: 100vh; +} + +/* Stats Grid */ +.stats-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); + gap: 20px; + margin: 24px 0; +} + +/* Metric Card */ +.sh-metric-card { + background: var(--sh-bg-card); + border: 1px solid var(--sh-border); + border-radius: 16px; + padding: 24px; + transition: all 0.3s ease; + position: relative; + overflow: hidden; +} + +.sh-metric-card::before { + content: ''; + position: absolute; + top: 0; + left: 0; + right: 0; + height: 3px; + background: linear-gradient(90deg, var(--sh-primary), var(--sh-primary-end)); + opacity: 0; + transition: opacity 0.3s ease; +} + +.sh-metric-card:hover { + transform: translateY(-3px); + box-shadow: 0 12px 28px var(--sh-hover-shadow); +} + +.sh-metric-card:hover::before { + opacity: 1; +} + +/* Metric status variants */ +.sh-metric-ok::before { + background: var(--sh-success); + opacity: 1; +} + +.sh-metric-warning::before { + background: var(--sh-warning); + opacity: 1; +} + +.sh-metric-critical::before { + background: var(--sh-danger); + opacity: 1; +} + +/* Metric Header */ +.sh-metric-header { + display: flex; + align-items: center; + gap: 12px; + margin-bottom: 16px; +} + +.sh-metric-icon { + font-size: 28px; + line-height: 1; +} + +.sh-metric-title { + font-size: 16px; + font-weight: 600; + color: var(--sh-text-secondary); +} + +/* Metric Value */ +.sh-metric-value { + font-size: 40px; + font-weight: 700; + font-family: 'JetBrains Mono', monospace; + color: var(--sh-text-primary); + margin-bottom: 12px; +} + +/* Metric Progress Bar */ +.sh-metric-progress { + width: 100%; + height: 8px; + background: var(--sh-bg-tertiary); + border-radius: 4px; + overflow: hidden; + margin-bottom: 8px; +} + +.sh-metric-progress-bar { + height: 100%; + background: var(--sh-primary); + transition: width 0.5s ease; + border-radius: 4px; +} + +/* Metric Details */ +.sh-metric-details { + font-size: 14px; + color: var(--sh-text-secondary); + font-weight: 500; +} + +/* Content Grid */ +.content-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(350px, 1fr)); + gap: 24px; + margin-top: 24px; +} + +/* Component List */ +.component-list { + display: flex; + flex-direction: column; + gap: 12px; +} + +.component-item { + display: flex; + align-items: center; + justify-content: space-between; + padding: 16px; + background: var(--sh-bg-secondary); + border: 1px solid var(--sh-border); + border-radius: 12px; + transition: all 0.2s ease; + position: relative; + overflow: hidden; +} + +.component-item::before { + content: ''; + position: absolute; + top: 0; + left: 0; + right: 0; + height: 3px; + background: var(--sh-primary); + opacity: 0; + transition: opacity 0.3s ease; +} + +.component-item:hover { + transform: translateX(4px); + border-color: var(--sh-primary); +} + +.component-item:hover::before { + opacity: 1; +} + +.component-name { + font-size: 16px; + font-weight: 600; + color: var(--sh-text-primary); + flex: 1; +} + +.component-status { + font-size: 14px; + color: var(--sh-text-secondary); + margin: 0 16px; +} + +.component-actions { + display: flex; + gap: 8px; +} + +/* Quick Actions */ +.quick-actions { + display: flex; + flex-wrap: wrap; + gap: 12px; +} + +/* Activity Log */ +.activity-log { + display: flex; + flex-direction: column; + gap: 12px; +} + +.activity-item { + display: flex; + align-items: center; + gap: 12px; + padding: 12px; + background: var(--sh-bg-secondary); + border-radius: 8px; + font-size: 14px; +} + +.activity-time { + font-family: 'JetBrains Mono', monospace; + color: var(--sh-text-secondary); + font-size: 12px; + min-width: 80px; +} + +.activity-text { + color: var(--sh-text-primary); + flex: 1; +} + +/* ============================================================================ + Button Variants (Small Size) + ============================================================================ */ + +.sh-btn-sm { + padding: 6px 12px; + font-size: 12px; +} + +/* ============================================================================ + Responsive Design + ============================================================================ */ + +@media (max-width: 768px) { + .module-dashboard { + padding: 16px; + } + + .stats-grid, + .content-grid { + grid-template-columns: 1fr; + } + + .component-item { + flex-direction: column; + align-items: flex-start; + gap: 12px; + } + + .component-actions { + width: 100%; + } + + .sh-metric-value { + font-size: 32px; + } +} + +/* ============================================================================ + Dark Mode Enhancements + ============================================================================ */ + +[data-theme="dark"] .module-dashboard { + background: var(--sh-bg-primary); +} + +[data-theme="dark"] .component-item, +[data-theme="dark"] .activity-item { + background: var(--sh-bg-secondary); + border-color: var(--sh-border); +} + +[data-theme="dark"] .component-item:hover { + background: var(--sh-bg-tertiary); +} +``` + +**Key Points:** +- Always import `system-hub/common.css` for design system variables +- Use CSS variables (`var(--sh-*)`) instead of hardcoded colors +- Support dark mode with `[data-theme="dark"]` selectors +- Use responsive grid layouts (`grid-template-columns: repeat(auto-fit, minmax(...))`) +- Add smooth transitions for better UX +- Use JetBrains Mono for numeric values +- Follow mobile-first responsive design + +--- + +## Complete Implementation Example + +Here's a complete minimal working example for a new module called "Example Dashboard": + +### Directory Structure +``` +luci-app-example-dashboard/ +├── Makefile +├── htdocs/luci-static/resources/ +│ ├── example-dashboard/ +│ │ ├── api.js +│ │ └── dashboard.css +│ └── view/example-dashboard/ +│ └── overview.js +└── root/ + └── usr/ + ├── libexec/rpcd/ + │ └── luci.example-dashboard + └── share/ + ├── luci/menu.d/ + │ └── luci-app-example-dashboard.json + └── rpcd/acl.d/ + └── luci-app-example-dashboard.json +``` + +### api.js +```javascript +'use strict'; +'require baseclass'; +'require rpc'; + +var callStatus = rpc.declare({ + object: 'luci.example-dashboard', + method: 'status', + expect: {} +}); + +return baseclass.extend({ + getStatus: callStatus +}); +``` + +### overview.js +```javascript +'use strict'; +'require view'; +'require example-dashboard/api as API'; + +return view.extend({ + load: function() { + return API.getStatus(); + }, + + render: function(data) { + return E('div', {}, [ + E('link', { 'rel': 'stylesheet', 'href': L.resource('example-dashboard/dashboard.css') }), + E('h2', {}, 'Example Dashboard'), + E('p', {}, 'Status: ' + (data.status || 'Unknown')) + ]); + }, + + handleSaveApply: null, + handleSave: null, + handleReset: null +}); +``` + +### luci.example-dashboard (RPCD) +```bash +#!/bin/sh +. /usr/share/libubox/jshn.sh + +status() { + json_init + json_add_string "status" "running" + json_add_string "version" "1.0.0" + json_dump +} + +case "$1" in + list) + echo '{"status":{}}' + ;; + call) + case "$2" in + status) status ;; + esac + ;; +esac +``` + +### menu.d/luci-app-example-dashboard.json +```json +{ + "admin/secubox/monitoring/example-dashboard": { + "title": "Example Dashboard", + "order": 50, + "action": { + "type": "firstchild" + }, + "depends": { + "acl": ["luci-app-example-dashboard"] + } + }, + "admin/secubox/monitoring/example-dashboard/overview": { + "title": "Overview", + "order": 1, + "action": { + "type": "view", + "path": "example-dashboard/overview" + } + } +} +``` + +### acl.d/luci-app-example-dashboard.json +```json +{ + "luci-app-example-dashboard": { + "description": "Example Dashboard", + "read": { + "ubus": { + "luci.example-dashboard": ["status"] + } + } + } +} +``` + +### dashboard.css +```css +@import url('../system-hub/common.css'); + +div { + padding: 20px; +} +``` + +**Installation Steps:** +1. Copy files to module directory +2. Set RPCD permissions: `chmod +x root/usr/libexec/rpcd/luci.example-dashboard` +3. Validate: `./secubox-tools/validate-modules.sh` +4. Build: `./secubox-tools/local-build.sh build luci-app-example-dashboard` +5. Deploy: `scp build/x86-64/*.ipk root@router:/tmp/` +6. Install: `ssh root@router "opkg install /tmp/luci-app-example-dashboard*.ipk && /etc/init.d/rpcd restart"` + +--- + +## Common Pitfalls and Solutions + +### 1. RPCD "Object not found" Error +**Error:** `RPC call to luci.example-dashboard/status failed with error -32000: Object not found` + +**Solutions:** +- Check RPCD script name matches ubus object name exactly (including `luci.` prefix) +- Verify RPCD script is executable: `chmod +x root/usr/libexec/rpcd/luci.example-dashboard` +- Restart RPCD service: `/etc/init.d/rpcd restart` +- Check RPCD logs: `logread | grep rpcd` + +### 2. HTTP 404 View Not Found +**Error:** `HTTP error 404 while loading class file '/luci-static/resources/view/example-dashboard/overview.js'` + +**Solutions:** +- Verify menu path matches view file location exactly +- Menu: `"path": "example-dashboard/overview"` → File: `view/example-dashboard/overview.js` +- Check file permissions: `644` for CSS/JS files +- Clear browser cache + +### 3. ACL Permission Denied +**Error:** Access denied or missing permissions + +**Solutions:** +- Verify ACL file exists in `root/usr/share/rpcd/acl.d/` +- Check ubus object name in ACL matches RPCD script name +- Restart RPCD: `/etc/init.d/rpcd restart` +- Check method is listed in appropriate section (read vs write) + +### 4. CSS Not Loading +**Problem:** Styles not applied + +**Solutions:** +- Verify CSS import path: `L.resource('example-dashboard/dashboard.css')` +- Check file permissions: `644` +- Import common.css: `@import url('../system-hub/common.css');` +- Clear browser cache +- Check browser console for 404 errors + +### 5. Auto-Refresh Not Working +**Problem:** Poll not updating dashboard + +**Solutions:** +- Verify poll.add() is called in render() method +- Check API calls in poll callback return Promises +- Ensure updateDashboard() method updates DOM correctly +- Use browser console to check for JavaScript errors + +--- + +## Validation Checklist + +Before deploying, always run these checks: + +```bash +# 1. Fix permissions +./secubox-tools/fix-permissions.sh --local + +# 2. Validate module structure +./secubox-tools/validate-modules.sh + +# 3. Validate JSON syntax +find luci-app-example-dashboard -name "*.json" -exec jsonlint {} \; + +# 4. Validate shell scripts +shellcheck luci-app-example-dashboard/root/usr/libexec/rpcd/* + +# 5. Build locally +./secubox-tools/local-build.sh build luci-app-example-dashboard +``` + +--- + +**Document Version:** 1.0.0 +**Last Updated:** 2025-12-27 +**Maintainer:** CyberMind.fr diff --git a/DOCUMENTATION-INDEX.md b/DOCUMENTATION-INDEX.md new file mode 100644 index 00000000..3d032274 --- /dev/null +++ b/DOCUMENTATION-INDEX.md @@ -0,0 +1,367 @@ +# SecuBox Documentation Index + +**Version:** 1.0.0 +**Date:** 2025-12-27 +**Complete Documentation for SecuBox OpenWrt Project** + +--- + +## 📖 Documentation Overview + +This index provides quick access to all SecuBox documentation. Choose the document that matches your needs: + +--- + +## 🚀 Getting Started + +### For New Contributors +1. Start with **[QUICK-START.md](./QUICK-START.md)** - Essential rules and commands +2. Read **[DEVELOPMENT-GUIDELINES.md](./DEVELOPMENT-GUIDELINES.md)** - Complete development guide +3. Review **[CLAUDE.md](./CLAUDE.md)** - Build system and architecture + +### For AI-Assisted Development +1. Use **[MODULE-IMPLEMENTATION-GUIDE.md](./MODULE-IMPLEMENTATION-GUIDE.md)** - Step-by-step workflow +2. Copy prompts from **[FEATURE-REGENERATION-PROMPTS.md](./FEATURE-REGENERATION-PROMPTS.md)** +3. Reference **[CODE-TEMPLATES.md](./CODE-TEMPLATES.md)** for implementation patterns + +### For Existing Module Modification +1. Check **[QUICK-START.md](./QUICK-START.md)** - Quick fixes and common commands +2. Run validation: `./secubox-tools/validate-modules.sh` +3. Review **[DEVELOPMENT-GUIDELINES.md](./DEVELOPMENT-GUIDELINES.md)** for specific topics + +--- + +## 📚 Document Descriptions + +### 1. Quick Reference Documents + +#### **QUICK-START.md** ⚡ +*Quick reference for common tasks - Read this first!* + +**Contents:** +- Critical naming rules (RPCD, menu paths, permissions) +- Design system essentials (colors, fonts, CSS classes) +- Common commands (validation, build, deploy, debug) +- Quick code templates (RPCD, View, Headers, Cards) +- Error quick fixes + +**When to use:** Daily development, quick lookups, debugging + +--- + +#### **README.md** 📋 +*Project overview and compatibility matrix* + +**Contents:** +- Project description and features +- OpenWrt version compatibility (24.10.x, 25.12.0-rc1, etc.) +- Package format support (.ipk vs .apk) +- Installation instructions +- Module categories and descriptions + +**When to use:** Project overview, version compatibility checks + +--- + +### 2. Complete Reference Documents + +#### **DEVELOPMENT-GUIDELINES.md** ⭐ +*Complete development guide - The definitive reference* + +**Contents:** +- **Design System**: Color palettes, typography, component library +- **Architecture**: File structure, naming conventions, RPCD patterns +- **Best Practices**: RPCD, ubus, ACL, JavaScript, CSS standards +- **Common Errors**: Diagnostics and solutions for typical issues +- **Validation**: Pre-commit, pre-deploy, post-deploy checklists +- **Deployment**: Step-by-step deployment procedures + +**When to use:** Detailed technical questions, design decisions, troubleshooting + +**Size:** Comprehensive (~500+ lines) + +--- + +#### **CLAUDE.md** 🏗️ +*Build system, architecture, and CI/CD reference* + +**Contents:** +- OpenWrt SDK build commands +- Package testing procedures +- Validation tools and workflows +- LuCI package structure +- Frontend-backend communication +- Critical naming conventions +- CI/CD integration (GitHub Actions) +- Common issues and solutions + +**When to use:** Build issues, CI/CD workflows, architecture questions + +--- + +### 3. Implementation & Regeneration Documents + +#### **MODULE-IMPLEMENTATION-GUIDE.md** 🎯 +*Master guide for implementing/regenerating modules* + +**Contents:** +- Step-by-step workflow for regenerating modules +- How to use Claude.ai for code generation +- Complete implementation example (from prompt to deployment) +- Common implementation patterns (multi-tab dashboards, filters, forms) +- Module-specific notes (System Hub, WireGuard, CrowdSec, etc.) +- Troubleshooting guide with solutions +- Best practices (code organization, error handling, performance, UX) +- Deployment checklist + +**When to use:** Implementing new modules, regenerating existing modules, using AI assistance + +**Size:** Comprehensive guide (~800+ lines) + +--- + +#### **FEATURE-REGENERATION-PROMPTS.md** 💬 +*Ready-to-use prompts for all 15 SecuBox modules* + +**Contents:** +- Design system reference (CSS variables, typography, components) +- Complete prompts for all 15 modules: + 1. SecuBox Central Hub + 2. System Hub (9 tabs) + 3. CrowdSec Dashboard + 4. Netdata Dashboard + 5. Netifyd Dashboard + 6. Network Modes + 7. WireGuard Dashboard + 8. Client Guardian + 9. Auth Guardian + 10. Bandwidth Manager + 11. Traffic Shaper + 12. Media Flow + 13. CDN Cache + 14. VHost Manager + 15. KSM Manager +- Common UI patterns across all modules +- Usage instructions for Claude.ai + +**When to use:** Getting AI to generate module code, understanding module requirements + +**Size:** Extensive (~2000+ lines) + +--- + +#### **CODE-TEMPLATES.md** 💻 +*Working code templates extracted from production modules* + +**Contents:** +- File structure template +- API module template (api.js) +- JavaScript view template (overview.js) +- RPCD backend template (shell script) +- Menu JSON template +- ACL JSON template +- CSS styling template +- Complete minimal working example +- Common pitfalls and solutions +- Validation checklist + +**When to use:** Manual implementation, understanding patterns, copying boilerplate code + +**Size:** Detailed templates (~1200+ lines) + +--- + +### 4. Tools & Scripts Documentation + +#### **secubox-tools/README.md** 🔧 +*Documentation for validation and build tools* + +**Contents:** +- Tool descriptions (validate-modules.sh, local-build.sh, etc.) +- Usage examples for each tool +- Supported architectures and devices +- Package building workflows +- Firmware building workflows +- Validation checks (7 automated checks) +- Recommended workflows +- Common fixes + +**When to use:** Using validation tools, local builds, firmware generation + +--- + +### 5. Live Demo & Examples + +#### **Live Demo Website** 🌐 +*Production demo of all modules* + +**URL:** https://secubox.cybermood.eu + +**Available Demos:** +- Main dashboard: `/` +- System Hub: `/system-hub` +- CrowdSec: `/crowdsec` +- WireGuard: `/wireguard` +- All 15 modules accessible + +**When to use:** Visual reference, understanding UI/UX, testing features + +--- + +## 🎯 Quick Lookup by Task + +### I want to... + +#### ...create a new module from scratch +1. Read: **MODULE-IMPLEMENTATION-GUIDE.md** (Step-by-step workflow) +2. Copy prompt from: **FEATURE-REGENERATION-PROMPTS.md** +3. Use templates from: **CODE-TEMPLATES.md** +4. Validate with: `./secubox-tools/validate-modules.sh` + +#### ...regenerate an existing module +1. Read: **MODULE-IMPLEMENTATION-GUIDE.md** (Section: "Step-by-Step: Regenerate a Module with Claude.ai") +2. Copy module specification from: **FEATURE-REGENERATION-PROMPTS.md** +3. Use Claude.ai or copy templates from: **CODE-TEMPLATES.md** +4. Validate and deploy following: **MODULE-IMPLEMENTATION-GUIDE.md** + +#### ...fix RPCD "Object not found" error +1. Quick fix: **QUICK-START.md** (Error Quick Fixes section) +2. Detailed troubleshooting: **DEVELOPMENT-GUIDELINES.md** (Common Errors section) +3. Or: **MODULE-IMPLEMENTATION-GUIDE.md** (Troubleshooting Guide) + +#### ...understand the design system +1. Quick reference: **QUICK-START.md** (Design System Essentials) +2. Complete guide: **DEVELOPMENT-GUIDELINES.md** (Design System & UI Guidelines) +3. See live examples: **https://secubox.cybermood.eu** + +#### ...build packages locally +1. Quick commands: **QUICK-START.md** (Build & Deploy section) +2. Complete guide: **secubox-tools/README.md** +3. Architecture details: **CLAUDE.md** (Build Commands section) + +#### ...validate my changes before commit +1. Run: `./secubox-tools/fix-permissions.sh --local` +2. Run: `./secubox-tools/validate-modules.sh` +3. Review checklist: **DEVELOPMENT-GUIDELINES.md** (Validation Checklist) + +#### ...understand menu and ACL configuration +1. Quick templates: **CODE-TEMPLATES.md** (Menu JSON Template, ACL JSON Template) +2. Detailed guide: **DEVELOPMENT-GUIDELINES.md** (Architecture & Naming Conventions) +3. Working examples: Look in any `luci-app-*/root/usr/share/` directory + +#### ...deploy to test router +1. Quick commands: **QUICK-START.md** (Common Commands) +2. Step-by-step: **MODULE-IMPLEMENTATION-GUIDE.md** (Deploy to Test Router section) +3. Fix permissions after deploy: `./secubox-tools/fix-permissions.sh --remote` + +#### ...understand CSS variable system +1. Quick reference: **QUICK-START.md** (CSS Variables section) +2. Complete guide: **DEVELOPMENT-GUIDELINES.md** (CSS/Styling Standards) +3. Template: **CODE-TEMPLATES.md** (CSS Styling Template) +4. Live CSS: `luci-app-system-hub/htdocs/luci-static/resources/system-hub/common.css` + +#### ...write RPCD backend script +1. Template: **CODE-TEMPLATES.md** (RPCD Backend Template) +2. Best practices: **DEVELOPMENT-GUIDELINES.md** (RPCD & ubus Best Practices) +3. Working examples: Look in any `luci-app-*/root/usr/libexec/rpcd/` directory + +#### ...create multi-tab dashboard +1. Pattern: **MODULE-IMPLEMENTATION-GUIDE.md** (Pattern 1: Multi-Tab Dashboard) +2. Example: See `luci-app-system-hub` (9 tabs) +3. Live demo: https://secubox.cybermood.eu/system-hub + +--- + +## 📊 Documentation Comparison Matrix + +| Document | Size | Scope | Use Case | Audience | +|----------|------|-------|----------|----------| +| **QUICK-START.md** | Small | Quick reference | Daily development | All developers | +| **README.md** | Small | Project overview | First introduction | New contributors | +| **DEVELOPMENT-GUIDELINES.md** | Large | Complete reference | Detailed questions | All developers | +| **CLAUDE.md** | Medium | Build & architecture | Build/CI/CD issues | Developers, DevOps | +| **MODULE-IMPLEMENTATION-GUIDE.md** | Large | Implementation workflow | Module creation | AI-assisted dev | +| **FEATURE-REGENERATION-PROMPTS.md** | Very Large | Module specifications | AI prompts | AI-assisted dev | +| **CODE-TEMPLATES.md** | Large | Code templates | Manual coding | Developers | +| **secubox-tools/README.md** | Medium | Tools documentation | Tool usage | Developers, DevOps | + +--- + +## 🔄 Documentation Update Workflow + +When making changes to the codebase: + +1. **Update code** in module files +2. **Run validation**: `./secubox-tools/validate-modules.sh` +3. **Update documentation** if: + - New pattern introduced → Add to **CODE-TEMPLATES.md** + - New design guideline → Update **DEVELOPMENT-GUIDELINES.md** + - New common error → Add to **QUICK-START.md** and **DEVELOPMENT-GUIDELINES.md** + - New module → Add to **FEATURE-REGENERATION-PROMPTS.md** + - New build feature → Update **CLAUDE.md** and **secubox-tools/README.md** +4. **Update version** and date in modified documents +5. **Commit** documentation along with code changes + +--- + +## 📞 Support & Contact + +- **Documentation Issues:** Create issue at [GitHub Issues](https://github.com/anthropics/claude-code/issues) +- **Technical Support:** support@cybermind.fr +- **Live Demo:** https://secubox.cybermood.eu +- **Company:** CyberMind.fr + +--- + +## 🎓 Learning Path + +### Beginner (New to SecuBox) +1. Day 1: Read **README.md** + **QUICK-START.md** +2. Day 2: Skim **DEVELOPMENT-GUIDELINES.md** (focus on Design System and Architecture) +3. Day 3: Follow **MODULE-IMPLEMENTATION-GUIDE.md** to implement a simple module +4. Day 4: Study existing modules (start with `luci-app-cdn-cache` - simplest) +5. Day 5: Make your first contribution + +### Intermediate (Familiar with OpenWrt/LuCI) +1. Read **DEVELOPMENT-GUIDELINES.md** (full document) +2. Review **CODE-TEMPLATES.md** for patterns +3. Use **FEATURE-REGENERATION-PROMPTS.md** with Claude.ai to generate a module +4. Study **CLAUDE.md** for build system details +5. Contribute new modules or enhance existing ones + +### Advanced (Ready for Complex Modules) +1. Study complex modules: System Hub, Network Modes +2. Read all documentation for comprehensive understanding +3. Use **MODULE-IMPLEMENTATION-GUIDE.md** patterns for advanced features +4. Contribute to core design system and tools +5. Help with documentation improvements + +--- + +## 📝 Version History + +| Version | Date | Changes | +|---------|------|---------| +| 1.0.0 | 2025-12-27 | Initial comprehensive documentation release | +| | | - Created FEATURE-REGENERATION-PROMPTS.md (15 modules) | +| | | - Created CODE-TEMPLATES.md (complete templates) | +| | | - Created MODULE-IMPLEMENTATION-GUIDE.md (master guide) | +| | | - Created DOCUMENTATION-INDEX.md (this file) | +| | | - Enhanced existing documentation | + +--- + +## 🏆 Documentation Quality Goals + +- **Completeness:** All aspects of SecuBox development covered +- **Accuracy:** Code examples tested and working +- **Clarity:** Clear explanations with examples +- **Maintainability:** Easy to update as codebase evolves +- **Accessibility:** Multiple entry points for different use cases +- **AI-Friendly:** Structured for AI-assisted development + +--- + +**Last Updated:** 2025-12-27 +**Maintainer:** CyberMind.fr +**License:** Apache-2.0 diff --git a/FEATURE-REGENERATION-PROMPTS.md b/FEATURE-REGENERATION-PROMPTS.md new file mode 100644 index 00000000..adae0e3d --- /dev/null +++ b/FEATURE-REGENERATION-PROMPTS.md @@ -0,0 +1,2074 @@ +# SecuBox Feature Regeneration Prompts + +**Version:** 1.0.0 +**Date:** 2025-12-27 +**Purpose:** Comprehensive prompts for Claude.ai to regenerate all SecuBox module features matching the live demo at secubox.cybermood.eu + +--- + +## Table of Contents + +1. [Design System Reference](#design-system-reference) +2. [Core Modules Prompts](#core-modules-prompts) +3. [Security & Monitoring Modules](#security--monitoring-modules) +4. [Network Intelligence Modules](#network-intelligence-modules) +5. [VPN & Access Control Modules](#vpn--access-control-modules) +6. [Bandwidth & Traffic Modules](#bandwidth--traffic-modules) +7. [Performance & Services Modules](#performance--services-modules) + +--- + +## Design System Reference + +### Color Palette & Variables +All modules MUST use CSS variables from `system-hub/common.css`: + +**Dark Mode (Primary):** +```css +--sh-bg-primary: #0a0a0f; /* Deep black background */ +--sh-bg-secondary: #12121a; /* Card backgrounds */ +--sh-bg-tertiary: #1a1a24; /* Hover/active states */ +--sh-primary: #6366f1; /* Indigo primary */ +--sh-primary-end: #8b5cf6; /* Violet (gradients) */ +--sh-success: #22c55e; /* Green */ +--sh-danger: #ef4444; /* Red */ +--sh-warning: #f59e0b; /* Orange */ +--sh-text-primary: #fafafa; /* Main text */ +--sh-text-secondary: #a0a0b0; /* Secondary text */ +``` + +### Typography Standards +```css +/* Fonts */ +Inter: Body text, labels, UI elements +JetBrains Mono: Numbers, IDs, code, metrics + +/* Sizes */ +--sh-title-xl: 28px; /* Page titles */ +--sh-title-lg: 20px; /* Card titles */ +--sh-value-xl: 40px; /* Large metrics */ +--sh-value-lg: 32px; /* Stats overview */ +``` + +### Component Patterns +1. **Page Header**: Icon + Title + Subtitle + Stats Grid +2. **Stats Badges**: Monospace values, 130px minimum width +3. **Cards**: 3px top border (gradient or solid color) +4. **Buttons**: Gradient backgrounds, shadow effects, smooth transitions +5. **Filter Tabs**: Gradient for active, icon + label pattern + +--- + +## Core Modules Prompts + +### 1. SecuBox Central Hub (luci-app-secubox) + +**Module Purpose:** Main dashboard and central control panel + +**Prompt for Claude.ai:** + +``` +Create a LuCI dashboard module for SecuBox Central Hub with these features: + +DESIGN REQUIREMENTS: +- Dark theme with gradient backgrounds (#0a0a0f → #12121a) +- Page header with rocket icon 🚀 and title "SecuBox Control Center" +- Stats grid showing: Total Modules (badge), Active Services, System Health, Alerts Count +- Use CSS variables from --sh-* (never hardcode colors) + +MAIN FEATURES: +1. Module Overview Grid + - Display all 15 installed SecuBox modules as cards + - Each card: Module icon, name, status badge (active/inactive), version + - Color-coded borders: green (running), orange (warning), red (stopped) + - "Configure" and "View Details" buttons per card + - Filter tabs: All | Security | Network | Services + +2. System Health Dashboard + - Real-time metrics: CPU, RAM, Disk, Network + - Animated progress bars with gradient fills + - Threshold indicators (warn >80%, danger >90%) + - JetBrains Mono font for all numeric values + +3. Quick Actions Panel + - Restart All Services button (gradient orange) + - Update Packages button (gradient blue) + - View System Logs button (gradient indigo) + - Export Config button (gradient green) + +4. Alert Timeline + - Last 10 system events with timestamps + - Icon indicators for severity levels + - Expandable details per alert + - Auto-refresh every 30 seconds + +TECHNICAL SPECS: +- File: luci-app-secubox/htdocs/luci-static/resources/view/secubox/dashboard.js +- RPCD backend: luci.secubox (methods: getModules, getHealth, getAlerts) +- CSS: luci-app-secubox/htdocs/luci-static/resources/secubox/dashboard.css +- Use L.resolveDefault() for all ubus calls +- Implement proper error handling with user-friendly messages +- Add loading states with skeleton screens + +UI COMPONENTS TO USE: +- sh-page-header for main header +- sh-card with sh-card-success/warning/danger variants +- sh-stat-badge for metrics (130px minimum) +- sh-btn sh-btn-primary for action buttons +- sh-filter-tabs for category filtering + +REFERENCE THE LIVE DEMO: +Match the look and feel of secubox.cybermood.eu demo +- Smooth animations on card hover +- Gradient text effects on titles +- Glow effects on active elements +- Responsive grid (min 280px cards) +``` + +### 2. System Hub (luci-app-system-hub) + +**Module Purpose:** Unified system control center + +**Prompt for Claude.ai:** + +``` +Create a comprehensive System Hub module for OpenWrt with these features: + +DESIGN REQUIREMENTS: +- Use System Hub design system (common.css variables) +- Page title: "System Control Center" with ⚙️ icon +- Multi-tab interface: Overview | Services | Logs | Backup | Components | Diagnostics | Health | Remote | Settings + +OVERVIEW TAB: +1. System Info Grid (4 columns, responsive) + - Hostname card with edit button + - Uptime card with formatted duration + - Load Average card (1m, 5m, 15m) in monospace + - Kernel Version card with copy icon + +2. Resource Monitors (animated progress circles) + - CPU usage with color coding (<70% green, 70-90% orange, >90% red) + - Memory usage with used/total display + - Storage usage with filesystem breakdown + - Network throughput (RX/TX rates in real-time) + +3. Quick Status Indicators + - Internet connectivity (ping test every 60s) + - DNS resolution status + - NTP sync status + - Firewall status with rule count + +SERVICES TAB: +1. Service Cards Grid + - Each service: name, status badge, description, uptime + - Color-coded borders based on status + - Action buttons: Start/Stop/Restart/Enable/Disable + - Filter by: All | Running | Stopped | Enabled | Disabled + - Search bar for filtering services + +2. Service Details Modal + - Full service info (PID, memory usage, CPU time) + - Recent logs (last 50 lines with syntax highlighting) + - Configuration file path with edit link + - Dependencies tree view + +LOGS TAB: +1. System Logs Viewer + - Real-time log streaming (WebSocket or polling) + - Color-coded severity levels (error=red, warn=orange, info=blue) + - Filter by: severity, service, date range + - Search functionality with regex support + - Auto-scroll toggle + - Export logs button (download as .txt) + - Line numbers in monospace + - Compact header mode (saves vertical space) + +2. Log Statistics + - Error count in last hour/day + - Most active services + - Alert frequency chart (sparkline) + +BACKUP TAB: +1. Backup Management + - Create backup button (includes config + installed packages list) + - List existing backups with date, size, description + - Restore from backup with confirmation modal + - Download backup to local machine + - Upload backup from file + - Auto-backup schedule configuration + +2. Backup Preview + - Show included files before creating + - Estimated size calculation + - Compression options (gz, xz) + +COMPONENTS TAB: +1. Installed Packages Display + - Grid of all luci-app-* packages + - Each card: package name, version, size, status + - Category filtering (same as SecuBox modules) + - Dependency information + - Uninstall button with warning + +DIAGNOSTICS TAB: +1. Network Diagnostics + - Ping tool with target input + - Traceroute with hop visualization + - DNS lookup with multiple nameservers + - Port scanner (common ports or custom range) + - Bandwidth test (speedtest-cli integration) + +2. System Diagnostics + - Filesystem check status + - Memory leak detection + - Process list with resource usage + - Open file descriptors count + - Network connections table + +HEALTH TAB: +1. System Health Report + - Overall health score (0-100) with gradient circle + - Critical issues list with fix suggestions + - Temperature sensors (if available) + - Fan speeds (if available) + - SMART disk status + - Battery status (for UPS-backed systems) + +2. Health History + - 24h health score chart (line graph) + - Resource usage trends + - Alert frequency over time + +REMOTE TAB: +1. Remote Access Management + - SSH status with port and allowed IPs + - Web UI access info (HTTP/HTTPS, port, external access) + - RustDesk remote desktop integration + - WireGuard VPN status (if installed) + - Dynamic DNS configuration + +SETTINGS TAB: +1. System Hub Preferences + - Auto-refresh interval (10s/30s/60s/disabled) + - Dark/Light mode toggle + - Compact mode toggle + - Language selection + - Timezone configuration + - Dashboard layout customization + +TECHNICAL IMPLEMENTATION: +- Files: system-hub/overview.js, services.js, logs.js, backup.js, components.js, diagnostics.js, health.js, remote.js, settings.js +- RPCD: luci.system-hub with methods for each feature +- API file: system-hub/api.js with clean method wrappers +- CSS: system-hub/dashboard.css + common.css +- Use theme.js for dark/light mode switching +- WebSocket support for real-time log streaming +- LocalStorage for user preferences +- Proper loading states and error handling + +REFERENCE DEMO: +Match secubox.cybermood.eu/system-hub demo +- Smooth tab transitions +- Real-time data updates +- Responsive grid layouts +- Professional color coding +``` + +--- + +## Security & Monitoring Modules + +### 3. CrowdSec Dashboard (luci-app-crowdsec-dashboard) + +**Prompt for Claude.ai:** + +``` +Create a CrowdSec security monitoring dashboard for OpenWrt: + +DESIGN: +- Title: "CrowdSec Security" with 🛡️ icon +- Dark theme with emphasis on threat indicators +- Stats badges: Active Decisions | Blocked IPs | Alerts | Bouncers + +OVERVIEW TAB: +1. Threat Intelligence Summary + - Total decisions count (15M+ IPs blocked globally reference) + - Active local decisions with expiry countdown + - Decision types breakdown (ban, captcha, throttle) as pie chart + - Country distribution of threats (top 10 with flags) + +2. Recent Alerts Timeline + - Alert cards with: timestamp, scenario, IP, country flag, severity + - Color-coded by risk level + - Expandable details showing full event data + - Filter by: time range, scenario type, severity + +3. Real-time Activity Feed + - Last 100 events (scrollable, auto-updating) + - IP address in monospace with copy button + - Scenario name with icon + - Action taken (ban/log/captcha) + +DECISIONS TAB: +1. Active Decisions Table + - Columns: IP, Reason, Duration, Expires In, Type, Origin, Actions + - Sortable by all columns + - Search and filter capabilities + - Manual decision add/remove buttons + - Bulk actions (delete selected) + - Export to CSV button + +2. Decision Statistics + - Decisions over time (24h chart) + - Most blocked IPs + - Most triggered scenarios + - Average decision duration + +ALERTS TAB: +1. Alert Management + - Alert cards grouped by scenario + - Timeline view with date headers + - Severity indicators (critical/high/medium/low) + - Related decisions linking + - Mark as resolved functionality + +BOUNCERS TAB: +1. Bouncer Status + - Connected bouncers list + - Each bouncer: name, type, version, last pull, status + - Add new bouncer with API key generation + - Delete bouncer with confirmation + - Bouncer metrics (decisions applied, queries made) + +METRICS TAB: +1. Performance Metrics + - CrowdSec service health + - Decision pull frequency + - API response times + - Memory and CPU usage + - LAPI/CAPI status indicators + +SETTINGS TAB: +1. CrowdSec Configuration + - Enable/disable service + - Acquisition configuration (log paths) + - Scenario management (enable/disable specific scenarios) + - Collection management (install/remove) + - Console enrollment status + +TECHNICAL: +- RPCD: luci.crowdsec-dashboard +- Methods: getStats, getDecisions, getAlerts, getBouncers, getMetrics +- Commands: cscli decisions list/add/delete, cscli alerts list, cscli bouncers list +- Parse JSON output from cscli commands +- Handle API communication with CrowdSec daemon + +VISUAL ENHANCEMENTS: +- Gradient borders for threat level cards (green→orange→red) +- Animated pulse on new alerts +- Country flags for IP geolocation +- Sparkline charts for metrics +- Loading skeletons during data fetch +``` + +### 4. Netdata Dashboard (luci-app-netdata-dashboard) + +**Prompt for Claude.ai:** + +``` +Create a Netdata system monitoring dashboard with 1000+ metrics: + +DESIGN: +- Title: "System Monitoring" with 📊 icon +- Emphasis on real-time charts and metrics +- Stats badges: Alerts | Services | Charts | Collectors + +DASHBOARD TAB: +1. Overview Metrics Grid + - System load (1m, 5m, 15m) as gauge charts + - CPU usage per core (multi-core visualization) + - RAM usage with breakdown (used/cached/buffers/free) + - Disk I/O rates (read/write MB/s) + - Network throughput (all interfaces combined) + +2. Quick Charts + - CPU temperature chart (if available) + - Swap usage chart + - Processes count chart (running/sleeping/zombie) + - Context switches and interrupts chart + +3. Embedded Netdata + - Full Netdata web UI embedded in iframe + - Responsive sizing + - Theme matching (dark mode) + +SYSTEM TAB: +1. System Metrics Deep Dive + - CPU frequency and governor + - CPU idle time percentage + - Per-core usage bars + - System interrupts per second + - Context switches rate + - Kernel internal metrics + +2. Memory Details + - Memory allocation chart + - Page faults rate + - Committed memory ratio + - Huge pages usage + - Slab memory breakdown + +PROCESSES TAB: +1. Process Monitoring + - Top processes by CPU (live updating table) + - Top processes by RAM + - Process count by state + - Thread count total + - Process spawn rate + +2. Process Details + - Per-process CPU time + - Per-process memory maps + - Open files per process + - Process tree visualization + +REALTIME TAB: +1. Live Monitoring + - Real-time CPU chart (1s granularity) + - Real-time network I/O + - Real-time disk I/O + - Real-time memory changes + - Auto-refreshing every second + +NETWORK TAB: +1. Network Metrics + - Interface statistics (all interfaces) + - Packet rates (packets/s in/out) + - Error and drop counters + - TCP/UDP connection states + - Netfilter statistics + - DNS query statistics (if available) + +SETTINGS TAB: +1. Netdata Configuration + - Enable/disable Netdata service + - Configure retention period + - Enable/disable specific collectors + - Alert configuration + - Streaming configuration (central Netdata) + +TECHNICAL: +- RPCD: luci.netdata-dashboard +- Netdata API integration (http://localhost:19999/api/v1/) +- Methods: /info, /charts, /data, /alarms +- Real-time data fetching with polling +- Chart.js or native Netdata charts +- WebSocket support for live updates + +CHARTS TO INCLUDE: +- Line charts for time-series data +- Bar charts for comparisons +- Gauge charts for current values +- Area charts for stacked metrics +- Sparklines for compact overviews +``` + +--- + +## Network Intelligence Modules + +### 5. Netifyd Dashboard (luci-app-netifyd-dashboard) + +**Prompt for Claude.ai:** + +``` +Create a Deep Packet Inspection dashboard using Netifyd (300+ app detection): + +DESIGN: +- Title: "Network Intelligence" with 🔍 icon +- Focus on application and protocol visibility +- Stats badges: Active Flows | Applications | Devices | Protocols + +OVERVIEW TAB: +1. Network Activity Summary + - Total flows count (current + historical) + - Unique applications detected today + - Active devices count + - Protocol distribution (TCP/UDP/ICMP pie chart) + +2. Top Applications Chart + - Bar chart of top 10 applications by bandwidth + - Icons for recognized apps (Netflix, YouTube, Spotify, etc.) + - Percentage of total traffic + - Click to filter flows by application + +3. Top Devices + - Device cards with: hostname, MAC, IP, current app + - Bandwidth usage per device (RX/TX) + - Device type icon (phone, laptop, TV, IoT) + +APPLICATIONS TAB: +1. Application Discovery + - Grid of detected applications + - Each card: app icon, name, category, protocol, active flows + - Color-coded categories: + * Streaming (red): Netflix, YouTube, Twitch + * Social (blue): Facebook, Instagram, TikTok + * Messaging (green): WhatsApp, Telegram, Signal + * VoIP (purple): Zoom, Teams, Discord + * Gaming (orange): Steam, PlayStation, Xbox + - Real-time bandwidth per app (sparklines) + +2. Application Details + - Click app to see: active connections, total bandwidth, protocols used + - Flow timeline for selected app + - Device breakdown (which devices use this app) + +DEVICES TAB: +1. Device Inventory + - Table: IP, MAC, Hostname, Vendor, Active Apps, Bandwidth + - Sortable and searchable + - Device grouping by subnet + - Manual device naming/tagging + +2. Device Profile + - Per-device view: all flows, app usage history + - Bandwidth trends (24h chart) + - Risk assessment (unknown protocols, suspicious apps) + - Block/allow rules management + +FLOWS TAB: +1. Active Flows Monitor + - Real-time table of network flows + - Columns: Source, Destination, App, Protocol, Bandwidth, Duration + - Auto-scrolling with pause button + - Color-coded by risk level + - Flow details on click (full 5-tuple + DPI data) + +2. Flow Statistics + - Flows by protocol (pie chart) + - Top talkers (source IPs) + - Top destinations (external IPs) + - Port distribution + +TOP TALKERS TAB: +1. Bandwidth Leaders + - Ranked list of IP addresses by total traffic + - Direction indicators (upload/download) + - Time range selector (1h/24h/7d/30d) + - Export to CSV + +RISKS TAB: +1. Risk Assessment + - Suspicious flows detection + - Unknown protocols list + - Connections to blacklisted IPs + - Unusual port usage + - Potential malware C2 traffic + - Risk score per device (0-100) + +CATEGORY BANDWIDTH TAB: +1. Traffic by Category + - Stacked area chart showing categories over time + - Categories: Streaming, Social, Gaming, Business, Other + - Percentage breakdown + - Peak usage times + +DNS QUERIES TAB: +1. DNS Analytics + - Recent DNS queries table + - Most queried domains + - Failed queries count + - DNS leak detection + - Blocked queries (if using DNS filtering) + +SETTINGS TAB: +1. Netifyd Configuration + - Enable/disable DPI + - Select interfaces to monitor + - Application detection sensitivity + - Flow export configuration + - Privacy settings (data retention) + +TECHNICAL: +- RPCD: luci.netifyd-dashboard +- Netifyd API: Unix socket /var/run/netifyd/netifyd.sock +- JSON flow export parsing +- Application database from Netify signatures +- Real-time flow updates (WebSocket or SSE) + +VISUAL FEATURES: +- Application icons from FontAwesome or custom SVG set +- Animated flow counters (counting up effect) +- Color-coded bandwidth bars +- Interactive charts (click to filter) +- Tooltips with detailed info +``` + +### 6. Network Modes (luci-app-network-modes) + +**Prompt for Claude.ai:** + +``` +Create a Network Mode Configuration wizard with 5 topology options: + +DESIGN: +- Title: "Network Configuration" with 🌐 icon +- Wizard-style interface with step progression +- Large mode cards with illustrations + +OVERVIEW TAB: +1. Current Mode Display + - Large card showing active mode with icon + - Mode description + - Current network config summary (WAN/LAN IPs, DHCP status) + - "Change Mode" button (gradient) + +2. Mode Comparison Table + - All 5 modes in columns + - Rows: Use case, WAN ports, LAN ports, WiFi role, DHCP server, NAT + - Highlight current mode + +WIZARD TAB: +1. Mode Selection Screen + - 5 mode cards in grid: + * Router Mode 🏠 - Default home/office setup + * Bridge Mode 🌉 - Transparent layer-2 forwarding + * Access Point Mode 📡 - WiFi only, wired uplink + * Repeater/Extender Mode 🔁 - WiFi to WiFi repeating + * Travel Router Mode ✈️ - Portable WiFi from hotel ethernet + - Each card: title, description, pros/cons, diagram + - "Select" button per card + +2. Configuration Screen (per mode) + - Mode-specific settings: + * Router: WAN type (DHCP/PPPoE/Static), LAN subnet, DHCP range + * Bridge: Bridge members, STP enable, VLAN config + * AP: Uplink interface, SSID, security, channel + * Repeater: Source SSID scan, credentials, rebroadcast SSID + * Travel Router: Client WiFi scan, WAN MAC clone option + +3. Preview Screen + - Show configuration changes before applying + - Network diagram with new topology + - List of services that will be reconfigured + - Estimated downtime warning + - "Apply" and "Back" buttons + +4. Apply Screen + - Progress indicator during application + - Step-by-step status: + * Stopping services... + * Updating network config... + * Restarting interfaces... + * Starting services... + - Rollback timer (60 seconds to confirm) + - Confirmation screen after success + +ROUTER MODE TAB: +1. Router Settings + - WAN interface config (DHCP client, static, PPPoE, 3G/4G) + - LAN interface config (IP, netmask, DHCP server) + - Port mapping (which physical ports are WAN vs LAN) + - NAT and firewall rules + - DNS forwarder configuration + +ACCESS POINT TAB: +1. AP Settings + - Uplink interface selection (ethernet or WiFi) + - Disable NAT and DHCP server + - Bridge LAN and Uplink + - WiFi configuration (SSID, security, channel, power) + - Fast roaming (802.11r) settings + +RELAY TAB: +1. Relay/Repeater Settings + - Site survey (scan for WiFi networks) + - Connect to upstream WiFi (credentials) + - Rebroadcast SSID (same or different) + - WiFi to WiFi bridge config + - Signal strength indicators + +SNIFFER MODE TAB: +1. Packet Capture Configuration + - Monitor mode on WiFi + - Promiscuous mode on ethernet + - Capture filters (BPF syntax) + - Output format (pcap, pcapng) + - Capture rotation and storage + - Integration with tcpdump/wireshark + +SETTINGS TAB: +1. Advanced Network Settings + - VLAN configuration + - Link aggregation (bonding) + - QoS settings + - IPv6 configuration + - Custom routing rules + +TECHNICAL: +- RPCD: luci.network-modes +- Methods: get_current_mode, get_available_modes, set_mode, validate_config +- UCI config manipulation (/etc/config/network, wireless, firewall, dhcp) +- Interface state monitoring (network.interface events) +- Rollback mechanism (uci revert + timer) + +VALIDATION: +- IP address format validation +- Subnet overlap detection +- DHCP range within subnet check +- WiFi channel availability check +- Physical port assignment conflicts +``` + +--- + +## VPN & Access Control Modules + +### 7. WireGuard Dashboard (luci-app-wireguard-dashboard) + +**Prompt for Claude.ai:** + +``` +Create a WireGuard VPN management dashboard with QR code generation: + +DESIGN: +- Title: "WireGuard VPN" with 🔐 icon +- Modern VPN dashboard aesthetic +- Stats badges: Active Peers | Data Transferred | Uptime | Endpoints + +OVERVIEW TAB: +1. VPN Status + - Interface status (up/down) with toggle + - Public key display (monospace, copy button) + - Listen port + - IP address (VPN subnet) + - Endpoint (if client mode) + +2. Peer Statistics + - Active peers count + - Total data RX/TX (all peers combined) + - Latest handshake timestamp + - Connection quality indicators + +3. Quick Actions + - Start/Stop VPN button + - Generate New Keypair button + - Download Config button + - Add Peer button (quick modal) + +PEERS TAB: +1. Peer Management + - Peer cards grid: + * Each card: name, public key (truncated), allowed IPs, endpoint, status + * Color-coded border (green=active, orange=stale, red=disconnected) + * Last handshake time (e.g., "2 minutes ago") + * Data transfer counters (RX/TX) + * Edit and Delete buttons + +2. Add Peer Dialog + - Generate keypair automatically OR paste existing public key + - Assign VPN IP address (auto-suggest next available) + - Define allowed IPs (0.0.0.0/0 for full tunnel, specific subnets for split) + - Optional: persistent keepalive interval + - Optional: pre-shared key (PSK) for post-quantum security + - Generate config file and QR code instantly + +QR CODES TAB: +1. Mobile Client Setup + - Select peer from dropdown + - Generate WireGuard client config + - Display as QR code (for WireGuard mobile app scanning) + - Also show config text (copyable) + - Download .conf file button + - Include DNS servers in config + +2. QR Code Options + - Custom DNS servers + - Include all routes vs split tunnel + - MTU configuration + - Persistent keepalive setting + +TRAFFIC TAB: +1. Traffic Analytics + - Real-time bandwidth chart (per peer) + - Historical traffic graph (24h, 7d, 30d) + - Top bandwidth users + - Traffic by protocol (if DPI available) + +CONFIG TAB: +1. Interface Configuration + - Private key (hidden by default, show button) + - Public key (derived, read-only) + - Listen port (51820 default) + - IP addresses (comma-separated for multi-subnet) + - MTU size + - Table (routing table number) + +2. Advanced Settings + - Pre-up/Post-up scripts + - Pre-down/Post-down scripts + - Firewall zone assignment + - NAT masquerading toggle + +SETTINGS TAB: +1. Global VPN Settings + - Auto-start on boot toggle + - Keep-alive interval (global default) + - DNS leak protection + - IPv6 support toggle + - Logging level + +2. Endpoint Configuration (for client mode) + - Server endpoint hostname/IP + - Server public key + - Allowed IPs (what routes through VPN) + - Persistent keepalive for NAT traversal + +TECHNICAL: +- RPCD: luci.wireguard-dashboard +- Methods: status, get_interfaces, get_peers, add_peer, remove_peer, generate_keys, generate_config, generate_qr +- Commands: wg show, wg set, wg genkey, wg pubkey, wg genpsk +- QR code generation: qrencode command or JavaScript library (qrcodejs) +- Config file template generation +- Real-time peer status updates + +UI ENHANCEMENTS: +- Animated connection status indicators +- Gradient border for active peers +- Copy-to-clipboard for keys and configs +- Modal dialogs for add/edit peer +- Confirmation dialogs for destructive actions +- Toast notifications for success/error +``` + +### 8. Client Guardian (luci-app-client-guardian) + +**Prompt for Claude.ai:** + +``` +Create a Network Access Control (NAC) and Captive Portal system: + +DESIGN: +- Title: "Access Control" with 👥 icon +- Focus on device management and access policies +- Stats badges: Total Devices | Allowed | Blocked | Guest + +OVERVIEW TAB: +1. Network Summary + - Total devices seen (ever) + - Currently connected devices + - Allowed devices count + - Blocked devices count + - Guest devices (captive portal) + +2. Recent Activity + - Last 20 connection events + - Each event: timestamp, MAC, IP, hostname, action (allow/block/captive) + - Color-coded by action type + +3. Quick Actions + - Block All Unknown button (lockdown mode) + - Allow All button (open mode) + - Clear Guest Sessions button + +CLIENTS TAB: +1. Device Table + - Columns: MAC, IP, Hostname, Vendor, Zone, Status, Actions + - Sortable by all columns + - Search/filter bar + - Bulk selection for actions + +2. Device Details Modal + - Full device info: MAC, IP, Hostname, Vendor (from MAC prefix) + - Connection history (first seen, last seen, total connections) + - Current zone assignment (LAN, Guest, Blocked) + - Assigned policies + - Edit button (change hostname, zone, policies) + +ZONES TAB: +1. Zone Management + - Predefined zones: + * Trusted (full access) + * LAN (standard access) + * Guest (restricted access, captive portal) + * IoT (isolated, limited access) + * Quarantine (blocked) + +2. Zone Configuration + - Per-zone settings: + * Allowed services (HTTP, HTTPS, DNS, etc.) + * Bandwidth limits + * Time restrictions + * Inter-zone communication rules + * Firewall rules + +CAPTIVE PORTAL TAB: +1. Captive Portal Configuration + - Enable/disable portal + - Splash page customization: + * Custom logo upload + * Welcome message (HTML editor) + * Terms of Service text + * Redirect URL after acceptance + +2. Portal Themes + - Predefined themes (Business, Hotel, Cafe, School) + - Color scheme customization + - Preview button + +3. Portal Settings + - Session duration (1h, 4h, 24h, unlimited) + - Require email before access + - Require SMS verification + - Require social login (Facebook, Google) + - Auto-allow known devices + +PORTAL DESIGN TAB: +1. Splash Page Editor + - WYSIWYG HTML editor + - Template variables (e.g., {{client_mac}}, {{client_ip}}) + - Background image upload + - CSS styling panel + - Live preview + +LOGS TAB: +1. Access Logs + - Connection attempts log + - Allowed/blocked decisions + - Captive portal authentications + - Filter by: time range, MAC, IP, zone, action + +ALERTS TAB: +1. Security Alerts + - MAC spoofing detection + - Excessive connection attempts + - Unknown devices connecting + - Devices changing zones + - Alert rules configuration + +PARENTAL CONTROLS TAB: +1. Content Filtering + - Website category blocking (adult, social, gaming, etc.) + - Time-based access controls (school hours, bedtime) + - Per-device or per-user policies + - SafeSearch enforcement + - YouTube restricted mode + +2. Device Groups + - Group devices (e.g., "Kids Devices") + - Apply policies to groups + - Schedule-based rules (weekday vs weekend) + +SETTINGS TAB: +1. Client Guardian Settings + - Default zone for new devices + - MAC-IP binding enforcement + - ARP cache timeout + - DHCP integration (assign zone based on IP range) + - Logging level and retention + +TECHNICAL: +- RPCD: luci.client-guardian +- Methods: list_clients, update_client, get_zones, configure_portal, get_logs +- Integration with: + * nftables/iptables for access control + * dnsmasq for DNS and DHCP + * nginx/uhttpd for captive portal + * ipset for efficient device grouping +- Database for device tracking (SQLite or UCI) + +CAPTIVE PORTAL IMPLEMENTATION: +- Intercept HTTP traffic for unauthenticated clients +- Redirect to splash page +- After acceptance, add to allowed ipset +- Session management with cookies or tokens +``` + +### 9. Auth Guardian (luci-app-auth-guardian) + +**Prompt for Claude.ai:** + +``` +Create an authentication and session management system with OAuth2 and vouchers: + +DESIGN: +- Title: "Authentication" with 🔑 icon +- Professional authentication dashboard +- Stats badges: Active Sessions | OAuth Providers | Vouchers | Bypass Rules + +OVERVIEW TAB: +1. Authentication Status + - Total registered users + - Active sessions count + - OAuth providers configured + - Voucher redemptions today + +2. Recent Authentications + - Last 20 auth events + - Each: timestamp, username/email, method (OAuth/voucher/bypass), IP, status + - Color-coded by status (success=green, fail=red) + +SESSIONS TAB: +1. Active Sessions Table + - Columns: User, Session ID, Started, Last Activity, IP, Device, Actions + - Session details on click + - Revoke session button (with confirmation) + - Force logout all sessions button + +2. Session Management + - Session timeout configuration + - Concurrent session limit per user + - Idle timeout + - Remember me duration + +VOUCHERS TAB: +1. Voucher Management + - Create new voucher button + - Voucher table: Code, Duration, Remaining Uses, Created, Expires, Status + - Voucher types: + * Single-use (one time only) + * Multi-use (X redemptions) + * Time-limited (expires after duration) + * Bandwidth-limited (X GB quota) + +2. Create Voucher Dialog + - Generate random code OR custom code + - Voucher duration (1h, 4h, 24h, 7d, 30d, unlimited) + - Usage limit (1, 10, 100, unlimited) + - Bandwidth quota (optional) + - Notes/description field + - Print voucher button (printable page with code) + +3. Bulk Voucher Generation + - Generate X vouchers at once + - Export as CSV + - Print sheet (multiple vouchers per page) + +OAUTH TAB: +1. OAuth Provider Configuration + - Supported providers: + * Google OAuth + * GitHub OAuth + * Facebook Login + * Microsoft Azure AD + * Custom OAuth2 provider + +2. Provider Setup + - Client ID input + - Client Secret input (masked) + - Redirect URI (auto-generated) + - Scopes configuration + - Enable/disable per provider + - Test button (initiates OAuth flow) + +3. User Mapping + - Map OAuth attributes to local user fields + - Auto-create user on first OAuth login + - Group assignment based on OAuth claims + +SPLASH PAGE TAB: +1. Login Page Customization + - Custom logo upload + - Welcome text editor + - Enabled auth methods (OAuth buttons, voucher input, bypass link) + - Background image or gradient + - Color scheme + - Preview button + +BYPASS RULES TAB: +1. Bypass Configuration + - Whitelist MAC addresses (no auth required) + - Whitelist IP ranges + - Whitelist hostnames (regex patterns) + - Time-based bypass (e.g., office hours, all devices allowed) + +2. Bypass List + - Table: MAC/IP, Description, Added, Expires + - Add/remove bypass rules + - Temporary bypass (expires after X hours) + +LOGS TAB: +1. Authentication Logs + - All auth attempts (success and failure) + - Filter by: date range, username, method, IP + - Export to CSV + - Visualizations: + * Auth attempts over time (line chart) + * Auth methods breakdown (pie chart) + * Failed attempts by IP (bar chart) + +SETTINGS TAB: +1. Auth Guardian Settings + - Require authentication (global toggle) + - Default session duration + - Password policy (if local users) + - Two-factor authentication (TOTP) + - Login attempt limits (brute force protection) + - Session storage (memory vs database) + +TECHNICAL: +- RPCD: luci.auth-guardian +- Methods: status, list_providers, list_vouchers, create_voucher, delete_voucher, validate_voucher, list_sessions, revoke_session +- OAuth implementation: + * Authorization code flow + * JWT token validation + * Provider-specific API calls +- Voucher system: + * Random code generation (alphanumeric, 8-16 chars) + * Expiry tracking (cron job or daemon) + * Redemption logging +- Session management: + * Cookie-based or token-based + * Redis or in-memory storage for sessions + * Session cleanup task + +INTEGRATION: +- Works with Client Guardian for captive portal +- Firewall integration for post-auth access +- RADIUS support (optional, for enterprise) +``` + +--- + +## Bandwidth & Traffic Modules + +### 10. Bandwidth Manager (luci-app-bandwidth-manager) + +**Prompt for Claude.ai:** + +``` +Create a comprehensive QoS and bandwidth management system: + +DESIGN: +- Title: "Bandwidth Manager" with 📶 icon +- Focus on traffic shaping and quotas +- Stats badges: Active Rules | Total Bandwidth | Clients Tracked | Quotas + +OVERVIEW TAB: +1. Bandwidth Summary + - Total available bandwidth (WAN uplink/downlink) + - Current usage (real-time gauge) + - Peak usage (today's maximum) + - Average usage (24h) + +2. Top Bandwidth Users + - Table: IP/Hostname, Download, Upload, Total, Percentage + - Real-time updates + - Click to apply quick rule + +3. Traffic Classification + - By protocol: HTTP, HTTPS, DNS, P2P, Streaming, Gaming + - By priority: High, Medium, Low, Bulk + - Pie chart visualization + +RULES TAB: +1. QoS Rules Table + - Columns: Name, Source, Destination, Service, Priority, Rate Limit, Status + - Sortable and filterable + - Enable/disable toggle per rule + - Edit/Delete actions + +2. Add Rule Dialog + - Rule type: Bandwidth Limit, Priority, Guarantee + - Match criteria: + * Source IP/MAC/Subnet + * Destination IP/Subnet + * Port/Service (HTTP, HTTPS, SSH, etc.) + * Protocol (TCP, UDP, ICMP) + * Application (DPI-based, if available) + - Action: + * Set download limit (kbps/mbps) + * Set upload limit + * Set priority (1-7, or class names) + * Guarantee minimum bandwidth + - Schedule (always, time-based, day-of-week) + +QUOTAS TAB: +1. Bandwidth Quotas + - Per-device quotas + - Per-user quotas + - Family quotas (group of devices) + - Time-based quotas (daily, weekly, monthly) + +2. Quota Configuration + - Set quota amount (GB) + - Set quota period (day/week/month) + - Action on quota exceeded: + * Block all traffic + * Throttle to X kbps + * Send notification only + - Quota reset schedule + - Rollover unused quota (optional) + +3. Quota Usage Dashboard + - Cards per device/user showing: + * Quota limit + * Used amount + * Remaining + * Progress bar with color coding + * Reset date + - Warning threshold (notify at 80%, 90%) + +USAGE TAB: +1. Historical Usage + - Charts: + * Daily usage (last 30 days) as bar chart + * Hourly usage (last 24h) as line chart + * Weekly usage (last 12 weeks) as area chart + - Filter by device, service, direction (up/down) + - Export to CSV + +2. Usage Statistics + - Total transferred this month + - Average daily usage + - Peak hour (when usage is highest) + - Trending applications + +MEDIA TAB: +1. Media Traffic Detection + - Streaming services: Netflix, YouTube, Disney+, Twitch, etc. + - VoIP: Zoom, Teams, Discord, WhatsApp calls + - Gaming: Steam, PlayStation, Xbox Live + - Social Media: Facebook, Instagram, TikTok + +2. Media-Specific Rules + - Quick templates: + * Prioritize VoIP over streaming + * Throttle streaming during work hours + * Limit gaming bandwidth + - Per-service bandwidth allocation + - Quality-based throttling (4K vs 720p detection) + +CLASSES TAB: +1. Traffic Classes (HTB/CAKE) + - Predefined classes: + * Realtime (VoIP, gaming): highest priority + * Interactive (web browsing, SSH): high priority + * Bulk (downloads, updates): low priority + * Default: medium priority + +2. Class Configuration + - Per-class bandwidth allocation (percentage or absolute) + - Borrowing (allow class to use unused bandwidth from others) + - Ceiling (maximum bandwidth a class can use) + - Quantum (packet size for fair queuing) + +CLIENTS TAB: +1. Per-Client Management + - Client list with current bandwidth usage + - Quick actions: + * Set bandwidth limit for client + * Apply quota to client + * Block client temporarily + * Assign to traffic class + +SCHEDULES TAB: +1. Schedule Management + - Create time-based rules + - Examples: + * Business hours (9am-5pm Mon-Fri): prioritize business apps + * Evening (6pm-11pm): allow streaming + * Late night (11pm-6am): throttle everything + - Calendar view of schedules + - Conflict detection + +SETTINGS TAB: +1. Global Settings + - WAN bandwidth limits (uplink/downlink in Mbps) + - QoS algorithm: CAKE, HTB, SFQ, FQ_CODEL + - Enable/disable QoS globally + - Default traffic class + - Bandwidth test (measure actual WAN speed) + +2. Advanced Settings + - DSCP marking + - ECN (Explicit Congestion Notification) + - Overhead calculation (for PPPoE, etc.) + - Per-packet overhead bytes + - Link layer adaptation + +TECHNICAL: +- RPCD: luci.bandwidth-manager +- Methods: getStats, getRules, addRule, deleteRule, getQuotas, setQuota, getUsage +- QoS implementation: + * tc (traffic control) commands for HTB + * cake qdisc for modern QoS + * iptables conntrack for usage accounting + * nftables meters for rate limiting +- Database: + * SQLite or UCI for rules and quotas + * RRD for historical bandwidth data + * iptables counters for real-time stats + +VISUAL ENHANCEMENTS: +- Bandwidth gauge charts (animated) +- Sparklines for trending +- Color-coded quota bars +- Responsive rule cards +``` + +### 11. Traffic Shaper (luci-app-traffic-shaper) + +**Prompt for Claude.ai:** + +``` +Create an advanced traffic shaping module with anti-bufferbloat (CAKE): + +DESIGN: +- Title: "Traffic Shaper" with 🚀 icon +- Technical/advanced focus +- Stats badges: Active Queues | Avg Latency | Packet Loss | Throughput + +OVERVIEW TAB: +1. Shaper Status + - QoS enabled status toggle + - Active algorithm (CAKE, HTB, FQ_CODEL) + - Shaped interfaces (WAN, LAN) + - Current latency (ping to 1.1.1.1) + +2. Performance Metrics + - Round-trip time (RTT) under load + - Buffer size (current vs optimal) + - Packet drop rate + - Throughput (actual vs configured) + +3. Bufferbloat Test + - Run DSLReports speed test button + - Display results: download, upload, latency, grade + - Historical test results chart + +CLASSES TAB: +1. Traffic Classes (HTB hierarchy) + - Root class (total bandwidth) + - Child classes with priority: + * Expedited Forwarding (EF): VoIP, gaming + * Assured Forwarding (AF): business apps + * Best Effort (BE): web, email + * Background (bulk downloads) + +2. Class Configuration + - Rate (guaranteed bandwidth) + - Ceil (maximum bandwidth) + - Priority (1-7) + - Quantum (packet size) + - Burst (allow temporary overage) + +RULES TAB: +1. Classification Rules + - Match criteria: + * DSCP/TOS field + * Port numbers + * IP addresses + * Protocol + * DPI signature + - Action: assign to traffic class + - Rule priority (1-999) + +2. Rule Templates + - Predefined rules: + * VoIP optimization (SIP, RTP ports) + * Gaming optimization (known game servers) + * Streaming deprioritization + * P2P throttling + - One-click apply + +STATS TAB: +1. Queue Statistics + - Per-class metrics: + * Packets sent + * Bytes sent + * Drops (overload indicator) + * Overlimits (ceiling hits) + * Requeues + - Real-time and historical charts + +2. Interface Statistics + - Per-interface counters + - Queue depth graphs + - Latency measurements (ICMP ping or timestamping) + +PRESETS TAB: +1. QoS Presets + - Gaming preset (lowest latency, prioritize gaming ports) + - Streaming preset (balance, allow bandwidth for streaming) + - Business preset (prioritize VoIP, remote desktop) + - Balanced preset (general home use) + - Manual preset (custom configuration) + +2. Preset Configuration + - Select preset from dropdown + - Auto-configure all parameters + - Show what will change (diff preview) + - Apply button + +CAKE CONFIGURATION TAB: +1. CAKE Settings + - Bandwidth (uplink/downlink in Mbps) + - Overhead: + * None + * ADSL (with interleaving) + * VDSL2 + * Ethernet + * PPPoE + - Link layer adaptation: + * Ethernet + * ATM + * PTM + - Flows: + * Triple-isolate (src IP, dst IP, port) + * Dual-srchost + * Dual-dsthost + * Per-host + - Diffserv: + * Diffserv4 (4 tins) + * Diffserv3 (3 tins) + * Besteffort (single queue) + - ECN: enable/disable + - ACK filter: enable/disable (for slow uplinks) + +TECHNICAL: +- RPCD: luci.traffic-shaper +- Commands: + * tc qdisc add/del/replace + * tc class add/del/change + * tc filter add/del + * cake qdisc configuration +- Real-time monitoring: + * tc -s qdisc show + * tc -s class show + * Parse output for statistics +- Latency testing: + * ping command with timestamps + * Integration with fping or hping3 + +VISUAL ENHANCEMENTS: +- Real-time latency graph (live updating) +- Packet drop rate sparklines +- Class hierarchy tree view +- Color-coded classes by priority +``` + +### 12. Media Flow (luci-app-media-flow) + +**Prompt for Claude.ai:** + +``` +Create a media streaming and VoIP traffic detection dashboard: + +DESIGN: +- Title: "Media Monitor" with 🎬 icon +- Focus on streaming services and video calls +- Stats badges: Active Streams | VoIP Calls | Bandwidth Used | Services + +DASHBOARD TAB: +1. Active Media Streams + - Cards for each active stream: + * Service logo (Netflix, YouTube, etc.) + * Client device (IP, hostname) + * Stream quality estimate (4K, 1080p, 720p, SD) + * Current bitrate (Mbps) + * Duration + - Color-coded by service type (streaming=red, VoIP=green) + +2. Service Breakdown + - Pie chart: bandwidth by service + - Services: + * Netflix, Amazon Prime, Disney+, Hulu, HBO Max + * YouTube, Twitch, Vimeo + * Spotify, Apple Music, Pandora + * Zoom, Teams, Meet, Webex + * WhatsApp, Telegram, FaceTime + +SERVICES TAB: +1. Streaming Services Grid + - Each service as card: + * Icon/logo + * Total bandwidth used today + * Active sessions + * Peak quality detected + * Average session duration + - Click card for details + +2. Service History + - Per-service usage over time + - Quality distribution (how often 4K vs HD vs SD) + - Peak viewing hours + +CLIENTS TAB: +1. Device Media Usage + - Table: Device, Service, Quality, Bitrate, Duration + - Group by device + - Show total media consumption per device + - Identify heavy streaming users + +HISTORY TAB: +1. Historical Media Activity + - Timeline view of all media sessions + - Filter by: date range, service, device, quality + - Export to CSV + - Charts: + * Daily streaming hours + * Service popularity trends + * Quality vs bandwidth correlation + +ALERTS TAB: +1. Media Alerts + - Excessive streaming alerts + - Quality degradation alerts (4K dropped to 720p) + - VoIP quality issues (packet loss, jitter) + - New service detection + - Unusual patterns (e.g., streaming at 3am) + +2. Alert Configuration + - Set thresholds for alerts + - Notification methods (web UI, email, webhook) + - Per-device alert rules + +TECHNICAL: +- RPCD: luci.media-flow +- DPI integration: + * Netifyd for application detection + * nDPI library for deep inspection + * Signature matching for streaming protocols +- Quality estimation: + * Bitrate analysis (e.g., >15 Mbps = 4K, 5-15 Mbps = 1080p) + * DASH/HLS manifest parsing (if accessible) +- VoIP detection: + * RTP/RTCP ports and patterns + * SIP signaling detection + * WebRTC detection + +STREAMING PROTOCOLS: +- HLS (HTTP Live Streaming) +- DASH (Dynamic Adaptive Streaming) +- RTMP (Real-Time Messaging Protocol) +- RTP (for VoIP) +- WebRTC (for video calls) +``` + +--- + +## Performance & Services Modules + +### 13. CDN Cache (luci-app-cdn-cache) + +**Prompt for Claude.ai:** + +``` +Create a CDN caching proxy dashboard with bandwidth savings analytics: + +DESIGN: +- Title: "CDN Cache" with 💨 icon +- Focus on performance and savings +- Stats badges: Cache Hit Rate | Bandwidth Saved | Cached Objects | Storage Used + +OVERVIEW TAB: +1. Cache Performance + - Hit rate percentage (big gauge chart) + - Requests today: total, hits, misses + - Bandwidth saved estimate (GB and percentage) + - Storage usage (used/total) + +2. Top Cached Content + - Table: URL/domain, Hits, Size, Last Access + - Content types breakdown (images, videos, scripts, docs) + - Pie chart: cached vs non-cacheable traffic + +CACHE TAB: +1. Cached Objects Browser + - List of cached objects: + * URL + * Content-Type + * Size + * Expiry + * Hit count + * Actions (view, purge) + - Search and filter + - Bulk purge by pattern + +2. Cache Statistics + - Total objects + - Average object size + - Largest objects + - Most hit objects + - Expiring soon count + +POLICIES TAB: +1. Caching Policies + - Domains to cache (whitelist) + - Domains to never cache (blacklist) + - Content types to cache (image/*, video/*, text/css, etc.) + - Max object size (MB) + - Cache duration (TTL) by content type + +2. Cache Rules + - Rule editor: + * Match URL pattern (regex) + * Cache duration override + * Cache or bypass decision + * Priority (1-100) + +STATISTICS TAB: +1. Performance Metrics + - Response time comparison: cache hit vs miss + - Bandwidth charts: cached vs origin + - Request rate over time + - Cache efficiency trends (24h, 7d, 30d) + +2. Savings Calculator + - Original bandwidth used (without cache) + - Bandwidth saved (GB) + - Cost savings estimate ($ per GB from ISP) + - Response time improvement (ms) + +MAINTENANCE TAB: +1. Cache Maintenance + - Purge all button (with confirmation) + - Purge by pattern (e.g., *.youtube.com/*) + - Purge expired objects + - Optimize database (rebuild indexes) + - Prewarm cache (prefetch popular URLs) + +2. Storage Management + - Storage usage breakdown + - LRU eviction settings (least recently used) + - Max cache size configuration + - Storage location (disk, RAM, or hybrid) + +SETTINGS TAB: +1. CDN Cache Configuration + - Enable/disable cache + - Upstream DNS servers + - Proxy port (transparent or explicit) + - SSL certificate handling (bump or pass-through) + - Logging level + +2. Advanced Settings + - Negative caching (cache 404s, etc.) + - Range request handling + - Vary header support + - ETag validation + - Stale-while-revalidate + +TECHNICAL: +- RPCD: luci.cdn-cache +- Caching software: + * Squid proxy + * Nginx caching proxy + * Varnish + * OpenWrt's own uhttpd with caching module +- Methods: getStats, getCacheObjects, purge, setPolicies +- Storage backend: filesystem or database +- Monitoring: access logs parsing for hit/miss + +VISUAL ENHANCEMENTS: +- Animated gauge for hit rate +- Sparklines for trending metrics +- Color-coded savings (green = high savings) +- Before/after comparison charts +``` + +### 14. VHost Manager (luci-app-vhost-manager) + +**Prompt for Claude.ai:** + +``` +Create a virtual host and reverse proxy manager with auto SSL: + +DESIGN: +- Title: "Virtual Hosts" with 🌍 icon +- Focus on web hosting and proxying +- Stats badges: Active VHosts | SSL Certs | Total Requests | Uptime + +OVERVIEW TAB: +1. VHost Summary + - Total virtual hosts configured + - Active (enabled) vs inactive + - SSL-enabled hosts count + - Certificate expiry warnings + +2. Quick Actions + - Add VHost button + - Request SSL Certificate button + - View Access Logs button + +VHOSTS TAB: +1. Virtual Hosts List + - Cards for each vhost: + * Domain name + * Type (reverse proxy, static site, redirect) + * Backend (if proxy) + * Status (enabled/disabled) + * SSL status (valid, expiring, none) + * Actions (edit, disable, delete, view logs) + +2. Add/Edit VHost Dialog + - Domain name input (auto-validate DNS) + - VHost type: + * Reverse Proxy (proxy to backend server) + * Static Site (serve from directory) + * Redirect (301/302 to another URL) + - Backend configuration (for proxy): + * Backend URL (http://192.168.1.10:8080) + * Protocol (HTTP, HTTPS, WebSocket) + * Load balancing (if multiple backends) + - SSL configuration: + * Auto (Let's Encrypt via ACME) + * Manual (upload cert + key) + * None (HTTP only) + - Advanced: + * Custom headers + * Access control (allow/deny IPs) + * Request rewriting + +INTERNAL TAB: +1. Internal Services + - Predefined proxies for common services: + * LuCI itself + * Netdata + * CrowdSec dashboard + * RustDesk + * Custom apps + - One-click enable proxy for internal service + +CERTIFICATES TAB: +1. SSL Certificate Management + - List of certificates: + * Domain + * Issuer (Let's Encrypt, self-signed, CA) + * Valid From - Valid To + * Days until expiry + * Actions (renew, revoke, download, delete) + +2. ACME Configuration + - ACME provider (Let's Encrypt production/staging, ZeroSSL, BuyPass) + - Email for notifications + - Challenge type: + * HTTP-01 (port 80 validation) + * DNS-01 (TXT record validation) + * TLS-ALPN-01 (port 443 validation) + - Auto-renewal toggle (renew when <30 days remaining) + +3. Request Certificate + - Domain input (supports wildcards with DNS-01) + - Validation method selector + - Issue button (shows progress) + +SSL TAB: +1. SSL/TLS Settings + - Global SSL settings: + * Minimum TLS version (1.0, 1.1, 1.2, 1.3) + * Cipher suites + * HSTS (HTTP Strict Transport Security) + * OCSP stapling + - Per-vhost overrides + +REDIRECTS TAB: +1. Redirect Rules + - Simple redirects: + * From domain/path + * To URL + * Type (301 permanent, 302 temporary, 307 temporary preserve method) + - Wildcard redirects + - Regex-based redirects + +LOGS TAB: +1. Access Logs + - Combined access log for all vhosts + - Filter by vhost, IP, status code, date + - Columns: Timestamp, IP, Method, Path, Status, Bytes, Referrer, User-Agent + - Real-time log streaming + - Export to CSV + +2. Error Logs + - Proxy errors (backend unreachable, timeout) + - SSL errors (cert invalid, expired) + - Configuration errors + +TECHNICAL: +- RPCD: luci.vhost-manager +- Reverse proxy software: + * Nginx + * HAProxy + * Caddy (for auto SSL) + * Apache +- ACME client: + * acme.sh script + * Certbot + * Caddy built-in ACME +- Methods: getVHosts, addVHost, deleteVHost, requestCertificate, getLogs + +INTEGRATION: +- DNS validation via API (Cloudflare, etc.) +- Dynamic DNS updates +- Firewall port opening (80, 443) +- Let's Encrypt rate limit handling +``` + +### 15. KSM Manager (luci-app-ksm-manager) + +**Prompt for Claude.ai:** + +``` +Create a cryptographic key and secrets management dashboard with HSM support: + +DESIGN: +- Title: "Key Management" with 🔐 icon +- Security-focused, professional aesthetic +- Stats badges: Total Keys | Active Keys | Certificates | Secrets + +OVERVIEW TAB: +1. Key Management Status + - Total keys managed + - Key types breakdown (RSA, ECDSA, ED25519) + - Expiring keys (next 30 days) + - HSM status (if connected) + +2. Recent Activity + - Last key operations: generated, used, rotated, revoked + - Audit log (last 20 entries) + +KEYS TAB: +1. Cryptographic Keys List + - Table: Key ID, Type, Size, Usage, Created, Expires, Status + - Key types: + * Signing keys (for code, documents) + * Encryption keys (for data at rest) + * Authentication keys (SSH, TLS client) + - Actions: view, export public, rotate, revoke, delete + +2. Generate Key Dialog + - Algorithm selection: + * RSA (2048, 3072, 4096 bit) + * ECDSA (P-256, P-384, P-521) + * ED25519 + - Usage flags: + * Digital signature + * Key encipherment + * Data encipherment + - Storage: + * Software (filesystem) + * HSM (if available) + * TPM (if available) + - Passphrase protection (optional) + +HSM TAB: +1. Hardware Security Module + - HSM connection status + - HSM info: vendor, model, firmware version + - Available key slots + - HSM operations: + * Initialize HSM + * Generate key on HSM + * Import key to HSM + * Backup HSM + +CERTIFICATES TAB: +1. X.509 Certificate Management + - List: Subject, Issuer, Valid From/To, Serial, Fingerprint + - Certificate chain view + - Actions: view details, export (PEM/DER), revoke + +2. Certificate Request (CSR) + - Generate CSR for signing by CA + - Fields: CN, O, OU, C, ST, L, Email + - Key usage extensions + - Export CSR for submission to CA + +3. Self-Signed Certificates + - Quick generate self-signed cert + - Validity period selection + - Subject alternative names (SANs) + +SECRETS TAB: +1. Secret Storage (Vault) + - Key-value secret store + - Secrets list: Name, Type, Created, Last Accessed + - Secret types: + * Password + * API key + * Token + * Connection string + - Encrypted at rest + - Access control (which users/apps can access) + +2. Add Secret Dialog + - Secret name (path-based: db/prod/password) + - Secret value (masked input) + - TTL (time-to-live, auto-expire) + - Version control (keep old versions) + +SSH TAB: +1. SSH Key Management + - SSH key pairs list + - Generate SSH key (RSA, ED25519, ECDSA) + - Import existing key + - Export public key (for authorized_keys) + - Authorized keys management (who can SSH in) + +AUDIT TAB: +1. Audit Log + - All key operations logged: + * Generated, imported, exported, used, rotated, revoked, deleted + - Timestamp, user, operation, key ID, result + - Filter by: date range, operation type, key ID, user + - Export audit log + +SETTINGS TAB: +1. KSM Configuration + - Key storage location + - Default key algorithm and size + - Auto-rotation policy (rotate keys every X days) + - Backup location and schedule + - HSM connection settings (if supported) + +TECHNICAL: +- RPCD: luci.ksm-manager +- Key storage: + * OpenSSL for key operations + * GnuPG for PGP keys + * SSH-keygen for SSH keys + * HSM integration via PKCS#11 +- Secret encryption: + * Encrypt secrets with master key + * Master key derived from passphrase or stored in HSM +- Methods: listKeys, generateKey, exportKey, importKey, listSecrets, addSecret, getSecret + +SECURITY: +- All secrets encrypted at rest +- Audit logging of all operations +- Access control (role-based) +- Secure key deletion (overwrite before delete) +``` + +--- + +## Common UI Patterns Across All Modules + +### Global Design Consistency + +**All modules MUST include:** + +1. **Page Header Pattern** + ```javascript + E('div', { 'class': 'sh-page-header' }, [ + E('div', {}, [ + E('h2', { 'class': 'sh-page-title' }, [ + E('span', { 'class': 'sh-page-title-icon' }, '[ICON]'), + '[MODULE TITLE]' + ]), + E('p', { 'class': 'sh-page-subtitle' }, '[DESCRIPTION]') + ]), + E('div', { 'class': 'sh-stats-grid' }, [ + // 4 stat badges minimum + ]) + ]) + ``` + +2. **Stats Badges** (130px minimum, monospace values) + ```javascript + E('div', { 'class': 'sh-stat-badge' }, [ + E('div', { 'class': 'sh-stat-value' }, '[VALUE]'), + E('div', { 'class': 'sh-stat-label' }, '[LABEL]') + ]) + ``` + +3. **Filter Tabs** (for categorization) + ```javascript + E('div', { 'class': 'sh-filter-tabs' }, [ + E('div', { 'class': 'sh-filter-tab active', 'data-filter': 'all' }, [ + E('span', { 'class': 'sh-tab-icon' }, '[ICON]'), + E('span', { 'class': 'sh-tab-label' }, '[LABEL]') + ]) + ]) + ``` + +4. **Cards with Color Borders** + ```javascript + E('div', { 'class': 'sh-card sh-card-success' }, [ + E('div', { 'class': 'sh-card-header' }, [ + E('h3', { 'class': 'sh-card-title' }, '[TITLE]') + ]), + E('div', { 'class': 'sh-card-body' }, [ + // Content + ]) + ]) + ``` + +5. **Gradient Buttons** + ```javascript + E('button', { 'class': 'sh-btn sh-btn-primary' }, '[ACTION]') + ``` + +6. **Loading States** + - Skeleton screens while fetching data + - Spinner for button actions + - Progress bars for long operations + +7. **Error Handling** + - User-friendly error messages + - Retry buttons + - Fallback content + +8. **Responsive Design** + - Mobile-first approach + - Cards stack on mobile + - Stats grid adapts (130px minimum) + - Tables become scrollable or card-based + +--- + +## How to Use These Prompts + +### Step 1: Select Module +Choose the module you want to regenerate/implement from the list above. + +### Step 2: Copy Full Prompt +Copy the entire prompt for that module (from "Create a..." to "VISUAL ENHANCEMENTS:"). + +### Step 3: Provide to Claude.ai +Paste the prompt into Claude.ai (claude.ai conversation) with additional context: + +``` +I need you to implement [MODULE NAME] for OpenWrt LuCI. + +IMPORTANT CONSTRAINTS: +- OpenWrt uses LuCI framework (not React/Vue) +- JavaScript uses L.view pattern (not ES6 modules) +- Backend is RPCD (shell scripts) communicating via ubus +- CSS must use variables from common.css +- All code must be production-ready +- Follow the design system exactly + +Here's the complete specification: + +[PASTE PROMPT HERE] + +Please provide: +1. Complete JavaScript view file +2. RPCD backend script +3. Any required CSS +4. ACL configuration +5. Menu configuration JSON + +Make sure all code matches the live demo at secubox.cybermood.eu +``` + +### Step 4: Iterate +If needed, provide screenshots from the live demo or request refinements to match the exact look and feel. + +--- + +## Additional Resources + +- **Live Demo:** https://secubox.cybermood.eu +- **Design System:** DEVELOPMENT-GUIDELINES.md +- **Quick Start:** QUICK-START.md +- **Build Guide:** CLAUDE.md + +--- + +**Document Version:** 1.0.0 +**Last Updated:** 2025-12-27 +**Maintainer:** CyberMind.fr diff --git a/MODULE-IMPLEMENTATION-GUIDE.md b/MODULE-IMPLEMENTATION-GUIDE.md new file mode 100644 index 00000000..b941a779 --- /dev/null +++ b/MODULE-IMPLEMENTATION-GUIDE.md @@ -0,0 +1,874 @@ +# SecuBox Module Implementation Guide + +**Version:** 1.0.0 +**Date:** 2025-12-27 +**Purpose:** Complete guide for regenerating SecuBox modules matching the live demo + +--- + +## Quick Navigation + +📋 **[FEATURE-REGENERATION-PROMPTS.md](./FEATURE-REGENERATION-PROMPTS.md)** - Complete feature specifications for all 15 modules +💻 **[CODE-TEMPLATES.md](./CODE-TEMPLATES.md)** - Ready-to-use code templates and implementation examples +🏗️ **[DEVELOPMENT-GUIDELINES.md](./DEVELOPMENT-GUIDELINES.md)** - Complete development guidelines and design system +⚡ **[QUICK-START.md](./QUICK-START.md)** - Quick reference for common tasks +🔧 **[CLAUDE.md](./CLAUDE.md)** - Build system and architecture reference + +--- + +## Document Overview + +This guide shows you how to use the comprehensive documentation to regenerate or create SecuBox modules that match the live demo at **secubox.cybermood.eu**. + +### What's Included + +1. **Feature Specifications** - Detailed requirements for all 15 modules +2. **Code Templates** - Working implementation examples +3. **Design System** - CSS variables, typography, components +4. **Validation Tools** - Automated testing and fixing +5. **Deployment Scripts** - Local build and remote deployment + +--- + +## Implementation Workflow + +### Step 1: Choose Your Approach + +**Option A: Use Claude.ai for Code Generation** +1. Open [claude.ai](https://claude.ai) +2. Copy the relevant module prompt from [FEATURE-REGENERATION-PROMPTS.md](./FEATURE-REGENERATION-PROMPTS.md) +3. Paste the prompt and request implementation +4. Claude will generate all required files based on the templates +5. Review and integrate the generated code + +**Option B: Manual Implementation Using Templates** +1. Copy templates from [CODE-TEMPLATES.md](./CODE-TEMPLATES.md) +2. Replace placeholders with module-specific values +3. Implement module-specific logic +4. Validate and test + +**Option C: Hybrid Approach (Recommended)** +1. Use Claude.ai for initial code generation +2. Refine using templates and guidelines +3. Validate with automated tools +4. Deploy and test on target device + +--- + +## Step-by-Step: Regenerate a Module with Claude.ai + +### Example: Regenerating System Hub Module + +#### 1. Gather Context + +Before prompting Claude, gather these resources: + +```bash +# Read the module specification +cat FEATURE-REGENERATION-PROMPTS.md | grep -A 200 "System Hub" + +# Review the design system +cat DEVELOPMENT-GUIDELINES.md | grep -A 100 "Design System" + +# Check existing implementation (if available) +ls -la luci-app-system-hub/ +``` + +#### 2. Prepare the Prompt + +Create a comprehensive prompt for Claude.ai: + +``` +I need you to implement the System Hub module for OpenWrt LuCI framework. + +IMPORTANT CONSTRAINTS: +- OpenWrt uses LuCI framework (not React/Vue) +- JavaScript uses L.view.extend() pattern (not ES6 modules) +- Backend is RPCD (shell scripts) communicating via ubus +- CSS must use variables from system-hub/common.css +- All code must be production-ready and match live demo +- Follow the design system exactly + +TECHNICAL REQUIREMENTS: +- RPCD script MUST be named: luci.system-hub +- Menu paths MUST match view file locations +- Use CSS variables (--sh-*) for all colors +- Support dark mode with [data-theme="dark"] +- Implement proper error handling +- Add loading states for async operations + +REFERENCE DOCUMENTS: +1. Live Demo: https://secubox.cybermood.eu/system-hub +2. Feature Specification: [paste from FEATURE-REGENERATION-PROMPTS.md] +3. Code Templates: [paste relevant templates from CODE-TEMPLATES.md] + +Please provide: +1. Complete JavaScript view files (overview.js, services.js, etc.) +2. RPCD backend script (luci.system-hub) +3. API module (system-hub/api.js) +4. CSS styles (system-hub/dashboard.css) +5. Menu configuration JSON +6. ACL configuration JSON + +Make sure all code matches the live demo visual design and functionality. +``` + +#### 3. Generate Code + +Paste your prompt into Claude.ai and let it generate the implementation. + +#### 4. Review Generated Code + +Check the generated code against these requirements: + +**API Module Checklist:** +- [ ] Uses `'use strict';` +- [ ] Requires `baseclass` and `rpc` +- [ ] All RPC methods use `rpc.declare()` +- [ ] Object names match RPCD script name (`luci.system-hub`) +- [ ] Helper functions included if needed +- [ ] Exports from `baseclass.extend()` + +**View Module Checklist:** +- [ ] Extends `view.extend()` +- [ ] Implements `load()` method returning Promise +- [ ] Implements `render(data)` method +- [ ] Uses `E()` helper for DOM building +- [ ] Implements `poll.add()` for auto-refresh +- [ ] Proper error handling with try/catch +- [ ] Uses `ui.showModal()` for loading states +- [ ] Uses `ui.addNotification()` for user feedback + +**RPCD Backend Checklist:** +- [ ] Starts with `#!/bin/sh` +- [ ] Sources `/lib/functions.sh` and `/usr/share/libubox/jshn.sh` +- [ ] Implements `list` case with method declarations +- [ ] Implements `call` case with method routing +- [ ] All methods output valid JSON using `json_*` functions +- [ ] Proper parameter validation +- [ ] Error handling with appropriate messages + +**Menu JSON Checklist:** +- [ ] Paths follow `admin/secubox//` +- [ ] First entry uses `"type": "firstchild"` +- [ ] View entries use `"type": "view"` with correct `"path"` +- [ ] Paths match view file locations +- [ ] Proper `"order"` values for menu positioning +- [ ] Depends on correct ACL entry + +**ACL JSON Checklist:** +- [ ] Entry name matches package name +- [ ] All read methods listed under `"read"."ubus"` +- [ ] All write methods listed under `"write"."ubus"` +- [ ] ubus object names match RPCD script name +- [ ] UCI config access granted if needed + +**CSS Checklist:** +- [ ] Imports `system-hub/common.css` +- [ ] Uses CSS variables (`var(--sh-*)`) +- [ ] Supports dark mode with `[data-theme="dark"]` +- [ ] Responsive grid layouts +- [ ] Smooth transitions and animations +- [ ] JetBrains Mono for numeric values + +#### 5. Integrate into Codebase + +```bash +# Create module directory structure +mkdir -p luci-app-system-hub/htdocs/luci-static/resources/system-hub +mkdir -p luci-app-system-hub/htdocs/luci-static/resources/view/system-hub +mkdir -p luci-app-system-hub/root/usr/libexec/rpcd +mkdir -p luci-app-system-hub/root/usr/share/luci/menu.d +mkdir -p luci-app-system-hub/root/usr/share/rpcd/acl.d + +# Copy generated files to appropriate locations +# (Copy from Claude's output to respective files) + +# Set RPCD script as executable +chmod +x luci-app-system-hub/root/usr/libexec/rpcd/luci.system-hub +``` + +#### 6. Validate Implementation + +```bash +# Fix permissions first (CRITICAL) +./secubox-tools/fix-permissions.sh --local + +# Run comprehensive validation (7 checks) +./secubox-tools/validate-modules.sh + +# Expected output: +# ✅ All checks passed +# OR +# ❌ Errors found with specific fix instructions +``` + +#### 7. Build Locally + +```bash +# Build single module +./secubox-tools/local-build.sh build luci-app-system-hub + +# Or build all modules +./secubox-tools/local-build.sh build + +# Or full validation + build +./secubox-tools/local-build.sh full +``` + +#### 8. Deploy to Test Router + +```bash +# Transfer package +scp build/x86-64/luci-app-system-hub*.ipk root@192.168.1.1:/tmp/ + +# Install on router +ssh root@192.168.1.1 << 'EOF' +opkg install /tmp/luci-app-system-hub*.ipk +/etc/init.d/rpcd restart +/etc/init.d/uhttpd restart +EOF + +# Fix permissions on deployed router (if needed) +./secubox-tools/fix-permissions.sh --remote +``` + +#### 9. Test in Browser + +1. Navigate to `http://192.168.1.1/cgi-bin/luci` +2. Go to SecuBox → System → System Hub +3. Verify: + - Page loads without errors + - Data displays correctly + - Actions work (buttons, forms) + - Auto-refresh updates data + - Styling matches demo + - Dark mode works + - Responsive design works on mobile + +#### 10. Iterate and Refine + +If issues found: +1. Check browser console for JavaScript errors +2. Check router logs: `ssh root@192.168.1.1 "logread | tail -50"` +3. Verify RPCD methods work: `ubus call luci.system-hub status` +4. Fix issues in local files +5. Rebuild and redeploy +6. Test again + +--- + +## Common Implementation Patterns + +### Pattern 1: Multi-Tab Dashboard + +**Example:** System Hub with 9 tabs + +```javascript +// In render() +var tabs = [ + { id: 'overview', title: 'Overview', icon: '🏠' }, + { id: 'services', title: 'Services', icon: '⚙️' }, + { id: 'logs', title: 'Logs', icon: '📋' } +]; + +var activeTab = 'overview'; + +// Render tab navigation +var tabNav = E('div', { 'class': 'sh-nav-tabs' }, + tabs.map(function(tab) { + return E('div', { + 'class': 'sh-nav-tab' + (activeTab === tab.id ? ' active' : ''), + 'click': function() { + // Switch tab logic + document.querySelectorAll('.sh-nav-tab').forEach(function(t) { + t.classList.remove('active'); + }); + this.classList.add('active'); + // Show/hide tab content + } + }, [ + E('span', {}, tab.icon), + E('span', {}, tab.title) + ]); + }) +); + +// Render tab content +var tabContent = E('div', { 'class': 'tab-content' }, [ + // Overview tab + E('div', { 'class': 'tab-pane' + (activeTab === 'overview' ? ' active' : ''), 'data-tab': 'overview' }, [ + this.renderOverviewContent() + ]), + // Services tab + E('div', { 'class': 'tab-pane' + (activeTab === 'services' ? ' active' : ''), 'data-tab': 'services' }, [ + this.renderServicesContent() + ]) +]); +``` + +### Pattern 2: Filter Tabs with Data Filtering + +**Example:** SecuBox module grid with category filtering + +```javascript +// Filter tabs +var filterTabs = E('div', { 'class': 'sh-filter-tabs' }, [ + E('div', { + 'class': 'sh-filter-tab active', + 'data-filter': 'all', + 'click': function(ev) { + document.querySelectorAll('.sh-filter-tab').forEach(function(t) { + t.classList.remove('active'); + }); + this.classList.add('active'); + self.filterModules('all'); + } + }, [ + E('span', { 'class': 'sh-tab-icon' }, '📦'), + E('span', { 'class': 'sh-tab-label' }, 'All') + ]), + E('div', { + 'class': 'sh-filter-tab', + 'data-filter': 'security', + 'click': function(ev) { + document.querySelectorAll('.sh-filter-tab').forEach(function(t) { + t.classList.remove('active'); + }); + this.classList.add('active'); + self.filterModules('security'); + } + }, [ + E('span', { 'class': 'sh-tab-icon' }, '🛡️'), + E('span', { 'class': 'sh-tab-label' }, 'Security') + ]) +]); + +// Filter function +filterModules: function(category) { + var modules = document.querySelectorAll('.module-card'); + modules.forEach(function(module) { + if (category === 'all' || module.dataset.category === category) { + module.style.display = 'block'; + } else { + module.style.display = 'none'; + } + }); +} +``` + +### Pattern 3: Real-Time Log Viewer + +**Example:** System Hub logs tab + +```javascript +// Logs view with auto-scroll and auto-refresh +renderLogsTab: function() { + var self = this; + var autoScroll = true; + var autoRefresh = true; + var refreshInterval = 5; // seconds + + var logsContainer = E('div', { 'class': 'logs-container' }); + + // Load logs + var loadLogs = function() { + API.getLogs(100, '').then(function(result) { + var logs = result.logs || []; + + dom.content(logsContainer, + logs.map(function(log) { + return E('div', { 'class': 'log-line' }, log); + }) + ); + + // Auto-scroll to bottom + if (autoScroll) { + logsContainer.scrollTop = logsContainer.scrollHeight; + } + }); + }; + + // Initial load + loadLogs(); + + // Auto-refresh + if (autoRefresh) { + setInterval(loadLogs, refreshInterval * 1000); + } + + return E('div', {}, [ + // Controls + E('div', { 'class': 'logs-controls' }, [ + E('label', {}, [ + E('input', { + 'type': 'checkbox', + 'checked': autoScroll, + 'change': function() { autoScroll = this.checked; } + }), + ' Auto-scroll' + ]), + E('label', {}, [ + E('input', { + 'type': 'checkbox', + 'checked': autoRefresh, + 'change': function() { autoRefresh = this.checked; } + }), + ' Auto-refresh' + ]), + E('button', { + 'class': 'sh-btn sh-btn-primary', + 'click': loadLogs + }, '🔄 Refresh Now') + ]), + // Logs display + logsContainer + ]); +} +``` + +### Pattern 4: Action Buttons with Confirmation + +**Example:** Service management buttons + +```javascript +// Render action button with confirmation +renderActionButton: function(service, action, label, btnClass) { + var self = this; + + return E('button', { + 'class': 'sh-btn ' + btnClass, + 'click': function(ev) { + // Show confirmation modal + ui.showModal(_('Confirm Action'), [ + E('p', {}, _('Are you sure you want to %s service %s?').format(action, service)), + E('div', { 'class': 'right' }, [ + E('button', { + 'class': 'sh-btn sh-btn-secondary', + 'click': ui.hideModal + }, _('Cancel')), + E('button', { + 'class': 'sh-btn sh-btn-primary', + 'click': function() { + ui.hideModal(); + self.performServiceAction(service, action); + } + }, _('Confirm')) + ]) + ]); + } + }, label); +}, + +// Perform service action +performServiceAction: function(service, action) { + var self = this; + + ui.showModal(_('Performing Action'), [ + E('p', {}, E('em', { 'class': 'spinning' }, _('Please wait...'))) + ]); + + API.serviceAction(service, action).then(function(result) { + ui.hideModal(); + + if (result.success) { + ui.addNotification(null, E('p', _('Action completed successfully')), 'success'); + self.handleRefresh(); + } else { + ui.addNotification(null, E('p', _('Action failed: %s').format(result.message)), 'error'); + } + }).catch(function(error) { + ui.hideModal(); + ui.addNotification(null, E('p', _('Error: %s').format(error.message)), 'error'); + }); +} +``` + +### Pattern 5: Form with Validation + +**Example:** Settings page + +```javascript +renderSettingsForm: function() { + var self = this; + var settings = this.settingsData || {}; + + return E('form', { 'class': 'settings-form' }, [ + // Text input + E('div', { 'class': 'form-group' }, [ + E('label', {}, 'Hostname'), + E('input', { + 'type': 'text', + 'class': 'form-control', + 'value': settings.hostname || '', + 'id': 'input-hostname' + }) + ]), + + // Number input with validation + E('div', { 'class': 'form-group' }, [ + E('label', {}, 'Refresh Interval (seconds)'), + E('input', { + 'type': 'number', + 'class': 'form-control', + 'value': settings.refresh_interval || 30, + 'min': 10, + 'max': 300, + 'id': 'input-refresh' + }) + ]), + + // Checkbox + E('div', { 'class': 'form-group' }, [ + E('label', {}, [ + E('input', { + 'type': 'checkbox', + 'checked': settings.auto_refresh || false, + 'id': 'input-auto-refresh' + }), + ' Enable auto-refresh' + ]) + ]), + + // Submit button + E('div', { 'class': 'form-actions' }, [ + E('button', { + 'class': 'sh-btn sh-btn-primary', + 'type': 'submit', + 'click': function(ev) { + ev.preventDefault(); + self.handleSaveSettings(); + } + }, 'Save Settings') + ]) + ]); +}, + +handleSaveSettings: function() { + var hostname = document.getElementById('input-hostname').value; + var refreshInterval = parseInt(document.getElementById('input-refresh').value); + var autoRefresh = document.getElementById('input-auto-refresh').checked; + + // Validate + if (!hostname) { + ui.addNotification(null, E('p', _('Hostname is required')), 'error'); + return; + } + + if (refreshInterval < 10 || refreshInterval > 300) { + ui.addNotification(null, E('p', _('Refresh interval must be between 10 and 300 seconds')), 'error'); + return; + } + + // Save via API + API.saveSettings(hostname, refreshInterval, autoRefresh).then(function(result) { + if (result.success) { + ui.addNotification(null, E('p', _('Settings saved successfully')), 'success'); + } else { + ui.addNotification(null, E('p', _('Failed to save settings: %s').format(result.message)), 'error'); + } + }); +} +``` + +--- + +## Module-Specific Notes + +### System Hub (luci-app-system-hub) +- **Complexity:** High - 9 tabs, many features +- **Key Features:** Health monitoring, service management, system logs, backup/restore +- **Special Requirements:** Integration with SecuBox for components list +- **Dependencies:** Calls `luci.secubox` for module enumeration + +### WireGuard Dashboard (luci-app-wireguard-dashboard) +- **Complexity:** Medium +- **Key Features:** Peer management, QR code generation, traffic stats +- **Special Requirements:** QR code generation (use qrencode or JavaScript library) +- **Dependencies:** WireGuard tools (`wg` command) + +### CrowdSec Dashboard (luci-app-crowdsec-dashboard) +- **Complexity:** Medium +- **Key Features:** Threat intelligence, decisions management, bouncers +- **Special Requirements:** Parse CrowdSec CLI output +- **Dependencies:** CrowdSec (`cscli` command) + +### Netdata Dashboard (luci-app-netdata-dashboard) +- **Complexity:** Low - mostly embedding iframe +- **Key Features:** Embedded Netdata UI, quick metrics overview +- **Special Requirements:** Netdata API integration +- **Dependencies:** Netdata service + +### Network Modes (luci-app-network-modes) +- **Complexity:** High - UCI manipulation +- **Key Features:** Network topology wizard, configuration preview +- **Special Requirements:** UCI config validation, rollback mechanism +- **Dependencies:** Network, firewall, DHCP configs + +--- + +## Troubleshooting Guide + +### Issue: "Object not found" Error + +**Symptoms:** +``` +RPC call to luci.module-name/method failed with error -32000: Object not found +``` + +**Diagnosis:** +```bash +# 1. Check RPCD script exists and is executable +ls -la luci-app-module-name/root/usr/libexec/rpcd/ + +# 2. Check RPCD script name matches ubus object +grep "object:" luci-app-module-name/htdocs/luci-static/resources/module-name/api.js + +# 3. Test RPCD script manually +ssh root@router "/usr/libexec/rpcd/luci.module-name list" + +# 4. Check RPCD logs +ssh root@router "logread | grep rpcd | tail -20" +``` + +**Solutions:** +1. Rename RPCD script to match ubus object name (must include `luci.` prefix) +2. Make script executable: `chmod +x luci.module-name` +3. Restart RPCD: `/etc/init.d/rpcd restart` +4. Reinstall package if deployed + +### Issue: View Not Loading (404) + +**Symptoms:** +``` +HTTP error 404 while loading class file '/luci-static/resources/view/module-name/overview.js' +``` + +**Diagnosis:** +```bash +# 1. Check menu path +cat luci-app-module-name/root/usr/share/luci/menu.d/*.json | grep "path" + +# 2. Check view file exists +ls -la luci-app-module-name/htdocs/luci-static/resources/view/ + +# 3. Verify paths match +# Menu: "path": "module-name/overview" +# File: view/module-name/overview.js +``` + +**Solutions:** +1. Update menu path to match view file location +2. OR move view files to match menu path +3. Rebuild and redeploy package + +### Issue: CSS Not Applied + +**Symptoms:** +- Unstyled page +- Missing colors, fonts, or layout + +**Diagnosis:** +```bash +# 1. Check browser console for CSS 404 errors +# (Open browser developer tools) + +# 2. Verify CSS import in view file +grep "stylesheet" luci-app-module-name/htdocs/luci-static/resources/view/*/overview.js + +# 3. Check CSS file exists +ls -la luci-app-module-name/htdocs/luci-static/resources/module-name/dashboard.css +``` + +**Solutions:** +1. Verify CSS import path: `L.resource('module-name/dashboard.css')` +2. Import common.css: `@import url('../system-hub/common.css');` +3. Check file permissions: `644` for CSS files +4. Clear browser cache (Ctrl+Shift+R) + +### Issue: Data Not Updating + +**Symptoms:** +- Dashboard shows stale data +- Auto-refresh not working + +**Diagnosis:** +```bash +# 1. Check poll is registered +# (Look for poll.add() in render() method) + +# 2. Check API calls return Promises +# (Verify methods return results from rpc.declare()) + +# 3. Test API methods directly +ssh root@router "ubus call luci.module-name status" +``` + +**Solutions:** +1. Add poll.add() to render() method +2. Verify API calls in poll callback return Promises +3. Ensure updateDashboard() updates correct DOM elements +4. Check browser console for JavaScript errors + +--- + +## Best Practices + +### 1. Code Organization + +**DO:** +- Keep related code together (API methods, helpers) +- Use descriptive variable and function names +- Add comments for complex logic +- Break large functions into smaller helpers + +**DON'T:** +- Put all code in one massive function +- Use single-letter variable names (except in loops) +- Duplicate code - create helper functions instead +- Leave commented-out code in production + +### 2. Error Handling + +**DO:** +```javascript +API.getData().then(function(result) { + if (result && result.data) { + // Process data + } else { + console.warn('No data returned'); + // Show empty state + } +}).catch(function(error) { + console.error('API error:', error); + ui.addNotification(null, E('p', 'Failed to load data'), 'error'); +}); +``` + +**DON'T:** +```javascript +API.getData().then(function(result) { + // Process data without checking + result.data.forEach(function(item) { ... }); // Will crash if data is null +}); +``` + +### 3. Performance + +**DO:** +- Use poll.add() instead of setInterval for auto-refresh +- Update specific DOM elements instead of full re-render +- Debounce search inputs +- Lazy load data only when needed + +**DON'T:** +- Re-render entire view on every update +- Poll too frequently (<10 seconds) +- Load all data upfront +- Perform expensive operations in render() + +### 4. User Experience + +**DO:** +- Show loading states (spinners, skeleton screens) +- Provide feedback for actions (success/error notifications) +- Confirm destructive actions (delete, restart) +- Use descriptive error messages + +**DON'T:** +- Leave users waiting without feedback +- Silent failures +- Generic error messages ("Error occurred") +- Allow destructive actions without confirmation + +--- + +## Deployment Checklist + +Before deploying to production: + +- [ ] **Code Quality** + - [ ] All validation checks pass + - [ ] No JavaScript errors in console + - [ ] No shell script errors (shellcheck) + - [ ] All JSON files valid (jsonlint) + +- [ ] **Functionality** + - [ ] All tabs/pages load correctly + - [ ] All actions work as expected + - [ ] Data displays correctly + - [ ] Auto-refresh updates data + - [ ] Forms validate input + - [ ] Error handling works + +- [ ] **Design** + - [ ] Matches live demo visually + - [ ] Dark mode works + - [ ] Responsive on mobile + - [ ] Consistent with other modules + - [ ] No layout issues + +- [ ] **Performance** + - [ ] Page loads quickly (<2s) + - [ ] Auto-refresh doesn't freeze UI + - [ ] No memory leaks + - [ ] Efficient data fetching + +- [ ] **Security** + - [ ] ACL permissions correct + - [ ] Input validation on frontend and backend + - [ ] No hardcoded credentials + - [ ] Safe command execution (no injection) + +- [ ] **Documentation** + - [ ] README.md updated + - [ ] Comments in complex code + - [ ] Menu entries have descriptions + - [ ] ACL entries have descriptions + +--- + +## Additional Resources + +### Documentation +- [LuCI API Reference](https://openwrt.github.io/luci/api/) +- [OpenWrt Developer Guide](https://openwrt.org/docs/guide-developer/start) +- [UCI Configuration](https://openwrt.org/docs/guide-user/base-system/uci) +- [ubus Documentation](https://openwrt.org/docs/techref/ubus) + +### Live Demo +- **Main Demo:** https://secubox.cybermood.eu +- **System Hub:** https://secubox.cybermood.eu/system-hub +- **CrowdSec:** https://secubox.cybermood.eu/crowdsec +- **WireGuard:** https://secubox.cybermood.eu/wireguard + +### Internal Documentation +- [FEATURE-REGENERATION-PROMPTS.md](./FEATURE-REGENERATION-PROMPTS.md) - All module specifications +- [CODE-TEMPLATES.md](./CODE-TEMPLATES.md) - Implementation templates +- [DEVELOPMENT-GUIDELINES.md](./DEVELOPMENT-GUIDELINES.md) - Complete dev guide +- [QUICK-START.md](./QUICK-START.md) - Quick reference +- [CLAUDE.md](./CLAUDE.md) - Build system reference + +### Tools +- [SecuBox Tools](./secubox-tools/) - Validation, build, deployment scripts +- [GitHub Actions](./.github/workflows/) - CI/CD workflows +- [Templates](./templates/) - Module templates + +--- + +## Getting Help + +If you encounter issues not covered in this guide: + +1. **Check Existing Modules:** Look at working modules for reference implementations +2. **Run Validation:** `./secubox-tools/validate-modules.sh` for automated checks +3. **Check Logs:** `logread | grep -i error` on the router +4. **Review Documentation:** Read DEVELOPMENT-GUIDELINES.md for detailed explanations +5. **Contact Support:** support@cybermind.fr + +--- + +**Document Version:** 1.0.0 +**Last Updated:** 2025-12-27 +**Maintainer:** CyberMind.fr +**Live Demo:** https://secubox.cybermood.eu