GsDChat/README.md

246 lines
10 KiB
Markdown

# GsDChat
A lightweight, secure, and private community chat platform built in pure C# (.NET 10) without external non-.NET libraries.
GsDChat provides a single-server architecture with SQLite persistence, dynamic DLL modding via `AssemblyLoadContext`, HTTPS/WSS and tunnel-ready HTTP/WS support, authenticated file transfers, and a server-driven screen-swapping Terminal User Interface (TUI).
---
## Key Features
- **Pure .NET Architecture**: Strict adherence to the standard .NET runtime and first-party `Microsoft.Data.Sqlite`. Zero native/unmanaged C/C++ third-party dependencies.
- **Flexible Network & Tunnel Support**: Configurable direct HTTPS/WSS (with custom PFX/PEM certificates or self-signed certs) or plain HTTP/WS for running inside Docker containers behind **Cloudflare Tunnels (`cloudflared`)**, Tailscale, or reverse proxies.
- **Direct Messaging (DMs) with Configurable E2EE**:
- Private 1-on-1 direct messages between users.
- Controlled by the `AllowDmE2ee` setting in `serversettings.json`:
- When `AllowDmE2ee: true` (default), DMs use full **End-to-End Encryption** (NIST P-256 ECDH key agreement + SHA-256 + AES-256-GCM authenticated encryption). Private keys are wrapped client-side with the user's password via PBKDF2-SHA256 + AES-256-GCM, and the server only stores/relays opaque ciphertext (`E2EE:v1:...`).
- When `AllowDmE2ee: false`, the server rejects E2EE DM payloads and DMs are transmitted in standard plaintext visible to the server.
- **User-Created Group Chats**:
- Any authenticated user can create private multi-user Group Chats (separate from public channels), invite users, and leave groups.
- Maximum member count per group chat is governed by `MaxGroupChatUsers` in `serversettings.json`.
- **Screen-Swapping TUI Client**: Built with ANSI escape codes and `System.Console` (zero third-party UI dependencies). Fast screen-swapping using function keys:
- **F1**: Active Conversation Chat (supports Public Channels, Group Chats, and E2EE/Plaintext DMs with lock badges, scrollable history, timestamps, role badges, file card indicators, bottom input box).
- **F2**: Channel, Group Chat & DM Browser (browse and switch between channels, group chats, and DMs; create/invite/leave groups; start DMs).
- **F3**: User Directory (member list, role tags, real-time online `●` / offline `○` presence, E2EE `[KEY]` indicator, and quick `[D] Direct Message`).
- **F4**: Shared Files Browser (table of uploaded files, download to `./downloads/`, upload from local path).
- **F5+**: Mod-defined custom screens rendered dynamically from server layout schemas.
- **Dynamic Modding System**: Place mod `.dll` files in `./mods/` to dynamically extend the server using `AssemblyLoadContext`:
- Intercept and transform chat messages (e.g. shorthand emoji formatting `:shrug:`, word filters).
- Register custom slash commands (e.g. `/roll 2d6`, `/announce`).
- Subscribe to server lifecycle and entity events (`UserConnected`, `ChannelCreated`, `FileUploaded`).
- Inject custom TUI screens or customize server MOTD.
- **Security & Authentication**:
- PBKDF2 with SHA-512 (100,000 iterations) and 256-bit cryptographically secure salt.
- Constant-time verification preventing timing attacks.
- 256-bit secure session tokens.
- Optional server-wide password gate.
- Role-based permissions (`Owner`, `Admin`, `Member`). First registered user automatically becomes the Server Owner.
- **Direct File Transfers**: Authenticated multipart HTTPS uploads (`POST /api/files/upload`) and streaming downloads (`GET /api/files/{id}`) with SHA-256 integrity verification.
---
## Project Structure
```
GsDChat/
├── GsDChat.slnx
├── serversettings.json # Local persisted server configuration file
├── src/
│ ├── GsDChat.Core/ # Shared models, E2EE & auth crypto, and network/UI protocols
│ ├── GsDChat.Modding/ # Mod SDK: IMod, pipelines, command registry, event bus
│ ├── GsDChat.Server/ # ASP.NET Core Kestrel, SQLite DB, WebSockets, File REST
│ ├── GsDChat.Client/ # Pure C# screen-swapping TUI client
│ └── GsDChat.Mods.SampleBot/ # Reference mod: /roll, /announce, emoji transformer, F5 screen
└── tests/
└── GsDChat.Tests/ # Comprehensive xUnit test suite (Unit, Integration, E2E)
```
---
## Quick Start
### 1. Build Solution
```bash
dotnet build GsDChat.slnx
```
### 2. Run All Tests
```bash
dotnet test GsDChat.slnx
```
### 3. Run the Server
```bash
dotnet run --project src/GsDChat.Server
```
By default, the server runs on `http://0.0.0.0:5000` with SQLite database in `./data/chat.db` and loads any mod DLLs in `./mods/`.
#### Server Configuration (`serversettings.json` / CLI flags)
Server settings are managed via a local, human-readable `serversettings.json` file (automatically created and formatted if missing). You can edit `./serversettings.json` directly or pass command-line arguments:
```json
{
"Host": "0.0.0.0",
"Port": 5000,
"UseTls": false,
"CertificatePath": "",
"CertificatePassword": "",
"ServerWidePassword": "",
"RegistrationMode": "Open",
"DataDirectory": "data",
"ModsDirectory": "mods",
"MaxFileSizeMb": 50,
"ServerName": "GsDChat Community Server",
"Motd": "Welcome to GsDChat! Enjoy private and modular messaging.",
"AllowDmE2ee": true,
"MaxGroupChatUsers": 10
}
```
CLI Overrides (persisted back to `serversettings.json`):
```bash
dotnet run --project src/GsDChat.Server -- --port 8080 --allow-dm-e2ee true --max-group-users 15
```
---
## Docker & Cloudflare Tunnel Deployment
### Option A: Standard Docker Compose
1. Edit `serversettings.json` in the project root to configure your server name, MOTD, `AllowDmE2ee`, `MaxGroupChatUsers`, etc.
2. Start the container:
```bash
docker compose up -d --build
```
`./serversettings.json` is mounted directly into the container (`/app/serversettings.json`) so all configuration changes persist cleanly across restarts alongside `./data/` and `./mods/`.
### Option B: Built-in Cloudflare Tunnel (`cloudflared`)
This deploys GsDChat in an isolated container with zero open host ports, securely accessible globally via Cloudflare Tunnel.
1. Create a tunnel in **Cloudflare Zero Trust** (`Networks -> Tunnels -> Add a Tunnel`).
2. Copy the tunnel token into `.env`:
```bash
CLOUDFLARE_TUNNEL_TOKEN=eyJh...
```
3. In Cloudflare Zero Trust, configure the Public Hostname:
- **Service**: `HTTP`
- **URL**: `gsdchat:5000`
4. Start both GsDChat and the cloudflared tunnel:
```bash
docker compose -f docker-compose.tunnel.yml up -d --build
```
---
### 4. Run the Client TUI
Launch the client interactively:
```bash
dotnet run --project src/GsDChat.Client
```
When launched, GsDChat opens a user-friendly **Server Selection Menu**:
- Displays a quick-access list of your recently visited servers and remembered usernames (like Discord server list).
- Option `[N]` to connect to a new server URL or IP.
- Option `[D]` to delete an entry from history.
- Prompts for credentials (or uses saved username) and masked password.
Or connect directly via command-line arguments:
```bash
dotnet run --project src/GsDChat.Client -- --server https://chat.example.com --username Alice --password MyPassword123!
```
---
## Zero-Install WebClient (Mobile & Desktop)
GsDChat includes a responsive, zero-install WebClient built with pure HTML5, CSS3, and JavaScript (served directly from the server's `wwwroot/`):
- **Access**: Open `http://<server-ip>:5000/` or your Cloudflare Tunnel URL in any browser.
- **Mobile Optimized**: Designed specifically for phones and touchscreens with responsive navigation tabs, bottom chat bar, and native file pickers.
- **Offline / Private LAN Ready**: 100% self-contained with zero external CDN dependencies.
- **Features**: Real-time WebSocket messaging, Public Channels, Group Chats (create, invite, leave), Direct Messages with Web Crypto API (`crypto.subtle`) P-256 ECDH + AES-256-GCM E2EE (interoperable with the C# TUI client), online user presence, authenticated file uploads, and downloads.
---
## Client TUI Navigation
| Key | Action |
|---|---|
| **F1** | Switch to **Chat** view |
| **F2** | Switch to **Channels / Groups / DMs** view |
| **F3** | Switch to **Users** directory view (`D` to start DM) |
| **F4** | Switch to **Files** transfer view |
| **F5** | Switch to **Server Status** (SampleBot mod view) |
| **Enter** (on F1) | Send message or run slash command |
| **PageUp / PageDown** | Scroll message viewport up and down |
| **Ctrl + C** | Exit client |
### Built-in & Mod Slash Commands
Type these directly in the chat input on **F1**:
- `/help` — List available commands.
- `/join <name>` — Switch to a channel, group chat, or DM.
- `/create <name> [topic]` — Create a new public channel (Admin/Owner).
- `/dm <username>` — Start or open a Direct Message with a user.
- `/group <name> [user1,user2,...]` — Create a new private Group Chat.
- `/invite <username>` — Invite a user to the active Group Chat.
- `/leave` — Leave the active Group Chat.
- `/upload <local_path>` — Upload a file to the active conversation.
- `/download <file_id>` — Download a shared file to `./downloads/`.
- `/roll [NdM]` *(SampleBot)* — Roll dice (e.g. `/roll 2d6`, `/roll 1d20`).
- `/announce <text>` *(SampleBot)* — Post an official broadcast announcement (Admin/Owner).
- Text emoji shortcuts: `:shrug:` converts to `¯\_(ツ)_/¯`, `:tableflip:` converts to `(╯°□°)╯︵ ┻━┻`, `:heart:` to `❤️`.
---
## Modding Guide
To create a custom mod:
1. Create a class library targeting `net10.0`.
2. Reference `GsDChat.Modding.csproj`.
3. Implement `IMod`:
```csharp
using GsDChat.Modding;
public class MyCustomMod : IMod
{
public string Id => "com.example.mycustommod";
public string Name => "My Custom Mod";
public string Version => "1.0.0";
public string Description => "Example custom mod for GsDChat";
public Task InitializeAsync(IModContext context)
{
// Register a custom slash command
context.Commands.RegisterCommand("ping", "Responds with pong", async cmdCtx =>
{
return CommandResult.Ok("🏓 Pong from custom mod!");
});
// Intercept messages
context.Pipeline.Use(async (msgCtx, next) =>
{
// Inspect or modify msgCtx.Message.Content
await next();
});
return Task.CompletedTask;
}
public Task ShutdownAsync() => Task.CompletedTask;
}
```
4. Drop the built `.dll` into the server's `./mods/` directory and restart the server.
---
## License
MIT License.