# ktovoz/moemail architecture

> Architecture diagram of the GitHub repository ktovoz/moemail, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2025-04-19). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/ktovoz/moemail
- Repository: https://github.com/ktovoz/moemail

## Overview

##### Project Type and Purpose
- MoeMail is a full‑stack, serverless temporary email service built on Next.js (App Router) and Cloudflare’s edge platform.
- It offers a React‑based frontend, Next.js API routes for business logic, Cloudflare D1 (SQLite) as the primary database, Cloudflare KV for configuration, and two standalone Cloudflare Workers (email‑receiver and cleanup).
- Users authenticate via GitHub OAuth (NextAuth), create disposable mailboxes, receive messages (real‑time or Webhook), and manage roles/API keys under an RBAC system.

##### File Structure Analysis
- **app/** – Next.js App Router with UI under **components/** and page layouts, plus serverless API routes under **app/api/**.
- **lib/** – shared utilities: DB (Drizzle ORM), auth, permissions, webhook helper, schema definitions.
- **config/** & **hooks/** – runtime config loaders and custom React hooks.
- **drizzle.config.ts**, **drizzle/** – database migration scripts and metadata snapshots for D1 via Drizzle ORM.
- **workers/** – two standalone workers:
- **email-receiver.ts** handles inbound email via Cloudflare Email Routing.
- **cleanup.ts** performs scheduled purging of expired mailboxes/messages.
- **scripts/** – CLI tools for test data generation, local/remote migrations, and local webhook test server.
- **public/** – static assets & PWA manifest.
- **.github/workflows/deploy.yml** – GitHub Actions for CI/CD: migrations, Pages, and Workers deployment.
- **wrangler*.toml** – Cloudflare Worker configuration examples.

##### Main Components & Responsibilities
A. Frontend (Cloudflare Pages)
- React UI with SSR/SSG via Next.js App Router
- Theme provider, layout, forms, dialogs, pages for home, login, profile, mailbox views
- Calls Next.js API routes (fetch/browser) or direct fetch for OpenAPI endpoints with X‑API‑Key header

B. API Layer (Next.js Serverless)
- Under **app/api/**: REST endpoints for auth (NextAuth/GitHub), email generation, listing, deletion, message retrieval, roles management, config retrieval, Webhook setup, API key CRUD
- Uses **lib/db.ts** (Drizzle ORM) to query Cloudflare D1
- Reads/Writes settings in KV (via **lib/utils.ts**)

C. Data Layer
- **Cloudflare D1 (SQLite)** – primary store for users, roles, API keys, mailboxes, messages
- **Cloudflare KV** – key‑value storage for site‑wide settings (DEFAULT_ROLE, email domains, max emails…)

D. Workers Microservices
1. Email Receiver Worker
- Triggered by inbound mail routing in Cloudflare Email Routing
- Parses email, writes to D1, triggers configured Webhooks (HTTP POST)
2. Cleanup Worker
- Scheduled (cron) Worker that removes expired mailboxes/messages from D1
3. Webhook Test Server (local, via **scripts/webhook-test-server.ts**)

E. External Integrations
- **GitHub OAuth** for user authentication
- **Cloudflare Email Routing**
- **User‑provided Webhook endpoints**
- **GitHub Actions** or Wrangler CLI for automated deployments

##### Relationships & Data Flows
- User’s browser ↔ Frontend UI (Next.js)
- Frontend → Next.js API → D1 / KV / NextAuth
- Inbound email → Cloudflare Email Routing → Email Receiver Worker → D1 → Webhook HTTP POST → User’s external service
- Cron Scheduler → Cleanup Worker → D1
- Admin (Emperor) UI → API → KV to update global settings
- GitHub Actions / Wrangler → Deploy Pages + Workers + Migrations

##### Architectural Patterns & Principles
- **Separation of Concerns**: UI, API, data, and background processing separated into distinct layers/services.
- **Serverless & Edge**: All compute (UI SSR, API, Workers) runs on Cloudflare’s edge.
- **Event‑Driven**: Email receiver reacts to mail events; cleanup runs on schedule.
- **Role‑Based Access Control**: RBAC implemented in API layer, enforced via middleware.
- **Infrastructure as Code**: Wrangler and GitHub Actions automate deployments.

##### Essential Elements
- Component boundaries (Pages vs. Workers)
- Authentication flow via NextAuth/GitHub
- Data interactions with D1 and KV
- Email reception and cleanup pipelines
- Deployment triggers (GitHub Actions / Wrangler)
- Role management & API Key issuance

## Diagram (Mermaid)

```mermaid
flowchart TD
    %% External Services
    subgraph "External Services"
        direction TB
        GitHubOAuth["GitHub OAuth"]:::external
        EmailRouting["Cloudflare Email Routing"]:::external
        UserWebhook["User Webhook Endpoints"]:::external
        GitHubActions["GitHub Actions / Wrangler CLI"]:::external
    end

    %% Frontend UI
    subgraph "Frontend (Cloudflare Pages)" 
        direction TB
        Browser["User Browser"]:::external
        UI["React UI (Next.js App Router)"]:::frontend
    end

    Browser -->|"interacts with"| UI

    click UI "https://github.com/ktovoz/moemail/tree/master/app/components/"
    click UI "https://github.com/ktovoz/moemail/blob/master/app/layout.tsx"
    click UI "https://github.com/ktovoz/moemail/blob/master/app/providers.tsx"
    click UI "https://github.com/ktovoz/moemail/blob/master/app/page.tsx"
    click UI "https://github.com/ktovoz/moemail/blob/master/app/login/page.tsx"
    click UI "https://github.com/ktovoz/moemail/blob/master/app/moe/page.tsx"
    click UI "https://github.com/ktovoz/moemail/blob/master/app/profile/page.tsx"

    %% API Layer
    subgraph "API Layer (Next.js Serverless Functions)" 
        direction TB
        AuthAPI["Auth API (NextAuth/GitHub)"]:::api
        KeysAPI["API Keys CRUD"]:::api
        RolesAPI["Roles Management"]:::api
        EmailsAPI["Email Generation & Retrieval"]:::api
        WebhookAPI["Webhook Endpoints"]:::api
        ConfigAPI["Configuration Endpoint"]:::api
    end

    UI -->|"/api/* calls"| AuthAPI
    UI -->|"POST /api/api-keys"| KeysAPI
    UI -->|"POST /api/roles/*"| RolesAPI
    UI -->|"GET/POST /api/emails/*"| EmailsAPI
    UI -->|"POST /api/webhook"| WebhookAPI
    UI -->|"GET /api/config"| ConfigAPI

    click AuthAPI "https://github.com/ktovoz/moemail/blob/master/app/api/auth/[...auth]/route.ts"
    click AuthAPI "https://github.com/ktovoz/moemail/blob/master/app/api/auth/register/route.ts"
    click KeysAPI "https://github.com/ktovoz/moemail/blob/master/app/api/api-keys/route.ts"
    click KeysAPI "https://github.com/ktovoz/moemail/blob/master/app/api/api-keys/[id]/route.ts"
    click RolesAPI "https://github.com/ktovoz/moemail/blob/master/app/api/roles/init-emperor/route.ts"
    click RolesAPI "https://github.com/ktovoz/moemail/blob/master/app/api/roles/promote/route.ts"
    click RolesAPI "https://github.com/ktovoz/moemail/blob/master/app/api/roles/users/route.ts"
    click EmailsAPI "https://github.com/ktovoz/moemail/blob/master/app/api/emails/generate/route.ts"
    click EmailsAPI "https://github.com/ktovoz/moemail/blob/master/app/api/emails/route.ts"
    click EmailsAPI "https://github.com/ktovoz/moemail/blob/master/app/api/emails/[id]/route.ts"
    click EmailsAPI "https://github.com/ktovoz/moemail/blob/master/app/api/emails/[id]/[messageId]/route.ts"
    click WebhookAPI "https://github.com/ktovoz/moemail/blob/master/app/api/webhook/route.ts"
    click WebhookAPI "https://github.com/ktovoz/moemail/blob/master/app/api/webhook/test/route.ts"
    click ConfigAPI "https://github.com/ktovoz/moemail/blob/master/app/api/config/route.ts"

    %% Shared Utilities & Data Layer
    subgraph "Shared Utilities & Data Layer"
        direction TB
        DB["Drizzle ORM & D1 Integration"]:::data
        KV["Cloudflare KV Store"]:::kv
        Utils["Auth & Webhook Helpers, Permissions"]:::data
        ConfigLib["Runtime Config & Hooks"]:::data
    end

    AuthAPI -->|uses| DB
    KeysAPI -->|uses| DB
    RolesAPI -->|uses| DB
    EmailsAPI -->|uses| DB
    EmailsAPI -->|reads/writes| KV
    ConfigAPI -->|reads| KV

    click DB "https://github.com/ktovoz/moemail/blob/master/app/lib/db.ts"
    click DB "https://github.com/ktovoz/moemail/blob/master/drizzle.config.ts"
    click DB "https://github.com/ktovoz/moemail/tree/master/drizzle/"
    click KV "https://github.com/ktovoz/moemail/blob/master/app/lib/utils.ts"
    click Utils "https://github.com/ktovoz/moemail/blob/master/app/lib/auth.ts"
    click Utils "https://github.com/ktovoz/moemail/blob/master/app/lib/permissions.ts"
    click Utils "https://github.com/ktovoz/moemail/blob/master/app/lib/schema.ts"
    click Utils "https://github.com/ktovoz/moemail/blob/master/app/lib/validation.ts"
    click ConfigLib "https://github.com/ktovoz/moemail/blob/master/app/config/index.ts"
    click ConfigLib "https://github.com/ktovoz/moemail/blob/master/app/config/email.ts"
    click ConfigLib "https://github.com/ktovoz/moemail/blob/master/app/config/webhook.ts"
    click ConfigLib "https://github.com/ktovoz/moemail/blob/master/app/hooks/use-config.ts"
    click ConfigLib "https://github.com/ktovoz/moemail/blob/master/app/hooks/use-user-role.ts"
    click ConfigLib "https://github.com/ktovoz/moemail/blob/master/app/hooks/use-role-permission.ts"
    click ConfigLib "https://github.com/ktovoz/moemail/blob/master/app/hooks/use-copy.ts"
    click ConfigLib "https://github.com/ktovoz/moemail/blob/master/app/hooks/use-throttle.ts"

    %% Data Stores
    subgraph "Data Stores"
        direction TB
        D1["Cloudflare D1 (SQLite)"]:::database
        KVStore["Cloudflare KV"]:::kv
    end

    DB -->|queries| D1
    KV -->|manages| KVStore

    %% Workers
    subgraph "Workers Microservices"
        direction TB
        Receiver["Email Receiver Worker"]:::worker
        Cleanup["Cleanup Worker (cron)"]:::worker
        WebhookTest["Webhook Test Server (local)"]:::worker
    end

    EmailRouting -->|onMailReceived| Receiver
    Receiver -->|writes to| D1
    Receiver -->|HTTP POST| UserWebhook
    Cleanup -->|cron @daily| D1

    click Receiver "https://github.com/ktovoz/moemail/blob/master/workers/email-receiver.ts"
    click Cleanup "https://github.com/ktovoz/moemail/blob/master/workers/cleanup.ts"
    click WebhookTest "https://github.com/ktovoz/moemail/blob/master/scripts/webhook-test-server.ts"

    %% Deployment
    GitHubActions -->|"deploy Pages & Workers"| UI
    GitHubActions -->|"run migrations"| DB

    click GitHubActions "https://github.com/ktovoz/moemail/blob/master/.github/workflows/deploy.yml"
    click GitHubActions "https://github.com/ktovoz/moemail/blob/master/wrangler.example.toml"
    click GitHubActions "https://github.com/ktovoz/moemail/blob/master/wrangler.email.example.toml"
    click GitHubActions "https://github.com/ktovoz/moemail/blob/master/wrangler.cleanup.example.toml"

    %% Styles
    classDef frontend fill:#E0F7FA,stroke:#006064,color:#006064
    classDef api fill:#E8F5E9,stroke:#1B5E20,color:#1B5E20
    classDef database fill:#FFFDE7,stroke:#F9A825,color:#F9A825
    classDef kv fill:#FFF3E0,stroke:#EF6C00,color:#EF6C00
    classDef worker fill:#F3E5F5,stroke:#6A1B9A,color:#6A1B9A
    classDef external fill:#ECEFF1,stroke:#455A64,color:#455A64
    classDef data fill:#F1F8E9,stroke:#33691E,color:#33691E
```
