Compare commits
15 Commits
687387b105
...
CoreAuth
| Author | SHA1 | Date | |
|---|---|---|---|
| 3460ce6b04 | |||
| ec6a8c446a | |||
| 33eee17c43 | |||
| dd1aa45f6e | |||
| 38662f6655 | |||
| 777328caed | |||
| 87ade75f1d | |||
| 798652cb4d | |||
| 6a650a282b | |||
| 5b10afcec2 | |||
| 1220654656 | |||
| be797c55c2 | |||
| 20e99fefec | |||
| f77a5eb823 | |||
| d6ecb63b5f |
@@ -1,24 +1,23 @@
|
||||
using RelayClient.Crypto;
|
||||
using WebSocketSharp;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Text.Json.Serialization;
|
||||
using RelayClient.Crypto;
|
||||
using RelayClient.Services;
|
||||
using RelayShared.Rtc;
|
||||
using RelayShared.Services;
|
||||
|
||||
namespace RelayClient;
|
||||
|
||||
|
||||
public partial class MainPage : ContentPage
|
||||
{
|
||||
private readonly string _username;
|
||||
private readonly WebSocket _wsc;
|
||||
private string? _serverPublicKey;
|
||||
private readonly RelaySocketClient _socket;
|
||||
private readonly RtcBridgeService _rtc;
|
||||
|
||||
private string? _currentChannelId;
|
||||
private string? _currentChannelName;
|
||||
|
||||
private readonly Dictionary<string, List<ChatMessage>> _messagesByChannel = new();
|
||||
private readonly List<ChannelItem> _channels = [];
|
||||
|
||||
|
||||
public MainPage(string username)
|
||||
{
|
||||
InitializeComponent();
|
||||
@@ -33,19 +32,31 @@ public partial class MainPage : ContentPage
|
||||
KeyStorage.SavePublicKey(_username, keys.publicKey);
|
||||
}
|
||||
|
||||
_wsc = new WebSocket("ws://localhost:1337/");
|
||||
|
||||
_wsc.OnMessage += WscOnMessage;
|
||||
_wsc.Connect();
|
||||
|
||||
var publicKey = KeyStorage.LoadPublicKey(_username);
|
||||
_wsc.Send($"REGISTER_KEY|{_username}|{publicKey}");
|
||||
_wsc.Send("GET_SERVER_KEY");
|
||||
_wsc.Send("GET_CHANNELS");
|
||||
|
||||
hybridWebView.SetInvokeJavaScriptTarget(this);
|
||||
ServerAPI.setupClient();
|
||||
|
||||
_socket = new RelaySocketClient(_username);
|
||||
_rtc = new RtcBridgeService(
|
||||
_username,
|
||||
_socket,
|
||||
hybridWebView,
|
||||
() => _currentChannelId,
|
||||
SafeSendRawToWebView
|
||||
);
|
||||
|
||||
hybridWebView.SetInvokeJavaScriptTarget(_rtc);
|
||||
|
||||
_socket.Log += Console.WriteLine;
|
||||
_socket.ChannelListReceived += HandleChannelList;
|
||||
_socket.EncryptedChatReceived += HandleEncryptedChat;
|
||||
_socket.EncryptedRtcSignalReceived += payload =>
|
||||
{
|
||||
MainThread.BeginInvokeOnMainThread(async () =>
|
||||
{
|
||||
await _rtc.HandleIncomingRtcSignalAsync(payload);
|
||||
});
|
||||
};
|
||||
|
||||
_socket.Connect();
|
||||
}
|
||||
|
||||
private void SendButton_OnClicked(object? sender, EventArgs e)
|
||||
@@ -65,19 +76,19 @@ public partial class MainPage : ContentPage
|
||||
if (string.IsNullOrWhiteSpace(text))
|
||||
return;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(_serverPublicKey))
|
||||
if (string.IsNullOrWhiteSpace(_socket.ServerPublicKey))
|
||||
{
|
||||
Console.WriteLine("Server public key not loaded yet.");
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
if (string.IsNullOrWhiteSpace(_currentChannelId))
|
||||
{
|
||||
Console.WriteLine("No channel selected yet.");
|
||||
return;
|
||||
}
|
||||
|
||||
var encrypted = E2EeHelper.EncryptForRecipient(text, _serverPublicKey);
|
||||
var encrypted = E2EeHelper.EncryptForRecipient(text, _socket.ServerPublicKey);
|
||||
|
||||
var payload = new SocketEncryptedMessage
|
||||
{
|
||||
@@ -90,8 +101,7 @@ public partial class MainPage : ContentPage
|
||||
EncryptedKey = encrypted.EncryptedKey
|
||||
};
|
||||
|
||||
var json = JsonSerializer.Serialize(payload);
|
||||
_wsc.Send(json);
|
||||
_socket.SendJson(payload);
|
||||
|
||||
Console.WriteLine($"[{_username}] sent encrypted message.");
|
||||
|
||||
@@ -99,248 +109,83 @@ public partial class MainPage : ContentPage
|
||||
MessageEntry.Focus();
|
||||
}
|
||||
|
||||
private void WscOnMessage(object? sender, MessageEventArgs e)
|
||||
private void HandleChannelList(SocketChannelList channelList)
|
||||
{
|
||||
if (e.Data.StartsWith("SERVER:REGISTERED_KEY:"))
|
||||
_channels.Clear();
|
||||
_channels.AddRange(channelList.Channels.OrderBy(c => c.CreatedAt));
|
||||
|
||||
var defaultChannel = _channels
|
||||
.Where(c => c.Name.Equals("welcome", StringComparison.OrdinalIgnoreCase))
|
||||
.OrderBy(c => c.CreatedAt)
|
||||
.FirstOrDefault()
|
||||
?? _channels.OrderBy(c => c.CreatedAt).FirstOrDefault();
|
||||
|
||||
if (defaultChannel is null) return;
|
||||
|
||||
_currentChannelId = defaultChannel.ChannelId;
|
||||
_currentChannelName = defaultChannel.Name;
|
||||
|
||||
MainThread.BeginInvokeOnMainThread(async () =>
|
||||
{
|
||||
Console.WriteLine(e.Data);
|
||||
ChannelLabel.Text = $"#{_currentChannelName}";
|
||||
RenderChannelList();
|
||||
await _rtc.PushRtcContextToJsAsync();
|
||||
});
|
||||
|
||||
_socket.SendRaw($"GET_HISTORY|{_username}|{_currentChannelId}");
|
||||
}
|
||||
|
||||
private void HandleEncryptedChat(SocketEncryptedMessage payload) {
|
||||
if (payload.RecipientUsername != _username)
|
||||
return;
|
||||
}
|
||||
|
||||
// SafeSendRawToWebView($"[{_username}] RAW WS DATA: {e.Data}");
|
||||
|
||||
Console.WriteLine($"[{_username}] RAW WS DATA: {e.Data}");
|
||||
|
||||
string decryptedText;
|
||||
|
||||
try
|
||||
{
|
||||
using var doc = JsonDocument.Parse(e.Data);
|
||||
var root = doc.RootElement;
|
||||
var privateKey = KeyStorage.LoadPrivateKey(_username);
|
||||
|
||||
if (!root.TryGetProperty("Type", out var typeElement))
|
||||
return;
|
||||
|
||||
var type = (SignalType) typeElement.GetInt32();
|
||||
|
||||
if (type == SignalType.ChannelList)
|
||||
{
|
||||
var channelList = JsonSerializer.Deserialize<SocketChannelList>(e.Data);
|
||||
if (channelList is null)
|
||||
return;
|
||||
|
||||
_channels.Clear();
|
||||
_channels.AddRange(channelList.Channels.OrderBy(c => c.CreatedAt));
|
||||
|
||||
var defaultChannel = _channels
|
||||
.Where(c => c.Name.Equals("welcome", StringComparison.OrdinalIgnoreCase))
|
||||
.OrderBy(c => c.CreatedAt)
|
||||
.FirstOrDefault()
|
||||
?? _channels.OrderBy(c => c.CreatedAt).FirstOrDefault();
|
||||
|
||||
if (defaultChannel is not null)
|
||||
{
|
||||
_currentChannelId = defaultChannel.ChannelId;
|
||||
_currentChannelName = defaultChannel.Name;
|
||||
|
||||
MainThread.BeginInvokeOnMainThread(async () =>
|
||||
{
|
||||
ChannelLabel.Text = $"#{_currentChannelName}";
|
||||
RenderChannelList();
|
||||
await PushRtcContextToJsAsync();
|
||||
});
|
||||
|
||||
_wsc.Send($"GET_HISTORY|{_username}|{_currentChannelId}");
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (type == SignalType.ServerPublicKey)
|
||||
{
|
||||
var serverKeyMessage = JsonSerializer.Deserialize<ServerPublicKeyMessage>(e.Data);
|
||||
if (serverKeyMessage is not null)
|
||||
{
|
||||
_serverPublicKey = serverKeyMessage.PublicKey;
|
||||
Console.WriteLine($"[{_username}] loaded server public key.");
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (type == SignalType.EncryptedSignal)
|
||||
{
|
||||
var payload = JsonSerializer.Deserialize<SocketRtcSignalMessage>(e.Data);
|
||||
if (payload is null)
|
||||
return;
|
||||
|
||||
if (payload.ChannelId != _currentChannelId)
|
||||
return;
|
||||
|
||||
if (payload.SenderUsername == _username)
|
||||
return;
|
||||
|
||||
var privateKey = KeyStorage.LoadPrivateKey(_username);
|
||||
|
||||
var decryptedJson = E2EeHelper.DecryptForRecipient(
|
||||
new EncryptedPayload
|
||||
{
|
||||
CipherText = payload.CipherText,
|
||||
Nonce = payload.Nonce,
|
||||
Tag = payload.Tag,
|
||||
EncryptedKey = payload.EncryptedKey
|
||||
},
|
||||
privateKey
|
||||
);
|
||||
|
||||
var rtcSignal = JsonSerializer.Deserialize<RtcSignalMessage>(decryptedJson);
|
||||
|
||||
if (rtcSignal is null)
|
||||
return;
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(rtcSignal.To) &&
|
||||
!string.Equals(rtcSignal.To, _username, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
SafeSendRawToWebView($"Ignoring RTC signal meant for {rtcSignal.To}");
|
||||
return;
|
||||
}
|
||||
|
||||
SafeSendRawToWebView("Received encrypted RTC signal: " + decryptedJson);
|
||||
|
||||
MainThread.BeginInvokeOnMainThread(async () =>
|
||||
{
|
||||
await SendRtcSignalToJsAsync(decryptedJson);
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (type is SignalType.OfferUpdated or SignalType.AnswerUpdated or SignalType.CandidateAdded or SignalType.CallLeft)
|
||||
{
|
||||
var rtcNotification = JsonSerializer.Deserialize<RtcNotificationMessage>(e.Data);
|
||||
if (rtcNotification is null)
|
||||
return;
|
||||
|
||||
var notificationType = rtcNotification.Type;
|
||||
var notificationChannelId = rtcNotification.ChannelId ?? string.Empty;
|
||||
|
||||
if (notificationChannelId != _currentChannelId)
|
||||
return;
|
||||
|
||||
// SafeSendRawToWebView("RTC notification received: " + notificationType + " for " + notificationChannelId);
|
||||
|
||||
MainThread.BeginInvokeOnMainThread(async () =>
|
||||
{
|
||||
switch (notificationType)
|
||||
{
|
||||
case SignalType.OfferUpdated:
|
||||
{
|
||||
if (rtcNotification.Username == _username)
|
||||
break;
|
||||
|
||||
var offer = await GetRtcOffer();
|
||||
await SendRtcSignalToJsAsync(offer);
|
||||
break;
|
||||
}
|
||||
case SignalType.AnswerUpdated:
|
||||
{
|
||||
var answer = await ServerAPI.GetAnswerForChannelAsync(_currentChannelId);
|
||||
if (answer is not null)
|
||||
{
|
||||
await AnswerCallback(answer);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case SignalType.CandidateAdded:
|
||||
{
|
||||
if (rtcNotification.Username == _username)
|
||||
break;
|
||||
|
||||
try
|
||||
{
|
||||
IceCandidate? iceCandidate = JsonSerializer.Deserialize<IceCandidate>(rtcNotification.Direction);
|
||||
|
||||
if (iceCandidate is null)
|
||||
break;
|
||||
|
||||
IceCandidateCallback(iceCandidate);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
SafeSendRawToWebView($"Candidate rejected: {ex.Message}");
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case SignalType.CallLeft:
|
||||
{
|
||||
SafeSendRawToWebView("RTC call left notification received.");
|
||||
RtcLeaveCallback();
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (type != SignalType.EncryptedChat)
|
||||
return;
|
||||
|
||||
var pyload = JsonSerializer.Deserialize<SocketEncryptedMessage>(e.Data);
|
||||
if (pyload is null)
|
||||
return;
|
||||
|
||||
if (pyload.RecipientUsername != _username)
|
||||
return;
|
||||
|
||||
Console.WriteLine($"[{_username}] received encrypted payload for {pyload.RecipientUsername}");
|
||||
|
||||
var privKey = KeyStorage.LoadPrivateKey(_username);
|
||||
|
||||
var decryptedText = E2EeHelper.DecryptForRecipient(
|
||||
decryptedText = E2EeHelper.DecryptForRecipient(
|
||||
new EncryptedPayload
|
||||
{
|
||||
CipherText = pyload.CipherText,
|
||||
Nonce = pyload.Nonce,
|
||||
Tag = pyload.Tag,
|
||||
EncryptedKey = pyload.EncryptedKey
|
||||
CipherText = payload.CipherText,
|
||||
Nonce = payload.Nonce,
|
||||
Tag = payload.Tag,
|
||||
EncryptedKey = payload.EncryptedKey
|
||||
},
|
||||
privKey
|
||||
);
|
||||
|
||||
Console.WriteLine($"[{_username}] decrypted message from {pyload.SenderUsername}: {decryptedText}");
|
||||
|
||||
var message = new ChatMessage
|
||||
{
|
||||
SenderUsername = pyload.SenderUsername,
|
||||
Text = decryptedText,
|
||||
Timestamp = DateTime.Now
|
||||
};
|
||||
|
||||
if (!_messagesByChannel.ContainsKey(pyload.ChannelId))
|
||||
{
|
||||
_messagesByChannel[pyload.ChannelId] = [];
|
||||
}
|
||||
|
||||
_messagesByChannel[pyload.ChannelId].Add(message);
|
||||
|
||||
if (pyload.ChannelId == _currentChannelId)
|
||||
{
|
||||
MainThread.BeginInvokeOnMainThread(() =>
|
||||
{
|
||||
RenderSingleMessage(message);
|
||||
});
|
||||
}
|
||||
privateKey
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"[{_username}] failed to process websocket message: {ex.Message}");
|
||||
Console.WriteLine($"[{_username}] failed to decrypt chat: {ex.Message}");
|
||||
return;
|
||||
}
|
||||
|
||||
var message = new ChatMessage
|
||||
{
|
||||
SenderUsername = payload.SenderUsername,
|
||||
Text = decryptedText,
|
||||
Timestamp = DateTime.Now
|
||||
};
|
||||
|
||||
if (!_messagesByChannel.ContainsKey(payload.ChannelId))
|
||||
_messagesByChannel[payload.ChannelId] = [];
|
||||
|
||||
_messagesByChannel[payload.ChannelId].Add(message);
|
||||
|
||||
if (payload.ChannelId == _currentChannelId)
|
||||
{
|
||||
MainThread.BeginInvokeOnMainThread(() =>
|
||||
{
|
||||
RenderSingleMessage(message);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnDisappearing()
|
||||
{
|
||||
_wsc.OnMessage -= WscOnMessage;
|
||||
_wsc.Close();
|
||||
_socket.Disconnect();
|
||||
base.OnDisappearing();
|
||||
}
|
||||
|
||||
@@ -361,14 +206,17 @@ public partial class MainPage : ContentPage
|
||||
{
|
||||
_currentChannelId = channel.ChannelId;
|
||||
_currentChannelName = channel.Name;
|
||||
|
||||
|
||||
MainThread.BeginInvokeOnMainThread(async () =>
|
||||
{
|
||||
await PushRtcContextToJsAsync();
|
||||
await _rtc.PushRtcContextToJsAsync();
|
||||
|
||||
if (channel.Type == ChannelType.Voice)
|
||||
{
|
||||
SwapView();
|
||||
// JoinRtcChannel(); //TODO: Join voice calls when clicking channel rather than a separate button
|
||||
if (!RtcView.IsVisible)
|
||||
SwapView();
|
||||
|
||||
_ = _rtc.JoinRtcChannel();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -376,9 +224,7 @@ public partial class MainPage : ContentPage
|
||||
RenderCurrentChannelMessages();
|
||||
|
||||
if (!_messagesByChannel.ContainsKey(channel.ChannelId))
|
||||
{
|
||||
_wsc.Send($"GET_HISTORY|{_username}|{channel.ChannelId}");
|
||||
}
|
||||
_socket.SendRaw($"GET_HISTORY|{_username}|{channel.ChannelId}");
|
||||
};
|
||||
|
||||
SidebarList.Children.Add(button);
|
||||
@@ -403,7 +249,7 @@ public partial class MainPage : ContentPage
|
||||
|
||||
private async void RenderSingleMessage(ChatMessage message)
|
||||
{
|
||||
bool isOwnMessage = message.SenderUsername == _username;
|
||||
var isOwnMessage = message.SenderUsername == _username;
|
||||
|
||||
var bubble = new Border
|
||||
{
|
||||
@@ -438,7 +284,6 @@ public partial class MainPage : ContentPage
|
||||
MessagesScrollView.IsVisible = true;
|
||||
RtcView.IsVisible = false;
|
||||
ViewSwapped.Text = "Swap to Web View";
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -447,260 +292,23 @@ public partial class MainPage : ContentPage
|
||||
ViewSwapped.Text = "Swap to Message View";
|
||||
}
|
||||
}
|
||||
|
||||
private void SwapView_OnClicked(object? sender, EventArgs e)
|
||||
{
|
||||
SwapView();
|
||||
}
|
||||
|
||||
#region RTC Functions
|
||||
public async Task JoinRtcChannel()
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(_currentChannelId))
|
||||
return; //false;
|
||||
|
||||
_wsc.Send($"RTC_JOIN_CHANNEL|{_username}|{_currentChannelId}");
|
||||
|
||||
// SafeSendRawToWebView($"Attempting to join RTC Channel {_currentChannelName} | {_currentChannelId} ");
|
||||
|
||||
//bool active = await ServerAPI.GetIsChannelActiveAsync(_currentChannelId);
|
||||
|
||||
//SafeSendRawToWebView($"Rtc Channel {_currentChannelName} | {_currentChannelId} is active: {active}");
|
||||
|
||||
return; //active;
|
||||
}
|
||||
|
||||
public void LeaveRtcChannel()
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(_currentChannelId))
|
||||
return;
|
||||
|
||||
_wsc.Send($"RTC_LEAVE_CHANNEL|{_username}|{_currentChannelId}");
|
||||
}
|
||||
|
||||
public async void WriteRtcOffer(string json)
|
||||
{
|
||||
try
|
||||
{
|
||||
RtcDescription? description = JsonSerializer.Deserialize<RtcDescription>(json);
|
||||
DBOffer offer = new DBOffer
|
||||
{
|
||||
ChannelId = _currentChannelId,
|
||||
Username = _username,
|
||||
SessionDescription = description
|
||||
};
|
||||
var response = await ServerAPI.PostOfferAsync(offer);
|
||||
SafeSendRawToWebView(response.ToString());
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
SafeSendRawToWebView($"WriteRtcOffer failed: {ex.Message}");
|
||||
}
|
||||
|
||||
}
|
||||
public async Task<string> GetRtcOffer()
|
||||
{
|
||||
RtcDescription? offer = await ServerAPI.GetOffersForChannelAsync(_currentChannelId);
|
||||
return JsonSerializer.Serialize(offer);
|
||||
}
|
||||
|
||||
public async void WriteRtcAnswer(string json)
|
||||
{
|
||||
// SafeSendRawToWebView("WriteRtcAnswer entered with: " + json);
|
||||
|
||||
try
|
||||
{
|
||||
RtcDescription? description = JsonSerializer.Deserialize<RtcDescription>(json);
|
||||
DBOffer answer = new DBOffer
|
||||
{
|
||||
ChannelId = _currentChannelId,
|
||||
Username = _username,
|
||||
SessionDescription = description
|
||||
};
|
||||
await ServerAPI.PostAnswerAsync(answer);
|
||||
SafeSendRawToWebView("WriteRtcAnswer posted successfully");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
SafeSendRawToWebView("WriteRtcAnswer failed: " + ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public async void WriteIceCandidate(string json)
|
||||
{
|
||||
try
|
||||
{
|
||||
IceCandidate? candidate = JsonSerializer.Deserialize<IceCandidate>(json);
|
||||
DBIceCandidate DBCandidate = new DBIceCandidate
|
||||
{
|
||||
ChannelId = _currentChannelId,
|
||||
Username = _username,
|
||||
Candidate = candidate
|
||||
};
|
||||
if (candidate == null) return;
|
||||
await ServerAPI.PostIceCandidateAsync(DBCandidate);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
SafeSendRawToWebView("WriteIceCandidate failed: " + ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public async void IceCandidateCallback(IceCandidate candidate)
|
||||
{
|
||||
try
|
||||
{
|
||||
await hybridWebView.InvokeJavaScriptAsync("IceCandidateAdded", [candidate], [HybridJSType.Default.IceCandidate]);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
SafeSendRawToWebView("WriteIceCandidate failed: " + ex.Message);
|
||||
}
|
||||
}
|
||||
public async Task AnswerCallback(RtcDescription answer)
|
||||
{
|
||||
answer.sdp = answer.sdp.Replace("\r\n", "(rn)");
|
||||
try
|
||||
{
|
||||
await hybridWebView.InvokeJavaScriptAsync("AnswerCallbackJS", [answer], [HybridJSType.Default.RtcDescription]);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
SafeSendRawToWebView("AnswerCallback failed: " + ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public async void RtcLeaveCallback()
|
||||
{
|
||||
try
|
||||
{
|
||||
await hybridWebView.InvokeJavaScriptAsync("RtcLeaveCall", [], []);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
SafeSendRawToWebView("RtcLeaveCallback failed: " + ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
private Task SendRtcSignalToJsAsync(string rawJson)
|
||||
{
|
||||
MainThread.BeginInvokeOnMainThread(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
SafeSendRawToWebView("Dispatching RTC signal to JS");
|
||||
|
||||
var jsArg = JsonSerializer.Serialize(rawJson);
|
||||
|
||||
await hybridWebView.EvaluateJavaScriptAsync(
|
||||
$"window.RelaySocket.receiveRtcSignal({jsArg})"
|
||||
);
|
||||
|
||||
SafeSendRawToWebView("RTC signal dispatched to JS");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
SafeSendRawToWebView("SendRtcSignalToJsAsync failed: " + ex.Message);
|
||||
}
|
||||
});
|
||||
|
||||
return Task.CompletedTask;
|
||||
} //Remove?
|
||||
|
||||
private async Task PushRtcContextToJsAsync()
|
||||
{
|
||||
var usernameJson = JsonSerializer.Serialize(_username);
|
||||
var channelIdJson = JsonSerializer.Serialize(_currentChannelId);
|
||||
|
||||
await hybridWebView.EvaluateJavaScriptAsync($"window.setUsername({usernameJson})");
|
||||
await hybridWebView.EvaluateJavaScriptAsync($"window.setChannelId({channelIdJson})");
|
||||
|
||||
Console.WriteLine($"[{_username}] pushed RTC context into HybridWebView.");
|
||||
} //Remove?
|
||||
|
||||
public void SendRtcSignal(string json)
|
||||
{
|
||||
SafeSendRawToWebView("SendRtcSignal entered: " + json);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(_serverPublicKey))
|
||||
{
|
||||
SafeSendRawToWebView("SendRtcSignal failed: server public key not loaded.");
|
||||
return;
|
||||
}
|
||||
|
||||
RtcSignalMessage? rtcSignal;
|
||||
|
||||
try
|
||||
{
|
||||
rtcSignal = JsonSerializer.Deserialize<RtcSignalMessage>(json);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
SafeSendRawToWebView("SendRtcSignal failed to parse RTC signal: " + ex.Message);
|
||||
return;
|
||||
}
|
||||
|
||||
if (rtcSignal is null)
|
||||
{
|
||||
SafeSendRawToWebView("SendRtcSignal failed: rtcSignal was null.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(rtcSignal.ChannelId))
|
||||
{
|
||||
SafeSendRawToWebView("SendRtcSignal failed: channelId was empty.");
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var encrypted = E2EeHelper.EncryptForRecipient(json, _serverPublicKey);
|
||||
|
||||
var payload = new SocketRtcSignalMessage
|
||||
{
|
||||
Type = SignalType.EncryptedSignal,
|
||||
SenderUsername = _username,
|
||||
ChannelId = rtcSignal.ChannelId,
|
||||
CipherText = encrypted.CipherText,
|
||||
Nonce = encrypted.Nonce,
|
||||
Tag = encrypted.Tag,
|
||||
EncryptedKey = encrypted.EncryptedKey
|
||||
};
|
||||
|
||||
var socketJson = JsonSerializer.Serialize(payload);
|
||||
_wsc.Send(socketJson);
|
||||
|
||||
SafeSendRawToWebView($"SendRtcSignal sent: {rtcSignal.Type} -> {rtcSignal.ChannelId}");
|
||||
Console.WriteLine($"[{_username}] sent RTC signal: {rtcSignal.Type} -> {rtcSignal.ChannelId}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
SafeSendRawToWebView("SendRtcSignal websocket/encrypt failed: " + ex.Message);
|
||||
}
|
||||
} //Remove?
|
||||
|
||||
public async Task<string> GetRtcParticipants()
|
||||
{
|
||||
var participants = await ServerAPI.GetRtcParticipantsAsync(_currentChannelId);
|
||||
return JsonSerializer.Serialize(participants);
|
||||
}
|
||||
|
||||
#endregion
|
||||
private void OnSendMessageButtonClicked(object sender, EventArgs e)
|
||||
{
|
||||
SafeSendRawToWebView($"Hello from C#!");
|
||||
}
|
||||
|
||||
private async void OnHybridWebViewRawMessageReceived(object sender, HybridWebViewRawMessageReceivedEventArgs e)
|
||||
{
|
||||
if (e.Message == "rtc_page_ready")
|
||||
{
|
||||
await PushRtcContextToJsAsync();
|
||||
await _rtc.PushRtcContextToJsAsync();
|
||||
return;
|
||||
}
|
||||
|
||||
SafeSendRawToWebView($"JS RAW -> C#: {e.Message}");
|
||||
}
|
||||
|
||||
|
||||
private void SafeSendRawToWebView(string message)
|
||||
{
|
||||
MainThread.BeginInvokeOnMainThread(() =>
|
||||
@@ -719,9 +327,9 @@ public partial class MainPage : ContentPage
|
||||
public class ChannelButton : Button
|
||||
{
|
||||
public ChannelType Type { get; set; }
|
||||
public string Group { get; set; }
|
||||
public string Group { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
|
||||
[JsonSourceGenerationOptions(WriteIndented = false)]
|
||||
[JsonSerializable(typeof(RtcDescription))]
|
||||
[JsonSerializable(typeof(List<RtcSignalMessage>))]
|
||||
@@ -730,8 +338,5 @@ public partial class MainPage : ContentPage
|
||||
[JsonSerializable(typeof(string))]
|
||||
internal partial class HybridJSType : JsonSerializerContext
|
||||
{
|
||||
// This type's attributes specify JSON serialization info to preserve type structure
|
||||
// for trimmed builds.
|
||||
}
|
||||
|
||||
}
|
||||
@@ -49,4 +49,23 @@ window.addEventListener("load", async () => {
|
||||
Media.wireDeviceSelectors();
|
||||
await Media.loadDevices();
|
||||
await Media.ensureLocalMedia();
|
||||
});
|
||||
});
|
||||
|
||||
function testIndex(rawJson)
|
||||
{
|
||||
const data = typeof rawJson === "string" ? JSON.parse(rawJson) : rawJson;
|
||||
data.sdp = data.sdp.replaceAll("(rn)", "\r\n");
|
||||
handleRtcSignal(JSON.stringify(data));
|
||||
// if (data.type === "rtc_offer") {
|
||||
// handleOffer(data)
|
||||
// }
|
||||
// if (data.type === "rtc_answer") {
|
||||
// data.sdp = data.sdp.replaceAll("(rn)", "\r\n");
|
||||
// handleAnswer(data)
|
||||
// }
|
||||
}
|
||||
|
||||
function noDataTest()
|
||||
{
|
||||
LogMessage("No Data Called!!");
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
const peerConnections = {};
|
||||
const peerConnections = {};
|
||||
|
||||
async function joinChannelCall() {
|
||||
LogMessage("Current username: " + currentUsername);
|
||||
@@ -24,7 +24,7 @@ async function joinChannelCall() {
|
||||
}
|
||||
|
||||
for (const username of existingUsers) {
|
||||
await sendOffer(username);
|
||||
await sendOffer(username); //Creates an offer to each person in call for MESH RTC
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,6 +34,7 @@ async function sendOffer(username) {
|
||||
await Media.applyLocalStreamToPeerConnection(pc, username);
|
||||
|
||||
const offer = await pc.createOffer();
|
||||
// LogMessage(`Offer created: ${JSON.stringify(offer)}`);
|
||||
await pc.setLocalDescription(offer);
|
||||
|
||||
await RelaySocket.sendRtcSignal({
|
||||
@@ -88,11 +89,12 @@ async function handleRtcSignal(rawJson) {
|
||||
}
|
||||
|
||||
async function handleOffer(msg) {
|
||||
LogMessage(`Offer handler: ${msg}`);
|
||||
const pc = await ensurePeerConnectionForUser(msg.from);
|
||||
|
||||
await Media.ensureLocalMedia();
|
||||
await Media.applyLocalStreamToPeerConnection(pc, msg.from);
|
||||
|
||||
// const offer = JSON.parse(msg.offer);
|
||||
await pc.setRemoteDescription({
|
||||
type: "offer",
|
||||
sdp: msg.sdp
|
||||
|
||||
127
RelayClient/Services/RelaySocketClient.cs
Normal file
127
RelayClient/Services/RelaySocketClient.cs
Normal file
@@ -0,0 +1,127 @@
|
||||
using System.Text.Json;
|
||||
using RelayClient.Crypto;
|
||||
using RelayShared.Services;
|
||||
using WebSocketSharp;
|
||||
|
||||
namespace RelayClient.Services;
|
||||
|
||||
public sealed class RelaySocketClient
|
||||
{
|
||||
private readonly string _username;
|
||||
private readonly WebSocket _socket;
|
||||
|
||||
public string? ServerPublicKey { get; private set; }
|
||||
|
||||
public event Action<string>? RawMessageReceived;
|
||||
public event Action<SocketChannelList>? ChannelListReceived;
|
||||
public event Action<SocketEncryptedMessage>? EncryptedChatReceived;
|
||||
public event Action<SocketRtcSignalMessage>? EncryptedRtcSignalReceived;
|
||||
public event Action<string>? ServerPublicKeyReceived;
|
||||
public event Action<string>? Log;
|
||||
|
||||
public RelaySocketClient(string username, string url = "ws://localhost:1337/")
|
||||
{
|
||||
_username = username;
|
||||
_socket = new WebSocket(url);
|
||||
_socket.OnMessage += OnMessage;
|
||||
}
|
||||
|
||||
public void Connect()
|
||||
{
|
||||
_socket.Connect();
|
||||
|
||||
var publicKey = KeyStorage.LoadPublicKey(_username);
|
||||
|
||||
SendRaw($"REGISTER_KEY|{_username}|{publicKey}");
|
||||
SendRaw("GET_SERVER_KEY");
|
||||
SendRaw("GET_CHANNELS");
|
||||
}
|
||||
|
||||
public void SendRaw(string message)
|
||||
{
|
||||
if (_socket.ReadyState == WebSocketState.Open)
|
||||
_socket.Send(message);
|
||||
}
|
||||
|
||||
public void SendJson<T>(T payload)
|
||||
{
|
||||
SendRaw(JsonSerializer.Serialize(payload));
|
||||
}
|
||||
|
||||
public void Disconnect()
|
||||
{
|
||||
_socket.OnMessage -= OnMessage;
|
||||
|
||||
if (_socket.ReadyState == WebSocketState.Open)
|
||||
_socket.Close();
|
||||
}
|
||||
|
||||
private void OnMessage(object? sender, MessageEventArgs e)
|
||||
{
|
||||
if (e.Data.StartsWith("SERVER:REGISTERED_KEY:"))
|
||||
{
|
||||
Log?.Invoke(e.Data);
|
||||
return;
|
||||
}
|
||||
|
||||
RawMessageReceived?.Invoke(e.Data);
|
||||
Log?.Invoke($"[{_username}] RAW WS DATA: {e.Data}");
|
||||
|
||||
try
|
||||
{
|
||||
using var doc = JsonDocument.Parse(e.Data);
|
||||
var root = doc.RootElement;
|
||||
|
||||
if (!root.TryGetProperty("Type", out var typeElement))
|
||||
return;
|
||||
|
||||
var type = (SignalType)typeElement.GetInt32();
|
||||
|
||||
switch (type)
|
||||
{
|
||||
case SignalType.ChannelList:
|
||||
{
|
||||
var channelList = JsonSerializer.Deserialize<SocketChannelList>(e.Data);
|
||||
if (channelList is not null)
|
||||
ChannelListReceived?.Invoke(channelList);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
case SignalType.ServerPublicKey:
|
||||
{
|
||||
var serverKeyMessage = JsonSerializer.Deserialize<ServerPublicKeyMessage>(e.Data);
|
||||
if (serverKeyMessage is not null)
|
||||
{
|
||||
ServerPublicKey = serverKeyMessage.PublicKey;
|
||||
ServerPublicKeyReceived?.Invoke(serverKeyMessage.PublicKey);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
case SignalType.EncryptedSignal:
|
||||
{
|
||||
var payload = JsonSerializer.Deserialize<SocketRtcSignalMessage>(e.Data);
|
||||
if (payload is not null)
|
||||
EncryptedRtcSignalReceived?.Invoke(payload);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
case SignalType.EncryptedChat:
|
||||
{
|
||||
var payload = JsonSerializer.Deserialize<SocketEncryptedMessage>(e.Data);
|
||||
if (payload is not null)
|
||||
EncryptedChatReceived?.Invoke(payload);
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log?.Invoke($"[{_username}] failed to process websocket message: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
255
RelayClient/Services/RtcBridgeService.cs
Normal file
255
RelayClient/Services/RtcBridgeService.cs
Normal file
@@ -0,0 +1,255 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using RelayClient.Crypto;
|
||||
using RelayShared.Rtc;
|
||||
using RelayShared.Services;
|
||||
|
||||
namespace RelayClient.Services;
|
||||
|
||||
public sealed class RtcBridgeService
|
||||
{
|
||||
private readonly string _username;
|
||||
private readonly RelaySocketClient _socket;
|
||||
private readonly HybridWebView _hybridWebView;
|
||||
private readonly Func<string?> _getCurrentChannelId;
|
||||
private readonly Action<string> _sendRawToWebView;
|
||||
|
||||
public RtcBridgeService(string username, RelaySocketClient socket, HybridWebView hybridWebView,
|
||||
Func<string?> getCurrentChannelId, Action<string> sendRawToWebView)
|
||||
{
|
||||
_username = username;
|
||||
_socket = socket;
|
||||
_hybridWebView = hybridWebView;
|
||||
_getCurrentChannelId = getCurrentChannelId;
|
||||
_sendRawToWebView = sendRawToWebView;
|
||||
}
|
||||
|
||||
public Task JoinRtcChannel()
|
||||
{
|
||||
var channelId = _getCurrentChannelId();
|
||||
|
||||
if (string.IsNullOrWhiteSpace(channelId))
|
||||
return Task.CompletedTask;
|
||||
|
||||
_socket.SendRaw($"RTC_JOIN_CHANNEL|{_username}|{channelId}");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public void LeaveRtcChannel()
|
||||
{
|
||||
var channelId = _getCurrentChannelId();
|
||||
|
||||
if (string.IsNullOrWhiteSpace(channelId))
|
||||
return;
|
||||
|
||||
_socket.SendRaw($"RTC_LEAVE_CHANNEL|{_username}|{channelId}");
|
||||
}
|
||||
|
||||
public void SendRtcSignal(string json)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(_socket.ServerPublicKey))
|
||||
{
|
||||
_sendRawToWebView("SendRtcSignal failed: server public key not loaded.");
|
||||
return;
|
||||
}
|
||||
|
||||
RtcSignalMessage? rtcSignal;
|
||||
|
||||
try
|
||||
{
|
||||
rtcSignal = JsonSerializer.Deserialize<RtcSignalMessage>(json);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_sendRawToWebView("SendRtcSignal failed to parse RTC signal: " + ex.Message);
|
||||
return;
|
||||
}
|
||||
|
||||
if (rtcSignal is null)
|
||||
return;
|
||||
|
||||
rtcSignal.ChannelId ??= _getCurrentChannelId();
|
||||
rtcSignal.From ??= _username;
|
||||
|
||||
// _sendRawToWebView($"RTC_SIGNAL file: {JsonSerializer.Serialize(rtcSignal)}");
|
||||
if (string.IsNullOrWhiteSpace(rtcSignal.ChannelId))
|
||||
{
|
||||
_sendRawToWebView("SendRtcSignal failed: missing channel id.");
|
||||
return;
|
||||
}
|
||||
|
||||
var outgoingJson = JsonSerializer.Serialize(rtcSignal);
|
||||
|
||||
try
|
||||
{
|
||||
var encrypted = E2EeHelper.EncryptForRecipient(outgoingJson, _socket.ServerPublicKey);
|
||||
|
||||
var payload = new SocketRtcSignalMessage
|
||||
{
|
||||
Type = SignalType.EncryptedSignal,
|
||||
SenderUsername = _username,
|
||||
ChannelId = rtcSignal.ChannelId,
|
||||
CipherText = encrypted.CipherText,
|
||||
Nonce = encrypted.Nonce,
|
||||
Tag = encrypted.Tag,
|
||||
EncryptedKey = encrypted.EncryptedKey
|
||||
};
|
||||
|
||||
_socket.SendJson(payload);
|
||||
|
||||
_sendRawToWebView($"SendRtcSignal sent: {rtcSignal.Type} -> {rtcSignal.To}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_sendRawToWebView("SendRtcSignal failed: " + ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<string> GetRtcParticipants()
|
||||
{
|
||||
var channelId = _getCurrentChannelId();
|
||||
|
||||
if (string.IsNullOrWhiteSpace(channelId))
|
||||
return "[]";
|
||||
|
||||
var participants = await ServerAPI.GetRtcParticipantsAsync(channelId);
|
||||
return JsonSerializer.Serialize(participants ?? []);
|
||||
}
|
||||
|
||||
public async Task HandleIncomingRtcSignalAsync(SocketRtcSignalMessage payload)
|
||||
{
|
||||
// _sendRawToWebView("HandleIncomingRtcSignal called");
|
||||
var currentChannelId = _getCurrentChannelId();
|
||||
|
||||
if (payload.ChannelId != currentChannelId)
|
||||
{
|
||||
_sendRawToWebView("Channel id does not match");
|
||||
return;
|
||||
}
|
||||
|
||||
if (payload.SenderUsername == _username)
|
||||
{
|
||||
_sendRawToWebView("Received own message");
|
||||
return;
|
||||
}
|
||||
|
||||
string decryptedJson;
|
||||
|
||||
try
|
||||
{
|
||||
var privateKey = KeyStorage.LoadPrivateKey(_username);
|
||||
|
||||
decryptedJson = E2EeHelper.DecryptForRecipient(
|
||||
new EncryptedPayload
|
||||
{
|
||||
CipherText = payload.CipherText,
|
||||
Nonce = payload.Nonce,
|
||||
Tag = payload.Tag,
|
||||
EncryptedKey = payload.EncryptedKey
|
||||
},
|
||||
privateKey
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_sendRawToWebView("RTC decrypt failed: " + ex.Message);
|
||||
return;
|
||||
}
|
||||
|
||||
RtcSignalMessage? rtcSignal;
|
||||
|
||||
try
|
||||
{
|
||||
rtcSignal = JsonSerializer.Deserialize<RtcSignalMessage>(decryptedJson);
|
||||
// _sendRawToWebView($"Received Encrypted Signal: [{rtcSignal.From}]: {rtcSignal.Offer}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_sendRawToWebView("RTC signal parse failed: " + ex.Message);
|
||||
return;
|
||||
}
|
||||
|
||||
if (rtcSignal is null)
|
||||
{
|
||||
_sendRawToWebView("rtcSignal is null");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(rtcSignal.To) &&
|
||||
!string.Equals(rtcSignal.To, _username, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
_sendRawToWebView($"Ignoring RTC signal meant for {rtcSignal.To}");
|
||||
return;
|
||||
}
|
||||
|
||||
// _sendRawToWebView("Received encrypted RTC signal: " + decryptedJson);
|
||||
|
||||
await SendRtcSignalToJsAsync(rtcSignal);
|
||||
}
|
||||
|
||||
public Task PushRtcContextToJsAsync()
|
||||
{
|
||||
MainThread.BeginInvokeOnMainThread(async () =>
|
||||
{
|
||||
var usernameJson = JsonSerializer.Serialize(_username);
|
||||
var channelIdJson = JsonSerializer.Serialize(_getCurrentChannelId());
|
||||
|
||||
await _hybridWebView.EvaluateJavaScriptAsync($"window.setUsername({usernameJson})");
|
||||
await _hybridWebView.EvaluateJavaScriptAsync($"window.setChannelId({channelIdJson})");
|
||||
});
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private Task SendRtcSignalToJsAsync(RtcSignalMessage data)
|
||||
{
|
||||
if (data.Type == "rtc_offer" || data.Type == "rtc_answer")
|
||||
{
|
||||
data.Sdp = data.Sdp.Replace("\r\n", "(rn)");
|
||||
}
|
||||
MainThread.BeginInvokeOnMainThread(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
// await _hybridWebView.InvokeJavaScriptAsync("testIndex", [JsonSerializer.Serialize(data)], [RtcJsType.Default.String]);
|
||||
await _hybridWebView.InvokeJavaScriptAsync("testIndex", [data], [RtcJsType.Default.RtcSignalMessage]);
|
||||
#region OldDebugger
|
||||
// var jsArg = JsonSerializer.Serialize(data);
|
||||
//
|
||||
// await _hybridWebView.EvaluateJavaScriptAsync($@"
|
||||
// try {{
|
||||
// window.HybridWebView.SendRawMessage('C# eval entered');
|
||||
//
|
||||
// if (!window.RelaySocket) {{
|
||||
// window.HybridWebView.SendRawMessage('window.RelaySocket missing');
|
||||
// }} else if (typeof window.RelaySocket.receiveRtcSignal !== 'function') {{
|
||||
// window.HybridWebView.SendRawMessage('RelaySocket.receiveRtcSignal missing');
|
||||
// }} else {{
|
||||
// window.HybridWebView.SendRawMessage('Calling RelaySocket.receiveRtcSignal');
|
||||
// window.RelaySocket.receiveRtcSignal({jsArg});
|
||||
// }}
|
||||
// }} catch (err) {{
|
||||
// window.HybridWebView.SendRawMessage('RTC JS dispatch failed: ' + err);
|
||||
// }}
|
||||
// ");
|
||||
#endregion
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_sendRawToWebView("SendRtcSignalToJsAsync failed: " + ex.Message);
|
||||
}
|
||||
});
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(WriteIndented = false)]
|
||||
[JsonSerializable(typeof(RtcDescription))]
|
||||
[JsonSerializable(typeof(List<RtcSignalMessage>))]
|
||||
[JsonSerializable(typeof(RtcSignalMessage))]
|
||||
[JsonSerializable(typeof(IceCandidate))]
|
||||
[JsonSerializable(typeof(List<IceCandidate>))]
|
||||
[JsonSerializable(typeof(string))]
|
||||
internal partial class RtcJsType : JsonSerializerContext
|
||||
{
|
||||
}
|
||||
59
RelayCore/Endpoints/AuthEndpoints.cs
Normal file
59
RelayCore/Endpoints/AuthEndpoints.cs
Normal file
@@ -0,0 +1,59 @@
|
||||
using RelayCore.Services;
|
||||
|
||||
namespace RelayCore.Endpoints;
|
||||
|
||||
public static class AuthEndpoints
|
||||
{
|
||||
public static void MapAuthEndpoints(this WebApplication app)
|
||||
{
|
||||
app.MapPost("/user/signin", async (AuthSignin request, APIAuthService service, HttpContext context) =>
|
||||
{
|
||||
var ip = context.Connection.RemoteIpAddress?.MapToIPv4().ToString();
|
||||
context.Request.Headers.TryGetValue("User-Agent", out var userAgent);
|
||||
|
||||
Console.WriteLine($"IP:{ip}\nUserAgent:{userAgent}");
|
||||
// var token = await service.UserSigninAsync(request, ip, userAgent);
|
||||
|
||||
// return token != null ? Results.Ok(token) : Results.Unauthorized();
|
||||
return Results.Ok();
|
||||
});
|
||||
app.MapPost("/user/register", async (AuthRegister request, APIAuthService service) =>
|
||||
{
|
||||
var token = await service.UserRegisterAsync(request);
|
||||
return token != null ? Results.Ok(token) : Results.Unauthorized();
|
||||
});
|
||||
app.MapPost("/server/verify/user", async (AuthUserVerify request, APIAuthService service) =>
|
||||
{
|
||||
bool valid = await service.ServerVerifyUser(request);
|
||||
return Results.Ok(valid);
|
||||
});
|
||||
app.MapPost("/server/verify/license", async (AuthServerLicense request, APIAuthService service) =>
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public class AuthSignin
|
||||
{
|
||||
public string UserName { get; set; }
|
||||
public string Password { get; set; }
|
||||
}
|
||||
|
||||
public class AuthRegister
|
||||
{
|
||||
public string Username { get; set; }
|
||||
public string Password { get; set; }
|
||||
public string Email { get; set; }
|
||||
}
|
||||
|
||||
public class AuthUserVerify
|
||||
{
|
||||
public string Username { get; set; }
|
||||
public string Token { get; set; }
|
||||
}
|
||||
|
||||
public class AuthServerLicense
|
||||
{
|
||||
public string License { get; set; }
|
||||
}
|
||||
@@ -22,7 +22,7 @@ namespace RelayCore.Models
|
||||
/// <summary>
|
||||
/// Number of threads to use for parallel computation
|
||||
/// </summary>
|
||||
private const int DegreeOfParallelism = 1;
|
||||
private const int DegreeOfParallelism = 2;
|
||||
|
||||
/// <summary>
|
||||
/// Number of iterations for the Argon2id algorithm
|
||||
|
||||
@@ -4,7 +4,7 @@ namespace RelayCore.Models;
|
||||
|
||||
public class Sessions : Record
|
||||
{
|
||||
public required string UserId { get; set; }
|
||||
public required RecordId UserId { get; set; }
|
||||
public required string TokenHash { get; set; }
|
||||
public required DateTime IssuedAt { get; set; }
|
||||
public required DateTime ExpiresAt { get; set; }
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
using SurrealDb.Net;
|
||||
using SurrealDb.Net.Models.Auth;
|
||||
using System.Text.Json;
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Threading.Tasks;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
using RelayCore.Enums;
|
||||
using RelayCore.Models;
|
||||
using RelayCore.Endpoints;
|
||||
using RelayCore.Services;
|
||||
|
||||
|
||||
await using var db = new SurrealDbClient("ws://127.0.0.1:8000/rpc");
|
||||
@@ -25,8 +24,25 @@ Console.WriteLine($"Keeper created: {ToJsonString(keeper)}");
|
||||
Console.WriteLine($"Kira created: {ToJsonString(kira)}");
|
||||
Console.WriteLine($"Test created: {ToJsonString(test)}");
|
||||
|
||||
await server.Main(db);
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
builder.WebHost.UseUrls("http://127.0.0.1:1337/");
|
||||
builder.Services.AddSingleton(db);
|
||||
builder.Services.AddScoped<APIAuthService>();
|
||||
|
||||
var app = builder.Build();
|
||||
app.MapGet("/", () => "Auth Server Running!");
|
||||
app.MapAuthEndpoints();
|
||||
|
||||
// await server.Main(db);
|
||||
|
||||
await app.StartAsync();
|
||||
Console.WriteLine("API Started");
|
||||
Console.WriteLine("\n\n\n");
|
||||
|
||||
Console.Write("Press any key to stop.");
|
||||
Console.ReadKey(true);
|
||||
|
||||
await app.StopAsync();
|
||||
return;
|
||||
|
||||
static string ToJsonString(object? o)
|
||||
@@ -51,7 +67,7 @@ static async Task<Users> CreateUserAsync(SurrealDbClient db, string username, st
|
||||
OnlineStatus = (int)OnlineStatuses.Online,
|
||||
};
|
||||
|
||||
var created = await db.Create("users", user);
|
||||
var created = await db.Create("auth_users", user);
|
||||
|
||||
var hasher = new PasswordHasher();
|
||||
var passwordHash = hasher.HashPassword(created.Id.ToString() + rawPassword);
|
||||
@@ -65,7 +81,6 @@ static async Task<Users> CreateUserAsync(SurrealDbClient db, string username, st
|
||||
return updated;
|
||||
}
|
||||
|
||||
|
||||
partial class Program
|
||||
{
|
||||
public async Task Main(SurrealDbClient db)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
@@ -10,11 +10,12 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Konscious.Security.Cryptography.Argon2" Version="1.3.1" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.SignalR" Version="1.2.9" />
|
||||
<PackageReference Include="SurrealDb.Net" Version="0.9.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Folder Include="Services\" />
|
||||
<ProjectReference Include="..\RelayShared\RelayShared.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
49
RelayCore/Services/APIAuthService.cs
Normal file
49
RelayCore/Services/APIAuthService.cs
Normal file
@@ -0,0 +1,49 @@
|
||||
using RelayCore.Endpoints;
|
||||
using RelayCore.Models;
|
||||
using SurrealDb.Net;
|
||||
using SurrealDb.Net.Models;
|
||||
|
||||
namespace RelayCore.Services;
|
||||
|
||||
public class APIAuthService(SurrealDbClient _db)
|
||||
{
|
||||
|
||||
public async Task<string> UserSigninAsync(AuthSignin request)
|
||||
{
|
||||
var hasher = new PasswordHasher();
|
||||
var users = await _db.Select<Users>("auth_users");
|
||||
var user = users.FirstOrDefault(x => (x.Username == request.UserName || x.Email == request.UserName)
|
||||
&& hasher.VerifyPassword(request.Password, x.Password));
|
||||
var tokens = await _db.Select<Sessions>("auth_sessions");
|
||||
var token = tokens.Where(x => x.UserId == user.Id && !x.Revoked).OrderByDescending(x => x.ExpiresAt).FirstOrDefault();
|
||||
if (token.ExpiresAt > DateTime.UtcNow)
|
||||
return token.TokenHash;
|
||||
|
||||
//TODO: Generate TOKEN
|
||||
var newToken = hasher.HashPassword($"{user.Email}{user.Username}{user.Password}");
|
||||
//TODO: Store TOKEN and Username for verification
|
||||
var sessionId = await _db.Create<Sessions>(new Sessions
|
||||
{
|
||||
UserId = user.Id,
|
||||
TokenHash = newToken,
|
||||
IssuedAt = DateTime.UtcNow,
|
||||
ExpiresAt = DateTime.UtcNow.AddDays(30),
|
||||
DeviceName = "",
|
||||
Revoked = false,
|
||||
IpAddress = "",
|
||||
UserAgent = ""
|
||||
});
|
||||
//TODO: Add invalidation to TOKENs
|
||||
return newToken;
|
||||
}
|
||||
|
||||
public async Task<string> UserRegisterAsync(AuthRegister request)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public async Task<bool> ServerVerifyUser(AuthUserVerify request)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,7 @@ var bootstrapService = new ServerBootstrapService(db, coreClient, cryptoService)
|
||||
await bootstrapService.InitializeAsync();
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
builder.WebHost.UseUrls("http://127.0.0.1:5000/");
|
||||
|
||||
builder.Services.AddSingleton(db);
|
||||
builder.Services.AddScoped<RtcCallService>();
|
||||
|
||||
@@ -6,7 +6,7 @@ using RelayServer.Services.Rtc;
|
||||
using WebSocketSharp;
|
||||
using WebSocketSharp.Server;
|
||||
using ErrorEventArgs = WebSocketSharp.ErrorEventArgs;
|
||||
using RelayShared.Rtc;
|
||||
using RelayShared.Services;
|
||||
|
||||
namespace RelayServer.Services.Chat;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user