remade into 1 project

remade into 1 project
This commit is contained in:
2026-03-14 18:33:38 -04:00
parent ee37ddf2b8
commit d3d52c3553
42 changed files with 1971 additions and 1946 deletions

184
RelayCore/.gitignore vendored
View File

@@ -1,93 +1,93 @@
############################################
# .NET Build
############################################
bin/
obj/
out/
publish/
############################################
# Visual Studio
############################################
.vs/
*.user
*.suo
*.userprefs
*.csproj.user
*.dbmdl
*.cache
*.pdb
*.opendb
############################################
# Rider / JetBrains
############################################
.idea/
*.sln.iml
############################################
# VSCode
############################################
.vscode/
############################################
# NuGet
############################################
*.nupkg
*.snupkg
packages/
.nuget/
.nuget/packages/
############################################
# Logs
############################################
*.log
logs/
############################################
# OS files
############################################
.DS_Store
Thumbs.db
############################################
# Local secrets / environment
############################################
.env
.env.*
secrets.json
appsettings.Development.json
############################################
# E2EE private keys
############################################
keys/*
!keys/.gitkeep
############################################
# Local test databases / data folders
############################################
data/
*.db
*.sqlite
*.sqlite3
############################################
# Temporary files
############################################
*.tmp
*.temp
*.bak
############################################
# .NET Build
############################################
bin/
obj/
out/
publish/
############################################
# Visual Studio
############################################
.vs/
*.user
*.suo
*.userprefs
*.csproj.user
*.dbmdl
*.cache
*.pdb
*.opendb
############################################
# Rider / JetBrains
############################################
.idea/
*.sln.iml
############################################
# VSCode
############################################
.vscode/
############################################
# NuGet
############################################
*.nupkg
*.snupkg
packages/
.nuget/
.nuget/packages/
############################################
# Logs
############################################
*.log
logs/
############################################
# OS files
############################################
.DS_Store
Thumbs.db
############################################
# Local secrets / environment
############################################
.env
.env.*
secrets.json
appsettings.Development.json
############################################
# E2EE private keys
############################################
keys/*
!keys/.gitkeep
############################################
# Local test databases / data folders
############################################
data/
*.db
*.sqlite
*.sqlite3
############################################
# Temporary files
############################################
*.tmp
*.temp
*.bak
*.swp

View File

@@ -1,82 +1,82 @@
using System.Security.Cryptography;
using System.Text;
namespace RelayCore;
public static class E2EeHelper
{
public static (string publicKey, string privateKey) GenerateRsaKeyPair()
{
using var rsa = RSA.Create(2048);
var publicKey = Convert.ToBase64String(rsa.ExportSubjectPublicKeyInfo());
var privateKey = Convert.ToBase64String(rsa.ExportPkcs8PrivateKey());
return (publicKey, privateKey);
}
public static EncryptedMessagePayload EncryptForRecipient(string plainText, string recipientPublicKeyBase64)
{
var aesKey = RandomNumberGenerator.GetBytes(32);
var nonce = RandomNumberGenerator.GetBytes(12);
var plainBytes = Encoding.UTF8.GetBytes(plainText);
var cipherBytes = new byte[plainBytes.Length];
var tag = new byte[16];
using (var aes = new AesGcm(aesKey, 16))
{
aes.Encrypt(nonce, plainBytes, cipherBytes, tag);
}
var recipientPublicKey = Convert.FromBase64String(recipientPublicKeyBase64);
byte[] encryptedKey;
using (var rsa = RSA.Create())
{
rsa.ImportSubjectPublicKeyInfo(recipientPublicKey, out _);
encryptedKey = rsa.Encrypt(aesKey, RSAEncryptionPadding.OaepSHA256);
}
return new EncryptedMessagePayload
{
CipherText = Convert.ToBase64String(cipherBytes),
Nonce = Convert.ToBase64String(nonce),
Tag = Convert.ToBase64String(tag),
EncryptedKey = Convert.ToBase64String(encryptedKey)
};
}
public static string DecryptForRecipient(EncryptedMessagePayload payload, string recipientPrivateKeyBase64)
{
var encryptedKey = Convert.FromBase64String(payload.EncryptedKey);
var privateKey = Convert.FromBase64String(recipientPrivateKeyBase64);
byte[] aesKey;
using (var rsa = RSA.Create())
{
rsa.ImportPkcs8PrivateKey(privateKey, out _);
aesKey = rsa.Decrypt(encryptedKey, RSAEncryptionPadding.OaepSHA256);
}
var nonce = Convert.FromBase64String(payload.Nonce);
var tag = Convert.FromBase64String(payload.Tag);
var cipherBytes = Convert.FromBase64String(payload.CipherText);
var plainBytes = new byte[cipherBytes.Length];
using (var aes = new AesGcm(aesKey, 16))
{
aes.Decrypt(nonce, cipherBytes, tag, plainBytes);
}
return Encoding.UTF8.GetString(plainBytes);
}
}
public class EncryptedMessagePayload
{
public required string CipherText { get; set; }
public required string Nonce { get; set; }
public required string Tag { get; set; }
public required string EncryptedKey { get; set; }
using System.Security.Cryptography;
using System.Text;
namespace RelayCore;
public static class E2EeHelper
{
public static (string publicKey, string privateKey) GenerateRsaKeyPair()
{
using var rsa = RSA.Create(2048);
var publicKey = Convert.ToBase64String(rsa.ExportSubjectPublicKeyInfo());
var privateKey = Convert.ToBase64String(rsa.ExportPkcs8PrivateKey());
return (publicKey, privateKey);
}
public static EncryptedMessagePayload EncryptForRecipient(string plainText, string recipientPublicKeyBase64)
{
var aesKey = RandomNumberGenerator.GetBytes(32);
var nonce = RandomNumberGenerator.GetBytes(12);
var plainBytes = Encoding.UTF8.GetBytes(plainText);
var cipherBytes = new byte[plainBytes.Length];
var tag = new byte[16];
using (var aes = new AesGcm(aesKey, 16))
{
aes.Encrypt(nonce, plainBytes, cipherBytes, tag);
}
var recipientPublicKey = Convert.FromBase64String(recipientPublicKeyBase64);
byte[] encryptedKey;
using (var rsa = RSA.Create())
{
rsa.ImportSubjectPublicKeyInfo(recipientPublicKey, out _);
encryptedKey = rsa.Encrypt(aesKey, RSAEncryptionPadding.OaepSHA256);
}
return new EncryptedMessagePayload
{
CipherText = Convert.ToBase64String(cipherBytes),
Nonce = Convert.ToBase64String(nonce),
Tag = Convert.ToBase64String(tag),
EncryptedKey = Convert.ToBase64String(encryptedKey)
};
}
public static string DecryptForRecipient(EncryptedMessagePayload payload, string recipientPrivateKeyBase64)
{
var encryptedKey = Convert.FromBase64String(payload.EncryptedKey);
var privateKey = Convert.FromBase64String(recipientPrivateKeyBase64);
byte[] aesKey;
using (var rsa = RSA.Create())
{
rsa.ImportPkcs8PrivateKey(privateKey, out _);
aesKey = rsa.Decrypt(encryptedKey, RSAEncryptionPadding.OaepSHA256);
}
var nonce = Convert.FromBase64String(payload.Nonce);
var tag = Convert.FromBase64String(payload.Tag);
var cipherBytes = Convert.FromBase64String(payload.CipherText);
var plainBytes = new byte[cipherBytes.Length];
using (var aes = new AesGcm(aesKey, 16))
{
aes.Decrypt(nonce, cipherBytes, tag, plainBytes);
}
return Encoding.UTF8.GetString(plainBytes);
}
}
public class EncryptedMessagePayload
{
public required string CipherText { get; set; }
public required string Nonce { get; set; }
public required string Tag { get; set; }
public required string EncryptedKey { get; set; }
}

View File

@@ -1,109 +1,109 @@
using System;
using System.Security.Cryptography;
using System.Text;
using Konscious.Security.Cryptography;
namespace PasswordHasher
{
/// <summary>
/// Provides secure password hashing functionality using Argon2id algorithm
/// </summary>
public class PasswordHasher
{
/// <summary>
/// Size of the salt in bytes
/// </summary>
private const int SaltSize = 16;
/// <summary>
/// Size of the hash in bytes
/// </summary>
private const int HashSize = 32;
/// <summary>
/// Number of threads to use for parallel computation
/// </summary>
private const int DegreeOfParallelism = 1;
/// <summary>
/// Number of iterations for the Argon2id algorithm
/// </summary>
private const int Iterations = 2;
/// <summary>
/// Memory size in KB to use
/// </summary>
private const int MemorySize = 19456; // 19 MB
/// <summary>
/// Generates a secure hash of a password using Argon2id with a random salt
/// </summary>
/// <param name="password">The plain text password to hash</param>
/// <returns>A Base64 string containing the combined salt and hash</returns>
/// <exception cref="ArgumentNullException">Thrown when password is null</exception>
public string HashPassword(string password)
{
// Generate a random salt
byte[] salt = new byte[SaltSize];
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
{
rng.GetBytes(salt);
}
// Create hash
byte[] hash = HashPassword(password, salt);
// Combine salt and hash
var combinedBytes = new byte[salt.Length + hash.Length];
Array.Copy(salt, 0, combinedBytes, 0, salt.Length);
Array.Copy(hash, 0, combinedBytes, salt.Length, hash.Length);
// Convert to base64 for storage
return Convert.ToBase64String(combinedBytes);
}
/// <summary>
/// Generates a password hash using Argon2id with a specific salt
/// </summary>
/// <param name="password">The plain text password</param>
/// <param name="salt">The salt to use for hashing</param>
/// <returns>A byte array containing the password hash</returns>
private byte[] HashPassword(string password, byte[] salt)
{
var argon2 = new Argon2id(Encoding.UTF8.GetBytes(password))
{
Salt = salt,
DegreeOfParallelism = DegreeOfParallelism,
Iterations = Iterations,
MemorySize = MemorySize
};
return argon2.GetBytes(HashSize);
}
/// <summary>
/// Verifies if a password matches a stored hash
/// </summary>
/// <param name="password">The plain text password to verify</param>
/// <param name="hashedPassword">The stored hash in Base64 format</param>
/// <returns>True if the password matches the hash, false otherwise</returns>
/// <exception cref="ArgumentNullException">Thrown when password or hashedPassword are null</exception>
/// <exception cref="FormatException">Thrown when hashedPassword is not in valid Base64 format</exception>
public bool VerifyPassword(string password, string hashedPassword)
{
// Decode the stored hash
byte[] combinedBytes = Convert.FromBase64String(hashedPassword);
// Extract salt and hash
byte[] salt = new byte[SaltSize];
byte[] hash = new byte[HashSize];
Array.Copy(combinedBytes, 0, salt, 0, SaltSize);
Array.Copy(combinedBytes, SaltSize, hash, 0, HashSize);
// Compute hash for the input password
byte[] newHash = HashPassword(password, salt);
// Compare the hashes
return CryptographicOperations.FixedTimeEquals(hash, newHash);
}
}
using System;
using System.Security.Cryptography;
using System.Text;
using Konscious.Security.Cryptography;
namespace PasswordHasher
{
/// <summary>
/// Provides secure password hashing functionality using Argon2id algorithm
/// </summary>
public class PasswordHasher
{
/// <summary>
/// Size of the salt in bytes
/// </summary>
private const int SaltSize = 16;
/// <summary>
/// Size of the hash in bytes
/// </summary>
private const int HashSize = 32;
/// <summary>
/// Number of threads to use for parallel computation
/// </summary>
private const int DegreeOfParallelism = 1;
/// <summary>
/// Number of iterations for the Argon2id algorithm
/// </summary>
private const int Iterations = 2;
/// <summary>
/// Memory size in KB to use
/// </summary>
private const int MemorySize = 19456; // 19 MB
/// <summary>
/// Generates a secure hash of a password using Argon2id with a random salt
/// </summary>
/// <param name="password">The plain text password to hash</param>
/// <returns>A Base64 string containing the combined salt and hash</returns>
/// <exception cref="ArgumentNullException">Thrown when password is null</exception>
public string HashPassword(string password)
{
// Generate a random salt
byte[] salt = new byte[SaltSize];
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
{
rng.GetBytes(salt);
}
// Create hash
byte[] hash = HashPassword(password, salt);
// Combine salt and hash
var combinedBytes = new byte[salt.Length + hash.Length];
Array.Copy(salt, 0, combinedBytes, 0, salt.Length);
Array.Copy(hash, 0, combinedBytes, salt.Length, hash.Length);
// Convert to base64 for storage
return Convert.ToBase64String(combinedBytes);
}
/// <summary>
/// Generates a password hash using Argon2id with a specific salt
/// </summary>
/// <param name="password">The plain text password</param>
/// <param name="salt">The salt to use for hashing</param>
/// <returns>A byte array containing the password hash</returns>
private byte[] HashPassword(string password, byte[] salt)
{
var argon2 = new Argon2id(Encoding.UTF8.GetBytes(password))
{
Salt = salt,
DegreeOfParallelism = DegreeOfParallelism,
Iterations = Iterations,
MemorySize = MemorySize
};
return argon2.GetBytes(HashSize);
}
/// <summary>
/// Verifies if a password matches a stored hash
/// </summary>
/// <param name="password">The plain text password to verify</param>
/// <param name="hashedPassword">The stored hash in Base64 format</param>
/// <returns>True if the password matches the hash, false otherwise</returns>
/// <exception cref="ArgumentNullException">Thrown when password or hashedPassword are null</exception>
/// <exception cref="FormatException">Thrown when hashedPassword is not in valid Base64 format</exception>
public bool VerifyPassword(string password, string hashedPassword)
{
// Decode the stored hash
byte[] combinedBytes = Convert.FromBase64String(hashedPassword);
// Extract salt and hash
byte[] salt = new byte[SaltSize];
byte[] hash = new byte[HashSize];
Array.Copy(combinedBytes, 0, salt, 0, SaltSize);
Array.Copy(combinedBytes, SaltSize, hash, 0, HashSize);
// Compute hash for the input password
byte[] newHash = HashPassword(password, salt);
// Compare the hashes
return CryptographicOperations.FixedTimeEquals(hash, newHash);
}
}
}

View File

@@ -1,298 +1,298 @@
using SurrealDb.Net;
using SurrealDb.Net.Models;
using SurrealDb.Net.Models.Auth;
using System.Text.Json;
using PasswordHasher;
using RelayCore;
using var db = new SurrealDbClient("ws://127.0.0.1:8000/rpc");
await db.SignIn(new RootAuth { Username = "root", Password = "secret" });
await db.Use("test", "test");
var keeper = await CreateUserAsync(db, "Keeper317", "Keeper317@gmail.com", "password");
var kira = await CreateUserAsync(db, "Ru_Kira", "jduesling13@gmail.com", "password");
Console.WriteLine($"Keeper created: {ToJsonString(keeper)}");
Console.WriteLine($"Kira created: {ToJsonString(kira)}");
var keeperKeys = E2EeHelper.GenerateRsaKeyPair();
var kiraKeys = E2EeHelper.GenerateRsaKeyPair();
KeyStorage.SavePrivateKey("Keeper317", keeperKeys.privateKey);
KeyStorage.SavePrivateKey("Ru_Kira", kiraKeys.privateKey);
await db.Create("user_keys", new UserKeys
{
UserId = keeper.Id.ToString(),
PublicKey = keeperKeys.publicKey,
CreatedAt = DateTime.UtcNow,
UpdatedAt = DateTime.UtcNow
});
await db.Create("user_keys", new UserKeys
{
UserId = kira.Id.ToString(),
PublicKey = kiraKeys.publicKey,
CreatedAt = DateTime.UtcNow,
UpdatedAt = DateTime.UtcNow
});
Console.WriteLine("Public keys stored for both users.");
var conversation = await db.Create("conversations", new Conversations
{
CreatedByUserId = keeper.Id.ToString(),
CreatedAt = DateTime.UtcNow,
UpdatedAt = DateTime.UtcNow,
Title = "Keeper317 + Ru_Kira",
IsDirectMessage = true
});
Console.WriteLine($"Conversation created: {ToJsonString(conversation)}");
await db.Create("conversation_members", new ConversationMembers
{
ConversationId = conversation.Id.ToString(),
UserId = keeper.Id.ToString(),
JoinedAt = DateTime.UtcNow
});
await db.Create("conversation_members", new ConversationMembers
{
ConversationId = conversation.Id.ToString(),
UserId = kira.Id.ToString(),
JoinedAt = DateTime.UtcNow
});
Console.WriteLine("Conversation members added.");
var encrypted = E2EeHelper.EncryptForRecipient("hello from Keeper317", kiraKeys.publicKey);
var savedMessage = await db.Create("messages", new Messages
{
ConversationId = conversation.Id.ToString(),
SenderUserId = keeper.Id.ToString(),
RecipientUserId = kira.Id.ToString(),
CipherText = encrypted.CipherText,
Nonce = encrypted.Nonce,
Tag = encrypted.Tag,
EncryptedKey = encrypted.EncryptedKey,
CreatedAt = DateTime.UtcNow
});
Console.WriteLine($"Encrypted message saved: {ToJsonString(savedMessage)}");
var decrypted = E2EeHelper.DecryptForRecipient(encrypted, kiraKeys.privateKey);
Console.WriteLine($"Decrypted for Ru_Kira: {decrypted}");
return;
static string ToJsonString(object? o)
{
return JsonSerializer.Serialize(o, new JsonSerializerOptions { WriteIndented = true });
}
static async Task<Users> CreateUserAsync(SurrealDbClient db, string username, string email, string rawPassword)
{
var now = DateTime.UtcNow;
var user = new Users
{
Username = username,
Email = email,
CreatedAt = now,
UpdatedAt = now,
LastLogin = now,
TwoFactorEnabled = false,
EmailVerified = false,
AccountStatus = (int)AccountStatuses.Active,
OnlineStatus = (int)OnlineStatuses.Online,
};
var created = await db.Create("users", user);
var hasher = new PasswordHasher.PasswordHasher();
var passwordHash = hasher.HashPassword(created.Id.ToString() + rawPassword);
var updated = await db.Merge<PasswordHash, Users>(new PasswordHash
{
Id = created.Id,
Password = passwordHash
});
return updated;
}
public static class KeyStorage
{
public static void SavePrivateKey(string username, string privateKey)
{
Directory.CreateDirectory("keys");
File.WriteAllText(Path.Combine("keys", $"{username}.private.key"), privateKey);
}
public static string LoadPrivateKey(string username)
{
return File.ReadAllText(Path.Combine("keys", $"{username}.private.key"));
}
public static bool PrivateKeyExists(string username)
{
return File.Exists(Path.Combine("keys", $"{username}.private.key"));
}
}
public class ResponsibilityMerge : Record
{
public bool Marketing { get; set; }
}
public class Group
{
public bool Marketing { get; set; }
public int Count { get; set; }
}
public class Users : Record
{
public required string Username { get; set; }
public string? Password { get; set; }
public required string Email { get; set; }
public required DateTime CreatedAt { get; set; }
public required DateTime UpdatedAt { get; set; }
public required DateTime LastLogin { get; set; }
public bool TwoFactorEnabled { get; set; }
public bool EmailVerified { get; set; }
public required int AccountStatus { get; set; }
public required int OnlineStatus { get; set; }
}
public class PasswordHash : Record
{
public string? Password { get; set; }
}
public class Sessions : Record
{
public required string UserId { get; set; }
public required string TokenHash { get; set; }
public required DateTime IssuedAt { get; set; }
public required DateTime ExpiresAt { get; set; }
public DateTime? LastUsedAt { get; set; }
public bool Revoked { get; set; }
public required string DeviceName { get; set; }
public required string IpAddress { get; set; }
public required string UserAgent { get; set; }
}
public class PasswordReset : Record
{
public required string UserId { get; set; }
public required string TokenHash { get; set; }
public required DateTime CreatedAt { get; set; }
public required DateTime ExpiresAt { get; set; }
public bool Revoked { get; set; }
}
public class Licenses : Record
{
public required string UserId { get; set; }
public required int LicenseType { get; set; }
public required int Status { get; set; }
public required DateTime CreatedAt { get; set; }
public required DateTime StartsAt { get; set; }
public required DateTime UpdatedAt { get; set; }
public required DateTime ExpiresAt { get; set; }
}
public class AuthAudits : Record
{
public required string UserId { get; set; }
public required int EventType { get; set; }
public bool Success { get; set; }
public required string IpAddress { get; set; }
public required string UserAgent { get; set; }
public required string Details { get; set; }
public required DateTime CreatedAt { get; set; }
}
public class UserKeys : Record
{
public required string UserId { get; set; }
public required string PublicKey { get; set; }
public required DateTime CreatedAt { get; set; }
public required DateTime UpdatedAt { get; set; }
}
public class Conversations : Record
{
public required string CreatedByUserId { get; set; }
public required DateTime CreatedAt { get; set; }
public required DateTime UpdatedAt { get; set; }
public string? Title { get; set; }
public bool IsDirectMessage { get; set; }
}
public class ConversationMembers : Record
{
public required string ConversationId { get; set; }
public required string UserId { get; set; }
public required DateTime JoinedAt { get; set; }
}
public class Messages : Record
{
public required string ConversationId { get; set; }
public required string SenderUserId { get; set; }
public required string RecipientUserId { get; set; }
public required string CipherText { get; set; }
public required string Nonce { get; set; }
public required string Tag { get; set; }
public required string EncryptedKey { get; set; }
public required DateTime CreatedAt { get; set; }
}
enum AccountStatuses
{
Active,
Suspended,
Banned,
Deleted
}
enum OnlineStatuses
{
Online,
Busy,
DND,
Invisible,
Offline
}
enum LicenseStatuses
{
Active,
Expired,
Renewable,
Revoked
}
enum LicenseType
{
Free,
Basic,
Advanced,
Pro,
Enterprise
}
enum LogEvents
{
LoginSuccess,
LoginFailure,
LogoutSuccess,
LogoutFailure,
PasswordResetSuccess,
PasswordResetFailure,
using SurrealDb.Net;
using SurrealDb.Net.Models;
using SurrealDb.Net.Models.Auth;
using System.Text.Json;
using PasswordHasher;
using RelayCore;
using var db = new SurrealDbClient("ws://127.0.0.1:8000/rpc");
await db.SignIn(new RootAuth { Username = "root", Password = "secret" });
await db.Use("test", "test");
var keeper = await CreateUserAsync(db, "Keeper317", "Keeper317@gmail.com", "password");
var kira = await CreateUserAsync(db, "Ru_Kira", "jduesling13@gmail.com", "password");
Console.WriteLine($"Keeper created: {ToJsonString(keeper)}");
Console.WriteLine($"Kira created: {ToJsonString(kira)}");
var keeperKeys = E2EeHelper.GenerateRsaKeyPair();
var kiraKeys = E2EeHelper.GenerateRsaKeyPair();
KeyStorage.SavePrivateKey("Keeper317", keeperKeys.privateKey);
KeyStorage.SavePrivateKey("Ru_Kira", kiraKeys.privateKey);
await db.Create("user_keys", new UserKeys
{
UserId = keeper.Id.ToString(),
PublicKey = keeperKeys.publicKey,
CreatedAt = DateTime.UtcNow,
UpdatedAt = DateTime.UtcNow
});
await db.Create("user_keys", new UserKeys
{
UserId = kira.Id.ToString(),
PublicKey = kiraKeys.publicKey,
CreatedAt = DateTime.UtcNow,
UpdatedAt = DateTime.UtcNow
});
Console.WriteLine("Public keys stored for both users.");
var conversation = await db.Create("conversations", new Conversations
{
CreatedByUserId = keeper.Id.ToString(),
CreatedAt = DateTime.UtcNow,
UpdatedAt = DateTime.UtcNow,
Title = "Keeper317 + Ru_Kira",
IsDirectMessage = true
});
Console.WriteLine($"Conversation created: {ToJsonString(conversation)}");
await db.Create("conversation_members", new ConversationMembers
{
ConversationId = conversation.Id.ToString(),
UserId = keeper.Id.ToString(),
JoinedAt = DateTime.UtcNow
});
await db.Create("conversation_members", new ConversationMembers
{
ConversationId = conversation.Id.ToString(),
UserId = kira.Id.ToString(),
JoinedAt = DateTime.UtcNow
});
Console.WriteLine("Conversation members added.");
var encrypted = E2EeHelper.EncryptForRecipient("hello from Keeper317", kiraKeys.publicKey);
var savedMessage = await db.Create("messages", new Messages
{
ConversationId = conversation.Id.ToString(),
SenderUserId = keeper.Id.ToString(),
RecipientUserId = kira.Id.ToString(),
CipherText = encrypted.CipherText,
Nonce = encrypted.Nonce,
Tag = encrypted.Tag,
EncryptedKey = encrypted.EncryptedKey,
CreatedAt = DateTime.UtcNow
});
Console.WriteLine($"Encrypted message saved: {ToJsonString(savedMessage)}");
var decrypted = E2EeHelper.DecryptForRecipient(encrypted, kiraKeys.privateKey);
Console.WriteLine($"Decrypted for Ru_Kira: {decrypted}");
return;
static string ToJsonString(object? o)
{
return JsonSerializer.Serialize(o, new JsonSerializerOptions { WriteIndented = true });
}
static async Task<Users> CreateUserAsync(SurrealDbClient db, string username, string email, string rawPassword)
{
var now = DateTime.UtcNow;
var user = new Users
{
Username = username,
Email = email,
CreatedAt = now,
UpdatedAt = now,
LastLogin = now,
TwoFactorEnabled = false,
EmailVerified = false,
AccountStatus = (int)AccountStatuses.Active,
OnlineStatus = (int)OnlineStatuses.Online,
};
var created = await db.Create("users", user);
var hasher = new PasswordHasher.PasswordHasher();
var passwordHash = hasher.HashPassword(created.Id.ToString() + rawPassword);
var updated = await db.Merge<PasswordHash, Users>(new PasswordHash
{
Id = created.Id,
Password = passwordHash
});
return updated;
}
public static class KeyStorage
{
public static void SavePrivateKey(string username, string privateKey)
{
Directory.CreateDirectory("keys");
File.WriteAllText(Path.Combine("keys", $"{username}.private.key"), privateKey);
}
public static string LoadPrivateKey(string username)
{
return File.ReadAllText(Path.Combine("keys", $"{username}.private.key"));
}
public static bool PrivateKeyExists(string username)
{
return File.Exists(Path.Combine("keys", $"{username}.private.key"));
}
}
public class ResponsibilityMerge : Record
{
public bool Marketing { get; set; }
}
public class Group
{
public bool Marketing { get; set; }
public int Count { get; set; }
}
public class Users : Record
{
public required string Username { get; set; }
public string? Password { get; set; }
public required string Email { get; set; }
public required DateTime CreatedAt { get; set; }
public required DateTime UpdatedAt { get; set; }
public required DateTime LastLogin { get; set; }
public bool TwoFactorEnabled { get; set; }
public bool EmailVerified { get; set; }
public required int AccountStatus { get; set; }
public required int OnlineStatus { get; set; }
}
public class PasswordHash : Record
{
public string? Password { get; set; }
}
public class Sessions : Record
{
public required string UserId { get; set; }
public required string TokenHash { get; set; }
public required DateTime IssuedAt { get; set; }
public required DateTime ExpiresAt { get; set; }
public DateTime? LastUsedAt { get; set; }
public bool Revoked { get; set; }
public required string DeviceName { get; set; }
public required string IpAddress { get; set; }
public required string UserAgent { get; set; }
}
public class PasswordReset : Record
{
public required string UserId { get; set; }
public required string TokenHash { get; set; }
public required DateTime CreatedAt { get; set; }
public required DateTime ExpiresAt { get; set; }
public bool Revoked { get; set; }
}
public class Licenses : Record
{
public required string UserId { get; set; }
public required int LicenseType { get; set; }
public required int Status { get; set; }
public required DateTime CreatedAt { get; set; }
public required DateTime StartsAt { get; set; }
public required DateTime UpdatedAt { get; set; }
public required DateTime ExpiresAt { get; set; }
}
public class AuthAudits : Record
{
public required string UserId { get; set; }
public required int EventType { get; set; }
public bool Success { get; set; }
public required string IpAddress { get; set; }
public required string UserAgent { get; set; }
public required string Details { get; set; }
public required DateTime CreatedAt { get; set; }
}
public class UserKeys : Record
{
public required string UserId { get; set; }
public required string PublicKey { get; set; }
public required DateTime CreatedAt { get; set; }
public required DateTime UpdatedAt { get; set; }
}
public class Conversations : Record
{
public required string CreatedByUserId { get; set; }
public required DateTime CreatedAt { get; set; }
public required DateTime UpdatedAt { get; set; }
public string? Title { get; set; }
public bool IsDirectMessage { get; set; }
}
public class ConversationMembers : Record
{
public required string ConversationId { get; set; }
public required string UserId { get; set; }
public required DateTime JoinedAt { get; set; }
}
public class Messages : Record
{
public required string ConversationId { get; set; }
public required string SenderUserId { get; set; }
public required string RecipientUserId { get; set; }
public required string CipherText { get; set; }
public required string Nonce { get; set; }
public required string Tag { get; set; }
public required string EncryptedKey { get; set; }
public required DateTime CreatedAt { get; set; }
}
enum AccountStatuses
{
Active,
Suspended,
Banned,
Deleted
}
enum OnlineStatuses
{
Online,
Busy,
DND,
Invisible,
Offline
}
enum LicenseStatuses
{
Active,
Expired,
Renewable,
Revoked
}
enum LicenseType
{
Free,
Basic,
Advanced,
Pro,
Enterprise
}
enum LogEvents
{
LoginSuccess,
LoginFailure,
LogoutSuccess,
LogoutFailure,
PasswordResetSuccess,
PasswordResetFailure,
}

View File

@@ -1,16 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Konscious.Security.Cryptography.Argon2" Version="1.3.1" />
<PackageReference Include="SurrealDb.Net" Version="0.9.0" />
</ItemGroup>
</Project>
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Konscious.Security.Cryptography.Argon2" Version="1.3.1" />
<PackageReference Include="SurrealDb.Net" Version="0.9.0" />
</ItemGroup>
</Project>