## AI Master Prompt: CertMate - Automated TLS for Network Devices
**1. PROJECT OVERVIEW:**
CertMate is a Software-as-a-Service (SaaS) platform designed to automate the installation, renewal, and management of Let's Encrypt TLS certificates for network-attached devices, starting with printers and expandable to other devices like NAS, routers, and IoT devices. The core problem addressed is the complexity and manual effort required to secure these devices with valid TLS certificates, which often leads to outdated or self-signed certificates, exposing them to security risks. CertMate simplifies this process by providing a user-friendly interface and automated workflows, ensuring that all connected devices are securely accessed via HTTPS, thus enhancing network security and compliance. The value proposition is 'Effortless and automated TLS security for all your network devices'.
**2. TECH STACK:**
- **Frontend:** React with Next.js (App Router for enhanced routing and server components)
- **Styling:** Tailwind CSS (for rapid and utility-first styling)
- **UI Components:** shadcn/ui (for accessible, reusable, and customizable UI components)
- **Backend/API:** Next.js API Routes or a separate Node.js/Express.js server
- **Database ORM:** Drizzle ORM (for type-safe database interactions)
- **Database:** PostgreSQL (recommended for robustness and Drizzle compatibility)
- **Authentication:** NextAuth.js (for secure and flexible authentication)
- **Background Jobs/Cron:** A job scheduler like `node-cron` or a dedicated service (e.g., BullMQ with Redis) for certificate renewal tasks.
- **Certificate Management:** Integration with Certbot CLI (potentially via SSH or a custom agent on the device if direct Certbot execution is not feasible, or leveraging ACME protocol directly).
- **State Management:** React Context API or Zustand for frontend state management.
- **Forms:** React Hook Form with Zod for validation.
- **Utility:** Lodash, date-fns.
**3. DATABASE SCHEMA:**
```sql
-- Users table
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name VARCHAR(255),
email VARCHAR(255) UNIQUE NOT NULL,
emailVerified TIMESTAMP(3) WITH TIME ZONE,
image TEXT,
password TEXT, -- Hashed password
created_at TIMESTAMP(3) WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP(3) WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
-- Accounts table (for NextAuth.js)
CREATE TABLE accounts (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
userId UUID REFERENCES users(id) ON DELETE CASCADE,
type VARCHAR(255) NOT NULL,
provider VARCHAR(255) NOT NULL,
providerAccountId VARCHAR(255) NOT NULL,
refresh_token TEXT,
access_token TEXT,
expires_at BIGINT,
token_type VARCHAR(255),
scope VARCHAR(255),
id_token TEXT,
UNIQUE (provider, providerAccountId)
);
-- Sessions table (for NextAuth.js)
CREATE TABLE sessions (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
sessionToken TEXT UNIQUE NOT NULL,
expires TIMESTAMP(3) WITH TIME ZONE NOT NULL,
userId UUID REFERENCES users(id) ON DELETE CASCADE
);
-- Verification tokens table (for NextAuth.js)
CREATE TABLE verification_tokens (
identifier TEXT NOT NULL,
token TEXT NOT NULL,
expires TIMESTAMP(3) WITH TIME ZONE NOT NULL,
PRIMARY KEY (identifier, token)
);
-- Devices table
CREATE TABLE devices (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID REFERENCES users(id) ON DELETE CASCADE,
name VARCHAR(255) NOT NULL,
ip_address VARCHAR(45) NOT NULL,
hostname VARCHAR(255),
type VARCHAR(100), -- e.g., 'printer', 'nas', 'router'
model VARCHAR(255),
mac_address VARCHAR(17),
port INTEGER, -- For device access, e.g., 80, 443
requires_auth BOOLEAN DEFAULT FALSE,
auth_username VARCHAR(255),
auth_password VARCHAR(255), -- Encrypted password
created_at TIMESTAMP(3) WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP(3) WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
-- Certificates table
CREATE TABLE certificates (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
device_id UUID REFERENCES devices(id) ON DELETE CASCADE,
domain_name VARCHAR(255) NOT NULL, -- e.g., printer.local or a public domain
status VARCHAR(50) DEFAULT 'pending', -- e.g., 'pending', 'active', 'expired', 'renewal_failed'
cert_path TEXT, -- Path to the certificate file on the server
key_path TEXT, -- Path to the private key file on the server
issue_date TIMESTAMP(3) WITH TIME ZONE,
expiry_date TIMESTAMP(3) WITH TIME ZONE,
renewal_count INTEGER DEFAULT 0,
last_renewal_attempt TIMESTAMP(3) WITH TIME ZONE,
renewal_error TEXT, -- Store error message if renewal fails
created_at TIMESTAMP(3) WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP(3) WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
-- Device Certbot Configurations (if needed for advanced setup)
CREATE TABLE device_certbot_configs (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
device_id UUID REFERENCES devices(id) ON DELETE CASCADE,
certbot_path VARCHAR(255), -- Path to certbot executable
config_dir VARCHAR(255), -- Path to Certbot configuration directory
pre_hook TEXT, -- Script to run before renewal
post_hook TEXT, -- Script to run after renewal (e.g., restart service)
auth_hook TEXT, -- Script for custom authentication (e.g., Cloudflare API)
created_at TIMESTAMP(3) WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP(3) WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
-- Indexes for performance
CREATE INDEX idx_devices_user_id ON devices(user_id);
CREATE INDEX idx_certificates_device_id ON certificates(device_id);
CREATE INDEX idx_certificates_status ON certificates(status);
```
**4. CORE FEATURES & USER FLOW:**
**Feature 1: Device Onboarding**
* **User Flow:**
1. User navigates to the 'Devices' section.
2. Clicks 'Add Device'.
3. Enters device details: Name (user-friendly), IP Address, Device Type (Printer, NAS, etc.), Model (optional), Port (default 80/443).
4. If 'Requires Auth' is checked, provides Username and Password for device web interface.
5. User clicks 'Add'.
6. System performs a basic network check (ping, port accessibility).
7. System attempts to detect if the device has a web interface and if Certbot is potentially installable/executable (e.g., via SSH if provided, or prompts user for manual steps if auto-detection fails).
8. If successful, the device is added to the dashboard with 'Pending Certificate' status.
9. **Edge Case:** Invalid IP, unreachable device, incorrect credentials, unsupported device type.
**Feature 2: Automated Certificate Issuance & Installation**
* **User Flow:**
1. After a device is added, the system triggers an automated process.
2. **Domain Validation (using device IP or a user-provided domain mapped to the IP):**
* **HTTP-01 Challenge:** Certbot is invoked (either directly on a server or remotely via SSH/agent) to create a temporary file at a specific webroot path on the device or server. The system uses the device's IP or hostname for the challenge.
* **Alternative (if applicable):** If the user provides a public domain name pointing to the device's public IP, standard Certbot HTTP-01 or DNS-01 challenges can be used. Cloudflare integration can be added for DNS-01.
3. **Certificate Generation:** Let's Encrypt issues the certificate.
4. **Installation:**
* The system attempts to automatically upload/configure the certificate and key on the device (e.g., via Brother's specific API, SCP, or SSH commands).
* If direct upload fails, the system provides the certificate/key files for manual download and instructions for manual upload to the device's firmware.
5. **Status Update:** The certificate status is updated to 'Active' or 'Renewal Failed' with an error message.
6. **Edge Cases:** Firewall blocking validation, incorrect device credentials, device firmware limitations, Certbot execution errors, Let's Encrypt rate limits.
**Feature 3: Automated Certificate Renewal**
* **User Flow:**
1. A scheduled background job runs daily (or as per Let's Encrypt's recommended timing).
2. The job queries the `certificates` table for certificates nearing expiry (e.g., within 30 days).
3. For each nearing certificate, it triggers the renewal process (similar to Feature 2, Step 2-4).
4. **Important:** The renewal process uses the existing validated domain/challenge method.
5. If renewal is successful, the certificate expiry date and renewal count are updated. The device is configured with the new certificate.
6. If renewal fails, the `status` is updated to `renewal_failed`, `renewal_error` is populated, and a notification is sent to the user.
7. **Edge Cases:** Network changes, IP address changes, expired device credentials, changes in device web interface, failure to execute renewal hooks.
**Feature 4: Dashboard & Monitoring**
* **User Flow:**
1. User logs in and sees a dashboard overview.
2. **Device List:** Displays all added devices with their name, IP, type, and current certificate status (e.g., Active, Expiring Soon, Expired, Renewal Failed).
3. **Certificate Details:** Clicking a device shows detailed certificate information: Domain Name, Issue Date, Expiry Date, Status, Renewal History.
4. **Actions:** Options to manually trigger renewal, re-configure device credentials, or delete a device.
5. **Notifications:** A section or toast messages for important alerts (e.g., renewal failures).
6. **Edge Cases:** Empty state (no devices added), long list of devices, filtering/sorting options.
**Feature 5: User Authentication & Management**
* **User Flow:**
1. Signup/Login page (Email/Password, OAuth - Google/GitHub).
2. Password reset functionality.
3. User profile settings (change password, email).
4. **Edge Cases:** Email verification, duplicate email registration, incorrect login credentials.
**5. API & DATA FETCHING:**
- **Auth API:** Handled by NextAuth.js (`/api/auth/[...nextauth]`).
- **Device API (`/api/devices`):**
* `POST /api/devices`: Add a new device. Request body: `{ name, ip_address, type, model, port, requires_auth, auth_username, auth_password }`. Response: `{ success: true, device: {...} }` or error.
* `GET /api/devices`: Get all devices for the logged-in user. Response: `[{ id, name, ip_address, status, ... }, ...]`. Status is derived from the latest certificate data for that device.
* `GET /api/devices/{id}`: Get details for a specific device. Response: `{ ..., certificate: {...} }`.
* `PUT /api/devices/{id}`: Update device details. Request body: same as POST.
* `DELETE /api/devices/{id}`: Delete a device.
- **Certificate API (`/api/certificates`):**
* `POST /api/certificates/renew/{deviceId}`: Manually trigger renewal for a specific device. Response: `{ success: true, message: 'Renewal initiated' }` or error.
- **Data Fetching (Client-side):** Use `fetch` API or libraries like SWR/React Query within components to get data from the above API routes. For server components in Next.js, data fetching will be done directly in the component using server-side functions.
- **Data Flow:** API routes interact with Drizzle ORM to query/mutate the PostgreSQL database. Frontend components fetch data from API routes or directly in Server Components. State is managed locally within components or globally using Zustand/Context.
**6. COMPONENT BREAKDOWN (Next.js App Router):**
- **`app/layout.tsx`:** Root layout, includes global styles, providers (e.g., NextAuth SessionProvider), and base HTML structure.
- **`app/page.tsx`:** Landing page (marketing content, not part of MVP functionality).
- **`app/(auth)/signin/page.tsx`:** Sign-in page.
- **`app/(auth)/signup/page.tsx`:** Sign-up page.
- **`app/(auth)/reset-password/page.tsx`:** Password reset page.
- **`app/dashboard/layout.tsx`:** Dashboard layout, includes sidebar/navbar, main content area.
- **`app/dashboard/page.tsx`:** Main dashboard view. Fetches and displays a list of devices, their status, and summary stats. Handles empty state. (Server Component).
- **`app/dashboard/devices/page.tsx`:** Detailed device list view, possibly with filtering/sorting. (Server Component).
- **`app/dashboard/devices/[deviceId]/page.tsx`:** Individual device detail view. Shows certificate info, renewal status, history, and device configuration. Includes forms for editing device details or triggering manual actions. (Server Component with Client Components for forms/interactions).
- **`app/dashboard/devices/new/page.tsx`:** Page with a form to add a new device. Uses `react-hook-form`. (Client Component).
- **`app/settings/page.tsx`:** User profile and settings page.
- **`components/ui/`:** Reusable shadcn/ui components (Button, Input, Card, Table, Form, Dialog, Alert, etc.).
- **`components/auth/`:** Authentication related components (e.g., Sign-in form, OAuth buttons).
- **`components/devices/`:** Components specific to device management (e.g., `DeviceTable`, `DeviceStatusBadge`, `AddDeviceForm`, `CertificateDetails`).
- **`components/layout/`:** Navbar, Sidebar, Footer components.
- **`components/common/`:** Loading spinners, error message components, empty state placeholders.
- **`lib/`:** Utility functions, database client setup (Drizzle), API client helpers, auth configuration.
- **`services/`:** Backend logic, API route handlers, certbot integration logic, job scheduling setup.
**7. UI/UX DESIGN & VISUAL IDENTITY:**
- **Design Style:** Modern, Clean, and Professional.
- **Color Palette:**
* Primary: `#4F46E5` (Indigo-500) - For buttons, active states.
* Secondary: `#6366F1` (Indigo-600) - Accents.
* Background: `#FFFFFF` (White) or a very light grey `#F9FAFB` for main background.
* Dark Mode Background: `#111827` (Gray-900)
* Text (Light): `#1F2937` (Gray-800)
* Text (Dark): `#F3F4F6` (Gray-200)
* Accent/Success: `#10B981` (Green-500)
* Warning/Expiring: `#F59E0B` (Amber-500)
* Error/Failed: `#EF4444` (Red-500)
- **Typography:** Inter (or a similar clean sans-serif font like Inter, Poppins).
* Headings: Bold, varying weights.
* Body Text: Regular weight.
- **Layout:** Use a consistent grid system (e.g., Tailwind's default). Clear separation between sections. Sidebar navigation for logged-in users. Clean forms with clear labels and validation feedback.
- **Responsiveness:** Mobile-first approach. Ensure full usability on tablets and desktops. Sidebar might collapse into a hamburger menu on smaller screens.
- **Visual Elements:** Subtle use of icons (Lucide React recommended). Clean data tables. Progress indicators for long operations.
**8. SAMPLE/MOCK DATA:**
* **User:**
```json
{
"id": "user-uuid-123",
"name": "Alice Smith",
"email": "alice@example.com"
}
```
* **Device (Added, Pending Cert):**
```json
{
"id": "device-uuid-abc",
"userId": "user-uuid-123",
"name": "Living Room Printer",
"ip_address": "192.168.1.100",
"type": "printer",
"model": "Brother HL-L2350DW",
"status": "pending", // Derived status
"port": 80
}
```
* **Device (Active Cert):**
```json
{
"id": "device-uuid-def",
"userId": "user-uuid-123",
"name": "Office NAS",
"ip_address": "192.168.1.150",
"type": "nas",
"model": "Synology DS220j",
"status": "active",
"port": 443
}
```
* **Certificate (Active):**
```json
{
"id": "cert-uuid-xyz",
"deviceId": "device-uuid-def",
"domain_name": "nas.local",
"status": "active",
"issue_date": "2023-10-27T10:00:00Z",
"expiry_date": "2024-01-25T10:00:00Z",
"renewal_count": 1
}
```
* **Certificate (Expiring Soon):**
```json
{
"id": "cert-uuid-uvw",
"deviceId": "device-uuid-abc",
"domain_name": "printer.local",
"status": "active", // System will flag as 'Expiring Soon'
"issue_date": "2023-08-01T10:00:00Z",
"expiry_date": "2023-10-30T10:00:00Z",
"renewal_count": 0
}
```
* **Certificate (Renewal Failed):**
```json
{
"id": "cert-uuid-rst",
"deviceId": "device-uuid-ghi",
"domain_name": "router.local",
"status": "renewal_failed",
"issue_date": "2023-07-01T10:00:00Z",
"expiry_date": "2023-09-29T10:00:00Z",
"renewal_count": 2,
"last_renewal_attempt": "2023-09-25T10:00:00Z",
"renewal_error": "Challenge validation failed. Check network connectivity and device auth."
}
```
**9. TURKISH TRANSLATIONS:**
- **App Title:** CertMate (Sertifika Yöneticisi)
- **Dashboard:** Kontrol Paneli
- **Devices:** Cihazlar
- **Add Device:** Cihaz Ekle
- **Settings:** Ayarlar
- **Sign In:** Giriş Yap
- **Sign Up:** Kayıt Ol
- **Logout:** Çıkış Yap
- **Name:** İsim
- **IP Address:** IP Adresi
- **Status:** Durum
- **Active:** Aktif
- **Expiring Soon:** Yakında Süresi Dolacak
- **Expired:** Süresi Doldu
- **Renewal Failed:** Yenileme Başarısız
- **Pending:** Beklemede
- **Issue Date:** Yayın Tarihi
- **Expiry Date:** Son Kullanma Tarihi
- **Renew Certificate:** Sertifikayı Yenile
- **Edit Device:** Cihazı Düzenle
- **Delete Device:** Cihazı Sil
- **Save Changes:** Değişiklikleri Kaydet
- **Enter your email:** E-posta adresinizi girin
- **Enter your password:** Şifrenizi girin
- **Forgot Password?** Şifremi Unuttum?
- **Next:** Sonraki
- **Back:** Geri
- **Submit:** Gönder
- **Success:** Başarılı
- **Error:** Hata
- **Are you sure you want to delete this device?** Bu cihazı silmek istediğinizden emin misiniz?
- **Certificate renewal initiated.** Sertifika yenileme başlatıldı.
- **Automated TLS security for your network devices.** Ağ cihazlarınız için otomatik TLS güvenliği.
- **Effortless management and renewal.** Zahmetsiz yönetim ve yenileme.
- **Get Started:** Başlayın
**10. ANIMATIONS:**
- **Page Transitions:** Subtle fade-in/fade-out transitions between pages using Next.js's built-in features or libraries like `Framer Motion`.
- **Button Hovers:** Slight scale-up or background color change on hover.
- **Loading States:** Use spinners (e.g., from shadcn/ui or a custom SVG) with smooth transitions for data fetching or form submissions.
- **Table Row Hover:** Subtle background highlight on table row hover.
- **Form Validation:** Animate error messages appearing.
**11. EDGE CASES (Summary):**
- **Authentication:** Robust handling of sign-in, sign-out, password reset, email verification. OAuth flows.
- **Authorization:** Ensure users can only access and manage their own devices and data.
- **Empty States:** Graceful handling of scenarios with no devices, no certificates, etc., with clear calls to action.
- **Error Handling:** Comprehensive error handling for API requests, background jobs, and Certbot operations. Display user-friendly error messages.
- **Validation:** Client-side and server-side validation for all form inputs (device details, user credentials).
- **Network Issues:** Handle device unreachability, network interruptions during renewal. Implement retries with backoff.
- **Device Specifics:** Account for different device firmwares, web interfaces, and potential API limitations. Provide fallback manual instructions.
- **Certbot Execution:** Manage potential errors during Certbot execution (permissions, path issues, validation failures). Consider using Docker for isolated Certbot environments if running server-side.
- **Security:** Encrypt sensitive data like device passwords at rest. Use secure authentication practices (HTTPS, secure cookies/tokens).
- **Rate Limiting:** Be mindful of Let's Encrypt rate limits and implement strategies to avoid hitting them (e.g., renewal logic based on expiry, avoiding unnecessary retries).