RidgeChat/main.go

127 lines
3.0 KiB
Go

package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/json"
"encoding/pem"
"fmt"
"io/ioutil"
"os"
"time"
_ "embed"
"RidgedChat/ui"
)
//go:embed "default_config.json"
var defaultConfig []byte
// Config holds the client configuration
type Config struct {
ServerAddress string `json:"server_address"`
Username string `json:"username"`
OfflineMode bool `json:"offline_mode"`
HeaderVisible bool `json:"header_visible"`
SidebarVisible bool `json:"sidebar_visible"`
MainChatVisible bool `json:"mainchat_visible"`
UserTextEntryVisible bool `json:"usertextentry_visible"`
SendButtonVisible bool `json:"sendbutton_visible"`
}
type KeyManager struct {
CurrentPrivateKey *rsa.PrivateKey
NextPrivateKey *rsa.PrivateKey
CurrentPublicKey []byte
NextPublicKey []byte
}
func (km *KeyManager) GenerateKeyPair() {
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
fmt.Println("Error generating key pair:", err)
return
}
publicKeyDer, err := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)
if err != nil {
fmt.Println("Error marshaling public key:", err)
return
}
publicKeyBlock := pem.Block{
Type: "PUBLIC KEY",
Bytes: publicKeyDer,
}
publicKeyPem := pem.EncodeToMemory(&publicKeyBlock)
km.NextPrivateKey = privateKey
km.NextPublicKey = publicKeyPem
}
func (km *KeyManager) RotateKeys() {
for {
time.Sleep(5 * time.Minute)
km.CurrentPrivateKey = km.NextPrivateKey
km.CurrentPublicKey = km.NextPublicKey
km.GenerateKeyPair()
// notifyClients() // Implement this function
}
}
func ReadConfig(filePath string) (*Config, error) {
file, err := ioutil.ReadFile(filePath)
if err != nil {
return nil, err
}
var config Config
if err := json.Unmarshal(file, &config); err != nil {
return nil, err
}
return &config, nil
}
var keyManager = &KeyManager{}
func main() {
configPath := "./client_config.json"
if _, err := os.Stat(configPath); os.IsNotExist(err) {
ioutil.WriteFile(configPath, defaultConfig, 0644)
}
config, err := ReadConfig(configPath)
if err != nil {
fmt.Println("Error reading config:", err)
os.Exit(1)
}
client := NewClient(config.ServerAddress, config.Username)
if !config.OfflineMode {
if err := client.Connect(); err != nil {
fmt.Println("Error connecting to server:", err)
os.Exit(1)
}
go client.ListenForMessages()
// Initialize and start key rotation
keyManager.GenerateKeyPair()
keyManager.CurrentPrivateKey = keyManager.NextPrivateKey
keyManager.CurrentPublicKey = keyManager.NextPublicKey
keyManager.GenerateKeyPair()
go keyManager.RotateKeys()
} else {
fmt.Println("Running in offline mode. No server connection or key rotation.")
}
ui.StartGUI(ui.UIConfig{
OfflineMode: config.OfflineMode,
HeaderVisible: config.HeaderVisible,
SidebarVisible: config.SidebarVisible,
MainChatVisible: config.MainChatVisible,
UserTextEntryVisible: config.UserTextEntryVisible,
SendButtonVisible: config.SendButtonVisible,
})
}