marriedtermiteblyi commited on
Commit
a38217b
·
verified ·
1 Parent(s): a0220bf

put notes/af7dc466-f77f-42ba-b353-b9722675764b.json

Browse files
notes/af7dc466-f77f-42ba-b353-b9722675764b.json CHANGED
@@ -2,7 +2,7 @@
2
  "id": "af7dc466-f77f-42ba-b353-b9722675764b",
3
  "title": "HttpProxyServer.cs",
4
  "content": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Drawing;\r\nusing System.Drawing.Imaging;\r\nusing System.IO;\r\nusing System.Net;\r\nusing System.Net.Http;\r\nusing System.Net.Http.Headers;\r\nusing System.Net.Sockets;\r\nusing System.Text;\r\nusing System.Text.Json;\r\nusing System.Threading.Tasks;\r\nusing System.Windows.Forms;\r\n\r\nnamespace rikkei_education_service;\r\n\r\npublic class HttpProxyServer\r\n{\r\n\tprivate MainWindow mainWindow;\r\n\r\n\tprivate TcpListener listener;\r\n\r\n\tpublic bool isRunning = false;\r\n\r\n\tprivate int port = 8888;\r\n\r\n\tprivate string violateHost = Environment.GetEnvironmentVariable(\"VIOLATE_HOST\");\r\n\r\n\tpublic bool blockUrl = false;\r\n\r\n\tprivate readonly Dictionary<string, DateTime> lastNotificationTime = new Dictionary<string, DateTime>();\r\n\r\n\tprivate const int NOTIFICATION_COOLDOWN_SECONDS = 120;\r\n\r\n\tprivate readonly string apiEndpoint = \"https://api.raia.edu.vn/api/rikkei-education-app/find-ai-detect-data\";\r\n\r\n\tprivate readonly HttpClient httpClient = new HttpClient();\r\n\r\n\tprivate List<string> aiKeyWords = new List<string>();\r\n\r\n\tpublic HttpProxyServer(MainWindow mainWindow)\r\n\t{\r\n\t\tthis.mainWindow = mainWindow;\r\n\t\tLoadKeywordsFromApiAsync();\r\n\t}\r\n\r\n\tprivate async Task LoadKeywordsFromApiAsync()\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tHttpResponseMessage response = await httpClient.GetAsync(apiEndpoint);\r\n\t\t\tif (response.IsSuccessStatusCode)\r\n\t\t\t{\r\n\t\t\t\tAiDetectApiResponse apiResponse = JsonSerializer.Deserialize<AiDetectApiResponse>(await response.Content.ReadAsStringAsync());\r\n\t\t\t\tif (apiResponse?.data != null)\r\n\t\t\t\t{\r\n\t\t\t\t\taiKeyWords.Clear();\r\n\t\t\t\t\tforeach (AiDetectData item in apiResponse.data)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif (item.status && !string.IsNullOrEmpty(item.keyword))\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\taiKeyWords.Add(item.keyword);\r\n\t\t\t\t\t\t\tif (!string.IsNullOrEmpty(item.serverIp) && !item.serverIp.Equals(item.keyword, StringComparison.OrdinalIgnoreCase))\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\taiKeyWords.Add(item.serverIp);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tLoadFallbackKeywords();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tLoadFallbackKeywords();\r\n\t\t\t}\r\n\t\t}\r\n\t\tcatch (Exception)\r\n\t\t{\r\n\t\t\tLoadFallbackKeywords();\r\n\t\t}\r\n\t}\r\n\r\n\tprivate void LoadFallbackKeywords()\r\n\t{\r\n\t\taiKeyWords = new List<string>\r\n\t\t{\r\n\t\t\t\"openai\", \"chat.com\", \"bard\", \"claude\", \"perplexity\", \"poe\", \"copilot\", \"quillbot\", \"grammarly\", \"jasper\",\r\n\t\t\t\"lm\", \"gpt\", \"cursor\", \"gemini\", \"chatgpt\", \"chat.openai.com\", \"huggingface\", \"llama\", \"llm\", \"mistral\",\r\n\t\t\t\"groq\", \"moonshot\", \"notion ai\", \"you.com\", \"writesonic\", \"phind\", \"tabnine\", \"codewhisperer\", \"replika\", \"deepai\",\r\n\t\t\t\"character.ai\", \"codeium\", \"deepmind\", \"tome.app\", \"shortlyai\", \"copy.ai\", \"inferkit\", \"type.ai\", \"chatpdf\", \"upword\",\r\n\t\t\t\"ai21\", \"cohere\", \"wordtune\", \"scribe\", \"simplified\", \"writer.com\", \"peppertype\", \"frase\", \"anyword\", \"hypotenuse\",\r\n\t\t\t\"scalenut\", \"surferseo\", \"textcortex\", \"lex.page\", \"writecream\", \"rytr\", \"neuroflash\", \"lightpdf\", \"voicemaker\", \"suno\",\r\n\t\t\t\"heygen\", \"liên minh huyền thoại\", \"dota\", \"facebook\", \"zalo\", \"tiktok\", \"youtube\", \"riot\"\r\n\t\t};\r\n\t}\r\n\r\n\tpublic void Start()\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tisRunning = true;\r\n\t\t\tlistener = new TcpListener(IPAddress.Any, port);\r\n\t\t\tlistener.Start();\r\n\t\t\tAcceptConnectionsAsync();\r\n\t\t}\r\n\t\tcatch (Exception)\r\n\t\t{\r\n\t\t\tthrow;\r\n\t\t}\r\n\t}\r\n\r\n\tpublic void Stop()\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tisRunning = false;\r\n\t\t\tlistener?.Stop();\r\n\t\t}\r\n\t\tcatch (Exception)\r\n\t\t{\r\n\t\t}\r\n\t}\r\n\r\n\tprivate async Task AcceptConnectionsAsync()\r\n\t{\r\n\t\twhile (isRunning)\r\n\t\t{\r\n\t\t\ttry\r\n\t\t\t{\r\n\t\t\t\tTcpClient client = await listener.AcceptTcpClientAsync();\r\n\t\t\t\t_ = (IPEndPoint)client.Client.RemoteEndPoint;\r\n\t\t\t\tHandleClientAsync(client);\r\n\t\t\t}\r\n\t\t\tcatch (Exception)\r\n\t\t\t{\r\n\t\t\t\tif (!isRunning)\r\n\t\t\t\t{\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tprivate async Task HandleClientAsync(TcpClient client)\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tusing (client)\r\n\t\t\t{\r\n\t\t\t\tusing NetworkStream stream = client.GetStream();\r\n\t\t\t\tHttpRequest request = await ReadHttpRequestAsync(stream);\r\n\t\t\t\tif (request == null)\r\n\t\t\t\t{\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t\tvar (shouldBlock, blockedKeyword) = await CheckViolate($\"{request.Method} {request.Url} {request.Host}\");\r\n\t\t\t\tif (shouldBlock)\r\n\t\t\t\t{\r\n\t\t\t\t\tawait SendBlockedResponseAsync(stream, blockedKeyword);\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t\tif (IsAIService(request.Url))\r\n\t\t\t\t{\r\n\t\t\t\t}\r\n\t\t\t\tif (!(request.Method.ToUpper() == \"CONNECT\"))\r\n\t\t\t\t{\r\n\t\t\t\t\tawait SendResponseAsync(stream, await ForwardRequestAsync(request));\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t\t(bool shouldBlock, string blockedKeyword) tuple2 = await CheckViolate(\"CONNECT \" + request.Url);\r\n\t\t\t\tvar (shouldBlockConnect, _) = tuple2;\r\n\t\t\t\t_ = tuple2.blockedKeyword;\r\n\t\t\t\tif (shouldBlockConnect)\r\n\t\t\t\t{\r\n\t\t\t\t\tstring errorResponse = \"HTTP/1.1 403 Forbidden\\r\\nConnection: close\\r\\n\\r\\n\";\r\n\t\t\t\t\tbyte[] responseBytes = Encoding.ASCII.GetBytes(errorResponse);\r\n\t\t\t\t\tawait stream.WriteAsync(responseBytes, 0, responseBytes.Length);\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t\tawait HandleConnectMethodAsync(stream, request);\r\n\t\t\t}\r\n\t\t}\r\n\t\tcatch (Exception)\r\n\t\t{\r\n\t\t}\r\n\t}\r\n\r\n\tprivate async Task HandleConnectMethodAsync(NetworkStream clientStream, HttpRequest request)\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tstring[] hostParts = request.Url.Split(':');\r\n\t\t\tstring host = hostParts[0];\r\n\t\t\tint port = ((hostParts.Length > 1) ? int.Parse(hostParts[1]) : 443);\r\n\t\t\ttry\r\n\t\t\t{\r\n\t\t\t\tusing TcpClient targetClient = new TcpClient();\r\n\t\t\t\tawait targetClient.ConnectAsync(host, port);\r\n\t\t\t\tstring successResponse = \"HTTP/1.1 200 Connection Established\\r\\n\\r\\n\";\r\n\t\t\t\tbyte[] responseBytes = Encoding.ASCII.GetBytes(successResponse);\r\n\t\t\t\tawait clientStream.WriteAsync(responseBytes, 0, responseBytes.Length);\r\n\t\t\t\tusing NetworkStream targetStream = targetClient.GetStream();\r\n\t\t\t\tTask task1 = TunnelDataAsync(clientStream, targetStream, \"Client → Target\");\r\n\t\t\t\tTask task2 = TunnelDataAsync(targetStream, clientStream, \"Target → Client\");\r\n\t\t\t\tawait Task.WhenAll(task1, task2);\r\n\t\t\t}\r\n\t\t\tcatch (Exception)\r\n\t\t\t{\r\n\t\t\t\tstring errorResponse = \"HTTP/1.1 502 Bad Gateway\\r\\n\\r\\n\";\r\n\t\t\t\tbyte[] responseBytes2 = Encoding.ASCII.GetBytes(errorResponse);\r\n\t\t\t\tawait clientStream.WriteAsync(responseBytes2, 0, responseBytes2.Length);\r\n\t\t\t}\r\n\t\t}\r\n\t\tcatch (Exception)\r\n\t\t{\r\n\t\t}\r\n\t}\r\n\r\n\tprivate async Task TunnelDataAsync(NetworkStream from, NetworkStream to, string direction)\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tbyte[] buffer = new byte[4096];\r\n\t\t\twhile (true)\r\n\t\t\t{\r\n\t\t\t\tint num;\r\n\t\t\t\tint bytesRead = (num = await from.ReadAsync(buffer, 0, buffer.Length));\r\n\t\t\t\tif (num <= 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\tawait to.WriteAsync(buffer, 0, bytesRead);\r\n\t\t\t}\r\n\t\t}\r\n\t\tcatch (Exception)\r\n\t\t{\r\n\t\t}\r\n\t}\r\n\r\n\tprivate async Task<HttpRequest> ReadHttpRequestAsync(NetworkStream stream)\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tbyte[] buffer = new byte[4096];\r\n\t\t\tStringBuilder requestBuilder = new StringBuilder();\r\n\t\t\tstring chunk;\r\n\t\t\tdo\r\n\t\t\t{\r\n\t\t\t\tint bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);\r\n\t\t\t\tif (bytesRead == 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\tchunk = Encoding.ASCII.GetString(buffer, 0, bytesRead);\r\n\t\t\t\trequestBuilder.Append(chunk);\r\n\t\t\t}\r\n\t\t\twhile (!chunk.Contains(\"\\r\\n\\r\\n\"));\r\n\t\t\tstring requestText = requestBuilder.ToString();\r\n\t\t\treturn ParseHttpRequest(requestText);\r\n\t\t}\r\n\t\tcatch (Exception)\r\n\t\t{\r\n\t\t\treturn null;\r\n\t\t}\r\n\t}\r\n\r\n\tprivate HttpRequest ParseHttpRequest(string requestText)\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tstring[] array = requestText.Split('\\n');\r\n\t\t\tstring text = array[0];\r\n\t\t\tstring[] array2 = text.Split(' ');\r\n\t\t\tif (array2.Length >= 3)\r\n\t\t\t{\r\n\t\t\t\tstring method = array2[0];\r\n\t\t\t\tstring text2 = array2[1];\r\n\t\t\t\tstring text3 = ExtractHostFromHeaders(array);\r\n\t\t\t\treturn new HttpRequest\r\n\t\t\t\t{\r\n\t\t\t\t\tMethod = method,\r\n\t\t\t\t\tUrl = text2,\r\n\t\t\t\t\tHost = text3,\r\n\t\t\t\t\tFullUrl = text3 + text2,\r\n\t\t\t\t\tHeaders = array\r\n\t\t\t\t};\r\n\t\t\t}\r\n\t\t}\r\n\t\tcatch (Exception)\r\n\t\t{\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\r\n\tprivate string ExtractHostFromHeaders(string[] headers)\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tforeach (string text in headers)\r\n\t\t\t{\r\n\t\t\t\tif (text.StartsWith(\"Host:\", StringComparison.OrdinalIgnoreCase))\r\n\t\t\t\t{\r\n\t\t\t\t\treturn text.Substring(5).Trim();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tcatch (Exception)\r\n\t\t{\r\n\t\t}\r\n\t\treturn \"localhost\";\r\n\t}\r\n\r\n\tprivate async Task<(bool shouldBlock, string blockedKeyword)> CheckViolate(string rawRequest)\r\n\t{\r\n\t\tforeach (string aiKeyword in aiKeyWords)\r\n\t\t{\r\n\t\t\tif (!rawRequest.Contains(aiKeyword))\r\n\t\t\t{\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tShowViolationNotificationWithCooldown(aiKeyword, rawRequest);\r\n\t\t\tif (ViolationTracker.CanSendReport(aiKeyword))\r\n\t\t\t{\r\n\t\t\t\tStudent student = mainWindow.student;\r\n\t\t\t\tif (student != null && student.StudentId > 0 && mainWindow.examId > 0)\r\n\t\t\t\t{\r\n\t\t\t\t\ttry\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tawait SendViolateReport(rawRequest, aiKeyword);\r\n\t\t\t\t\t\tViolationTracker.MarkReportSent(aiKeyword);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tcatch (Exception)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (blockUrl)\r\n\t\t\t{\r\n\t\t\t\treturn (shouldBlock: true, blockedKeyword: aiKeyword);\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\treturn (shouldBlock: false, blockedKeyword: null);\r\n\t}\r\n\r\n\tprivate async Task SendViolateReport(string rawRequest, string detectedKeyword)\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tstring apiEndpoint = violateHost + \"/exam/init-violate\";\r\n\t\t\tint studentId = mainWindow.student.StudentId;\r\n\t\t\tint examId = mainWindow.examId;\r\n\t\t\tbyte[] screenshotBytes = await GetScreenshotAsync();\r\n\t\t\tif (screenshotBytes != null)\r\n\t\t\t{\r\n\t\t\t\tstring boundary = \"----WebKitFormBoundary\" + Guid.NewGuid().ToString(\"N\");\r\n\t\t\t\tusing HttpClient httpClient = new HttpClient();\r\n\t\t\t\tMultipartFormDataContent multipartContent = new MultipartFormDataContent(boundary);\r\n\t\t\t\tStringContent studentIdContent = new StringContent(studentId.ToString());\r\n\t\t\t\tmultipartContent.Add(studentIdContent, \"studentId\");\r\n\t\t\t\tStringContent examIdContent = new StringContent(examId.ToString());\r\n\t\t\t\tmultipartContent.Add(examIdContent, \"examId\");\r\n\t\t\t\tStringContent descriptionContent = new StringContent(detectedKeyword);\r\n\t\t\t\tmultipartContent.Add(descriptionContent, \"violateDescription\");\r\n\t\t\t\tByteArrayContent imageContent = new ByteArrayContent(screenshotBytes);\r\n\t\t\t\timageContent.Headers.ContentType = new MediaTypeHeaderValue(\"image/jpeg\");\r\n\t\t\t\tmultipartContent.Add(imageContent, \"image\", \"screenshot.jpg\");\r\n\t\t\t\tawait httpClient.PostAsync(apiEndpoint, multipartContent);\r\n\t\t\t}\r\n\t\t}\r\n\t\tcatch (Exception)\r\n\t\t{\r\n\t\t\tthrow;\r\n\t\t}\r\n\t}\r\n\r\n\tprivate async Task<byte[]> GetScreenshotAsync()\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tusing Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);\r\n\t\t\tusing (Graphics graphics = Graphics.FromImage(bitmap))\r\n\t\t\t{\r\n\t\t\t\tgraphics.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size);\r\n\t\t\t}\r\n\t\t\tusing MemoryStream memoryStream = new MemoryStream();\r\n\t\t\tImageCodecInfo jpegEncoder = GetJpegEncoder();\r\n\t\t\tEncoderParameters encoderParams = new EncoderParameters(1);\r\n\t\t\tencoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 90L);\r\n\t\t\tbitmap.Save(memoryStream, jpegEncoder, encoderParams);\r\n\t\t\treturn memoryStream.ToArray();\r\n\t\t}\r\n\t\tcatch (Exception)\r\n\t\t{\r\n\t\t\treturn null;\r\n\t\t}\r\n\t}\r\n\r\n\tprivate ImageCodecInfo GetJpegEncoder()\r\n\t{\r\n\t\tImageCodecInfo[] imageDecoders = ImageCodecInfo.GetImageDecoders();\r\n\t\tImageCodecInfo[] array = imageDecoders;\r\n\t\tforeach (ImageCodecInfo imageCodecInfo in array)\r\n\t\t{\r\n\t\t\tif (imageCodecInfo.FormatID == ImageFormat.Jpeg.Guid)\r\n\t\t\t{\r\n\t\t\t\treturn imageCodecInfo;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\r\n\tpublic async Task ReloadKeywordsAsync()\r\n\t{\r\n\t\tawait LoadKeywordsFromApiAsync();\r\n\t}\r\n\r\n\tpublic List<string> GetKeywords()\r\n\t{\r\n\t\treturn new List<string>(aiKeyWords);\r\n\t}\r\n\r\n\tprivate void ShowViolationNotificationWithCooldown(string detectedKeyword, string rawRequest)\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tif (IsNotificationAllowed(detectedKeyword))\r\n\t\t\t{\r\n\t\t\t\tstring text = $\"\\ud83d\\udea8 CẢNH BÁO VI PHẠM AI / LÀM VIỆC RIÊNG!\\n\\nHệ thống đã phát hiện bạn đang truy cập:\\n• {detectedKeyword}\\n\\nĐây là một công cụ AI không được phép sử dụng trong kỳ thi.\\nVui lòng tập trung vào làm bài thi / học tập!\";\r\n\t\t\t\tUpdateLastNotificationTime(detectedKeyword);\r\n\t\t\t}\r\n\t\t}\r\n\t\tcatch (Exception)\r\n\t\t{\r\n\t\t}\r\n\t}\r\n\r\n\tprivate bool IsNotificationAllowed(string keyword)\r\n\t{\r\n\t\tif (!lastNotificationTime.ContainsKey(keyword))\r\n\t\t{\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\tDateTime dateTime = lastNotificationTime[keyword];\r\n\t\treturn (DateTime.Now - dateTime).TotalSeconds >= 120.0;\r\n\t}\r\n\r\n\tprivate void UpdateLastNotificationTime(string keyword)\r\n\t{\r\n\t\tlastNotificationTime[keyword] = DateTime.Now;\r\n\t}\r\n\r\n\tprivate bool IsAIService(string url)\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tstring text = url;\r\n\t\t\tint num = url.IndexOf(':');\r\n\t\t\tif (num > 0)\r\n\t\t\t{\r\n\t\t\t\ttext = url.Substring(0, num);\r\n\t\t\t}\r\n\t\t\tstring text2 = text.ToLower();\r\n\t\t\tforeach (string aiKeyWord in aiKeyWords)\r\n\t\t\t{\r\n\t\t\t\tif (text2.Contains(aiKeyWord.ToLower()))\r\n\t\t\t\t{\r\n\t\t\t\t\treturn true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tcatch (Exception)\r\n\t\t{\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\r\n\tprivate async Task<HttpResponse> ForwardRequestAsync(HttpRequest request)\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tHttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(request.FullUrl);\r\n\t\t\thttpRequest.Method = request.Method;\r\n\t\t\tstring[] headers = request.Headers;\r\n\t\t\tforeach (string header in headers)\r\n\t\t\t{\r\n\t\t\t\tif (header.StartsWith(\"Host:\", StringComparison.OrdinalIgnoreCase) || header.StartsWith(\"Content-Length:\", StringComparison.OrdinalIgnoreCase))\r\n\t\t\t\t{\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t\tint colonIndex = header.IndexOf(':');\r\n\t\t\t\tif (colonIndex <= 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t\tstring name = header.Substring(0, colonIndex).Trim();\r\n\t\t\t\tstring value = header.Substring(colonIndex + 1).Trim();\r\n\t\t\t\tif (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value))\r\n\t\t\t\t{\r\n\t\t\t\t\ttry\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\thttpRequest.Headers.Add(name, value);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tcatch\r\n\t\t\t\t\t{\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tusing HttpWebResponse response = (HttpWebResponse)(await httpRequest.GetResponseAsync());\r\n\t\t\tusing Stream responseStream = response.GetResponseStream();\r\n\t\t\tStringBuilder responseBuilder = new StringBuilder();\r\n\t\t\tStringBuilder stringBuilder = responseBuilder;\r\n\t\t\tStringBuilder stringBuilder2 = stringBuilder;\r\n\t\t\tStringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(7, 3, stringBuilder);\r\n\t\t\thandler.AppendLiteral(\"HTTP/\");\r\n\t\t\thandler.AppendFormatted(response.ProtocolVersion);\r\n\t\t\thandler.AppendLiteral(\" \");\r\n\t\t\thandler.AppendFormatted((int)response.StatusCode);\r\n\t\t\thandler.AppendLiteral(\" \");\r\n\t\t\thandler.AppendFormatted(response.StatusDescription);\r\n\t\t\tstringBuilder2.AppendLine(ref handler);\r\n\t\t\tstring[] allKeys = response.Headers.AllKeys;\r\n\t\t\tforeach (string headerName in allKeys)\r\n\t\t\t{\r\n\t\t\t\tstring headerValue = response.Headers[headerName];\r\n\t\t\t\tstringBuilder = responseBuilder;\r\n\t\t\t\tStringBuilder stringBuilder3 = stringBuilder;\r\n\t\t\t\thandler = new StringBuilder.AppendInterpolatedStringHandler(2, 2, stringBuilder);\r\n\t\t\t\thandler.AppendFormatted(headerName);\r\n\t\t\t\thandler.AppendLiteral(\": \");\r\n\t\t\t\thandler.AppendFormatted(headerValue);\r\n\t\t\t\tstringBuilder3.AppendLine(ref handler);\r\n\t\t\t}\r\n\t\t\tresponseBuilder.AppendLine();\r\n\t\t\tif (responseStream != null)\r\n\t\t\t{\r\n\t\t\t\tbyte[] buffer = new byte[4096];\r\n\t\t\t\twhile (true)\r\n\t\t\t\t{\r\n\t\t\t\t\tint num;\r\n\t\t\t\t\tint bytesRead = (num = await responseStream.ReadAsync(buffer, 0, buffer.Length));\r\n\t\t\t\t\tif (num <= 0)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tresponseBuilder.Append(Encoding.UTF8.GetString(buffer, 0, bytesRead));\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn new HttpResponse\r\n\t\t\t{\r\n\t\t\t\tStatusCode = (int)response.StatusCode,\r\n\t\t\t\tHeaders = response.Headers,\r\n\t\t\t\tBody = responseBuilder.ToString()\r\n\t\t\t};\r\n\t\t}\r\n\t\tcatch (Exception ex)\r\n\t\t{\r\n\t\t\tException ex2 = ex;\r\n\t\t\treturn new HttpResponse\r\n\t\t\t{\r\n\t\t\t\tStatusCode = 500,\r\n\t\t\t\tBody = \"Error: \" + ex2.Message\r\n\t\t\t};\r\n\t\t}\r\n\t}\r\n\r\n\tprivate async Task SendBlockedResponseAsync(NetworkStream stream, string blockedKeyword)\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tstring blockedHtml = \"\\r\\n<!DOCTYPE html>\\r\\n<html>\\r\\n<head>\\r\\n <meta charset='UTF-8'>\\r\\n <title>Truy cập bị chặn</title>\\r\\n <style>\\r\\n body { \\r\\n font-family: Arial, sans-serif; \\r\\n text-align: center; \\r\\n background-color: #f8f9fa;\\r\\n margin: 0;\\r\\n padding: 50px;\\r\\n }\\r\\n .warning-box {\\r\\n background-color: #fff3cd;\\r\\n border: 2px solid #ffc107;\\r\\n border-radius: 10px;\\r\\n padding: 30px;\\r\\n max-width: 600px;\\r\\n margin: 0 auto;\\r\\n box-shadow: 0 4px 6px rgba(0,0,0,0.1);\\r\\n }\\r\\n .warning-icon {\\r\\n font-size: 48px;\\r\\n color: #dc3545;\\r\\n margin-bottom: 20px;\\r\\n }\\r\\n h1 {\\r\\n color: #dc3545;\\r\\n margin-bottom: 20px;\\r\\n }\\r\\n .keyword {\\r\\n background-color: #f8d7da;\\r\\n color: #721c24;\\r\\n padding: 5px 10px;\\r\\n border-radius: 5px;\\r\\n font-weight: bold;\\r\\n }\\r\\n </style>\\r\\n</head>\\r\\n<body>\\r\\n <div class='warning-box'>\\r\\n <div class='warning-icon'>\\ud83d\\udeab</div>\\r\\n <h1>TRUY CẬP BỊ CHẶN</h1>\\r\\n <p>Hệ thống đã phát hiện bạn đang cố gắng truy cập:</p>\\r\\n <p class='keyword'>\" + blockedKeyword + \"</p>\\r\\n <p><strong>Đây là một trang web/dịch vụ không được phép sử dụng trong kỳ thi.</strong></p>\\r\\n <p>Vui lòng tập trung vào làm bài thi và không truy cập các trang web không liên quan!</p>\\r\\n <hr>\\r\\n <p><em>Rikkei Education Service - Hệ thống giám sát thi trực tuyến</em></p>\\r\\n </div>\\r\\n</body>\\r\\n</html>\";\r\n\t\t\tstring responseText = \"HTTP/1.1 403 Forbidden\\r\\n\";\r\n\t\t\tresponseText += \"Content-Type: text/html; charset=UTF-8\\r\\n\";\r\n\t\t\tresponseText += $\"Content-Length: {Encoding.UTF8.GetByteCount(blockedHtml)}\\r\\n\";\r\n\t\t\tresponseText += \"Connection: close\\r\\n\";\r\n\t\t\tresponseText += \"\\r\\n\";\r\n\t\t\tresponseText += blockedHtml;\r\n\t\t\tbyte[] responseBytes = Encoding.UTF8.GetBytes(responseText);\r\n\t\t\tawait stream.WriteAsync(responseBytes, 0, responseBytes.Length);\r\n\t\t}\r\n\t\tcatch (Exception)\r\n\t\t{\r\n\t\t}\r\n\t}\r\n\r\n\tprivate async Task SendResponseAsync(NetworkStream stream, HttpResponse response)\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tstring responseText = $\"HTTP/1.1 {response.StatusCode} OK\\r\\n\";\r\n\t\t\tresponseText += \"Content-Type: text/html\\r\\n\";\r\n\t\t\tresponseText += $\"Content-Length: {response.Body?.Length ?? 0}\\r\\n\";\r\n\t\t\tresponseText += \"\\r\\n\";\r\n\t\t\tresponseText += response.Body;\r\n\t\t\tbyte[] responseBytes = Encoding.UTF8.GetBytes(responseText);\r\n\t\t\tawait stream.WriteAsync(responseBytes, 0, responseBytes.Length);\r\n\t\t}\r\n\t\tcatch (Exception)\r\n\t\t{\r\n\t\t}\r\n\t}\r\n}\r\n",
5
- "language": "javascript",
6
  "createdAt": 1758178379912,
7
- "updatedAt": 1758178379912
8
  }
 
2
  "id": "af7dc466-f77f-42ba-b353-b9722675764b",
3
  "title": "HttpProxyServer.cs",
4
  "content": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Drawing;\r\nusing System.Drawing.Imaging;\r\nusing System.IO;\r\nusing System.Net;\r\nusing System.Net.Http;\r\nusing System.Net.Http.Headers;\r\nusing System.Net.Sockets;\r\nusing System.Text;\r\nusing System.Text.Json;\r\nusing System.Threading.Tasks;\r\nusing System.Windows.Forms;\r\n\r\nnamespace rikkei_education_service;\r\n\r\npublic class HttpProxyServer\r\n{\r\n\tprivate MainWindow mainWindow;\r\n\r\n\tprivate TcpListener listener;\r\n\r\n\tpublic bool isRunning = false;\r\n\r\n\tprivate int port = 8888;\r\n\r\n\tprivate string violateHost = Environment.GetEnvironmentVariable(\"VIOLATE_HOST\");\r\n\r\n\tpublic bool blockUrl = false;\r\n\r\n\tprivate readonly Dictionary<string, DateTime> lastNotificationTime = new Dictionary<string, DateTime>();\r\n\r\n\tprivate const int NOTIFICATION_COOLDOWN_SECONDS = 120;\r\n\r\n\tprivate readonly string apiEndpoint = \"https://api.raia.edu.vn/api/rikkei-education-app/find-ai-detect-data\";\r\n\r\n\tprivate readonly HttpClient httpClient = new HttpClient();\r\n\r\n\tprivate List<string> aiKeyWords = new List<string>();\r\n\r\n\tpublic HttpProxyServer(MainWindow mainWindow)\r\n\t{\r\n\t\tthis.mainWindow = mainWindow;\r\n\t\tLoadKeywordsFromApiAsync();\r\n\t}\r\n\r\n\tprivate async Task LoadKeywordsFromApiAsync()\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tHttpResponseMessage response = await httpClient.GetAsync(apiEndpoint);\r\n\t\t\tif (response.IsSuccessStatusCode)\r\n\t\t\t{\r\n\t\t\t\tAiDetectApiResponse apiResponse = JsonSerializer.Deserialize<AiDetectApiResponse>(await response.Content.ReadAsStringAsync());\r\n\t\t\t\tif (apiResponse?.data != null)\r\n\t\t\t\t{\r\n\t\t\t\t\taiKeyWords.Clear();\r\n\t\t\t\t\tforeach (AiDetectData item in apiResponse.data)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif (item.status && !string.IsNullOrEmpty(item.keyword))\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\taiKeyWords.Add(item.keyword);\r\n\t\t\t\t\t\t\tif (!string.IsNullOrEmpty(item.serverIp) && !item.serverIp.Equals(item.keyword, StringComparison.OrdinalIgnoreCase))\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\taiKeyWords.Add(item.serverIp);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tLoadFallbackKeywords();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tLoadFallbackKeywords();\r\n\t\t\t}\r\n\t\t}\r\n\t\tcatch (Exception)\r\n\t\t{\r\n\t\t\tLoadFallbackKeywords();\r\n\t\t}\r\n\t}\r\n\r\n\tprivate void LoadFallbackKeywords()\r\n\t{\r\n\t\taiKeyWords = new List<string>\r\n\t\t{\r\n\t\t\t\"openai\", \"chat.com\", \"bard\", \"claude\", \"perplexity\", \"poe\", \"copilot\", \"quillbot\", \"grammarly\", \"jasper\",\r\n\t\t\t\"lm\", \"gpt\", \"cursor\", \"gemini\", \"chatgpt\", \"chat.openai.com\", \"huggingface\", \"llama\", \"llm\", \"mistral\",\r\n\t\t\t\"groq\", \"moonshot\", \"notion ai\", \"you.com\", \"writesonic\", \"phind\", \"tabnine\", \"codewhisperer\", \"replika\", \"deepai\",\r\n\t\t\t\"character.ai\", \"codeium\", \"deepmind\", \"tome.app\", \"shortlyai\", \"copy.ai\", \"inferkit\", \"type.ai\", \"chatpdf\", \"upword\",\r\n\t\t\t\"ai21\", \"cohere\", \"wordtune\", \"scribe\", \"simplified\", \"writer.com\", \"peppertype\", \"frase\", \"anyword\", \"hypotenuse\",\r\n\t\t\t\"scalenut\", \"surferseo\", \"textcortex\", \"lex.page\", \"writecream\", \"rytr\", \"neuroflash\", \"lightpdf\", \"voicemaker\", \"suno\",\r\n\t\t\t\"heygen\", \"liên minh huyền thoại\", \"dota\", \"facebook\", \"zalo\", \"tiktok\", \"youtube\", \"riot\"\r\n\t\t};\r\n\t}\r\n\r\n\tpublic void Start()\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tisRunning = true;\r\n\t\t\tlistener = new TcpListener(IPAddress.Any, port);\r\n\t\t\tlistener.Start();\r\n\t\t\tAcceptConnectionsAsync();\r\n\t\t}\r\n\t\tcatch (Exception)\r\n\t\t{\r\n\t\t\tthrow;\r\n\t\t}\r\n\t}\r\n\r\n\tpublic void Stop()\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tisRunning = false;\r\n\t\t\tlistener?.Stop();\r\n\t\t}\r\n\t\tcatch (Exception)\r\n\t\t{\r\n\t\t}\r\n\t}\r\n\r\n\tprivate async Task AcceptConnectionsAsync()\r\n\t{\r\n\t\twhile (isRunning)\r\n\t\t{\r\n\t\t\ttry\r\n\t\t\t{\r\n\t\t\t\tTcpClient client = await listener.AcceptTcpClientAsync();\r\n\t\t\t\t_ = (IPEndPoint)client.Client.RemoteEndPoint;\r\n\t\t\t\tHandleClientAsync(client);\r\n\t\t\t}\r\n\t\t\tcatch (Exception)\r\n\t\t\t{\r\n\t\t\t\tif (!isRunning)\r\n\t\t\t\t{\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tprivate async Task HandleClientAsync(TcpClient client)\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tusing (client)\r\n\t\t\t{\r\n\t\t\t\tusing NetworkStream stream = client.GetStream();\r\n\t\t\t\tHttpRequest request = await ReadHttpRequestAsync(stream);\r\n\t\t\t\tif (request == null)\r\n\t\t\t\t{\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t\tvar (shouldBlock, blockedKeyword) = await CheckViolate($\"{request.Method} {request.Url} {request.Host}\");\r\n\t\t\t\tif (shouldBlock)\r\n\t\t\t\t{\r\n\t\t\t\t\tawait SendBlockedResponseAsync(stream, blockedKeyword);\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t\tif (IsAIService(request.Url))\r\n\t\t\t\t{\r\n\t\t\t\t}\r\n\t\t\t\tif (!(request.Method.ToUpper() == \"CONNECT\"))\r\n\t\t\t\t{\r\n\t\t\t\t\tawait SendResponseAsync(stream, await ForwardRequestAsync(request));\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t\t(bool shouldBlock, string blockedKeyword) tuple2 = await CheckViolate(\"CONNECT \" + request.Url);\r\n\t\t\t\tvar (shouldBlockConnect, _) = tuple2;\r\n\t\t\t\t_ = tuple2.blockedKeyword;\r\n\t\t\t\tif (shouldBlockConnect)\r\n\t\t\t\t{\r\n\t\t\t\t\tstring errorResponse = \"HTTP/1.1 403 Forbidden\\r\\nConnection: close\\r\\n\\r\\n\";\r\n\t\t\t\t\tbyte[] responseBytes = Encoding.ASCII.GetBytes(errorResponse);\r\n\t\t\t\t\tawait stream.WriteAsync(responseBytes, 0, responseBytes.Length);\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t\tawait HandleConnectMethodAsync(stream, request);\r\n\t\t\t}\r\n\t\t}\r\n\t\tcatch (Exception)\r\n\t\t{\r\n\t\t}\r\n\t}\r\n\r\n\tprivate async Task HandleConnectMethodAsync(NetworkStream clientStream, HttpRequest request)\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tstring[] hostParts = request.Url.Split(':');\r\n\t\t\tstring host = hostParts[0];\r\n\t\t\tint port = ((hostParts.Length > 1) ? int.Parse(hostParts[1]) : 443);\r\n\t\t\ttry\r\n\t\t\t{\r\n\t\t\t\tusing TcpClient targetClient = new TcpClient();\r\n\t\t\t\tawait targetClient.ConnectAsync(host, port);\r\n\t\t\t\tstring successResponse = \"HTTP/1.1 200 Connection Established\\r\\n\\r\\n\";\r\n\t\t\t\tbyte[] responseBytes = Encoding.ASCII.GetBytes(successResponse);\r\n\t\t\t\tawait clientStream.WriteAsync(responseBytes, 0, responseBytes.Length);\r\n\t\t\t\tusing NetworkStream targetStream = targetClient.GetStream();\r\n\t\t\t\tTask task1 = TunnelDataAsync(clientStream, targetStream, \"Client → Target\");\r\n\t\t\t\tTask task2 = TunnelDataAsync(targetStream, clientStream, \"Target → Client\");\r\n\t\t\t\tawait Task.WhenAll(task1, task2);\r\n\t\t\t}\r\n\t\t\tcatch (Exception)\r\n\t\t\t{\r\n\t\t\t\tstring errorResponse = \"HTTP/1.1 502 Bad Gateway\\r\\n\\r\\n\";\r\n\t\t\t\tbyte[] responseBytes2 = Encoding.ASCII.GetBytes(errorResponse);\r\n\t\t\t\tawait clientStream.WriteAsync(responseBytes2, 0, responseBytes2.Length);\r\n\t\t\t}\r\n\t\t}\r\n\t\tcatch (Exception)\r\n\t\t{\r\n\t\t}\r\n\t}\r\n\r\n\tprivate async Task TunnelDataAsync(NetworkStream from, NetworkStream to, string direction)\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tbyte[] buffer = new byte[4096];\r\n\t\t\twhile (true)\r\n\t\t\t{\r\n\t\t\t\tint num;\r\n\t\t\t\tint bytesRead = (num = await from.ReadAsync(buffer, 0, buffer.Length));\r\n\t\t\t\tif (num <= 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\tawait to.WriteAsync(buffer, 0, bytesRead);\r\n\t\t\t}\r\n\t\t}\r\n\t\tcatch (Exception)\r\n\t\t{\r\n\t\t}\r\n\t}\r\n\r\n\tprivate async Task<HttpRequest> ReadHttpRequestAsync(NetworkStream stream)\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tbyte[] buffer = new byte[4096];\r\n\t\t\tStringBuilder requestBuilder = new StringBuilder();\r\n\t\t\tstring chunk;\r\n\t\t\tdo\r\n\t\t\t{\r\n\t\t\t\tint bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);\r\n\t\t\t\tif (bytesRead == 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\tchunk = Encoding.ASCII.GetString(buffer, 0, bytesRead);\r\n\t\t\t\trequestBuilder.Append(chunk);\r\n\t\t\t}\r\n\t\t\twhile (!chunk.Contains(\"\\r\\n\\r\\n\"));\r\n\t\t\tstring requestText = requestBuilder.ToString();\r\n\t\t\treturn ParseHttpRequest(requestText);\r\n\t\t}\r\n\t\tcatch (Exception)\r\n\t\t{\r\n\t\t\treturn null;\r\n\t\t}\r\n\t}\r\n\r\n\tprivate HttpRequest ParseHttpRequest(string requestText)\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tstring[] array = requestText.Split('\\n');\r\n\t\t\tstring text = array[0];\r\n\t\t\tstring[] array2 = text.Split(' ');\r\n\t\t\tif (array2.Length >= 3)\r\n\t\t\t{\r\n\t\t\t\tstring method = array2[0];\r\n\t\t\t\tstring text2 = array2[1];\r\n\t\t\t\tstring text3 = ExtractHostFromHeaders(array);\r\n\t\t\t\treturn new HttpRequest\r\n\t\t\t\t{\r\n\t\t\t\t\tMethod = method,\r\n\t\t\t\t\tUrl = text2,\r\n\t\t\t\t\tHost = text3,\r\n\t\t\t\t\tFullUrl = text3 + text2,\r\n\t\t\t\t\tHeaders = array\r\n\t\t\t\t};\r\n\t\t\t}\r\n\t\t}\r\n\t\tcatch (Exception)\r\n\t\t{\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\r\n\tprivate string ExtractHostFromHeaders(string[] headers)\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tforeach (string text in headers)\r\n\t\t\t{\r\n\t\t\t\tif (text.StartsWith(\"Host:\", StringComparison.OrdinalIgnoreCase))\r\n\t\t\t\t{\r\n\t\t\t\t\treturn text.Substring(5).Trim();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tcatch (Exception)\r\n\t\t{\r\n\t\t}\r\n\t\treturn \"localhost\";\r\n\t}\r\n\r\n\tprivate async Task<(bool shouldBlock, string blockedKeyword)> CheckViolate(string rawRequest)\r\n\t{\r\n\t\tforeach (string aiKeyword in aiKeyWords)\r\n\t\t{\r\n\t\t\tif (!rawRequest.Contains(aiKeyword))\r\n\t\t\t{\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tShowViolationNotificationWithCooldown(aiKeyword, rawRequest);\r\n\t\t\tif (ViolationTracker.CanSendReport(aiKeyword))\r\n\t\t\t{\r\n\t\t\t\tStudent student = mainWindow.student;\r\n\t\t\t\tif (student != null && student.StudentId > 0 && mainWindow.examId > 0)\r\n\t\t\t\t{\r\n\t\t\t\t\ttry\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tawait SendViolateReport(rawRequest, aiKeyword);\r\n\t\t\t\t\t\tViolationTracker.MarkReportSent(aiKeyword);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tcatch (Exception)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (blockUrl)\r\n\t\t\t{\r\n\t\t\t\treturn (shouldBlock: true, blockedKeyword: aiKeyword);\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\treturn (shouldBlock: false, blockedKeyword: null);\r\n\t}\r\n\r\n\tprivate async Task SendViolateReport(string rawRequest, string detectedKeyword)\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tstring apiEndpoint = violateHost + \"/exam/init-violate\";\r\n\t\t\tint studentId = mainWindow.student.StudentId;\r\n\t\t\tint examId = mainWindow.examId;\r\n\t\t\tbyte[] screenshotBytes = await GetScreenshotAsync();\r\n\t\t\tif (screenshotBytes != null)\r\n\t\t\t{\r\n\t\t\t\tstring boundary = \"----WebKitFormBoundary\" + Guid.NewGuid().ToString(\"N\");\r\n\t\t\t\tusing HttpClient httpClient = new HttpClient();\r\n\t\t\t\tMultipartFormDataContent multipartContent = new MultipartFormDataContent(boundary);\r\n\t\t\t\tStringContent studentIdContent = new StringContent(studentId.ToString());\r\n\t\t\t\tmultipartContent.Add(studentIdContent, \"studentId\");\r\n\t\t\t\tStringContent examIdContent = new StringContent(examId.ToString());\r\n\t\t\t\tmultipartContent.Add(examIdContent, \"examId\");\r\n\t\t\t\tStringContent descriptionContent = new StringContent(detectedKeyword);\r\n\t\t\t\tmultipartContent.Add(descriptionContent, \"violateDescription\");\r\n\t\t\t\tByteArrayContent imageContent = new ByteArrayContent(screenshotBytes);\r\n\t\t\t\timageContent.Headers.ContentType = new MediaTypeHeaderValue(\"image/jpeg\");\r\n\t\t\t\tmultipartContent.Add(imageContent, \"image\", \"screenshot.jpg\");\r\n\t\t\t\tawait httpClient.PostAsync(apiEndpoint, multipartContent);\r\n\t\t\t}\r\n\t\t}\r\n\t\tcatch (Exception)\r\n\t\t{\r\n\t\t\tthrow;\r\n\t\t}\r\n\t}\r\n\r\n\tprivate async Task<byte[]> GetScreenshotAsync()\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tusing Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);\r\n\t\t\tusing (Graphics graphics = Graphics.FromImage(bitmap))\r\n\t\t\t{\r\n\t\t\t\tgraphics.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size);\r\n\t\t\t}\r\n\t\t\tusing MemoryStream memoryStream = new MemoryStream();\r\n\t\t\tImageCodecInfo jpegEncoder = GetJpegEncoder();\r\n\t\t\tEncoderParameters encoderParams = new EncoderParameters(1);\r\n\t\t\tencoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 90L);\r\n\t\t\tbitmap.Save(memoryStream, jpegEncoder, encoderParams);\r\n\t\t\treturn memoryStream.ToArray();\r\n\t\t}\r\n\t\tcatch (Exception)\r\n\t\t{\r\n\t\t\treturn null;\r\n\t\t}\r\n\t}\r\n\r\n\tprivate ImageCodecInfo GetJpegEncoder()\r\n\t{\r\n\t\tImageCodecInfo[] imageDecoders = ImageCodecInfo.GetImageDecoders();\r\n\t\tImageCodecInfo[] array = imageDecoders;\r\n\t\tforeach (ImageCodecInfo imageCodecInfo in array)\r\n\t\t{\r\n\t\t\tif (imageCodecInfo.FormatID == ImageFormat.Jpeg.Guid)\r\n\t\t\t{\r\n\t\t\t\treturn imageCodecInfo;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\r\n\tpublic async Task ReloadKeywordsAsync()\r\n\t{\r\n\t\tawait LoadKeywordsFromApiAsync();\r\n\t}\r\n\r\n\tpublic List<string> GetKeywords()\r\n\t{\r\n\t\treturn new List<string>(aiKeyWords);\r\n\t}\r\n\r\n\tprivate void ShowViolationNotificationWithCooldown(string detectedKeyword, string rawRequest)\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tif (IsNotificationAllowed(detectedKeyword))\r\n\t\t\t{\r\n\t\t\t\tstring text = $\"\\ud83d\\udea8 CẢNH BÁO VI PHẠM AI / LÀM VIỆC RIÊNG!\\n\\nHệ thống đã phát hiện bạn đang truy cập:\\n• {detectedKeyword}\\n\\nĐây là một công cụ AI không được phép sử dụng trong kỳ thi.\\nVui lòng tập trung vào làm bài thi / học tập!\";\r\n\t\t\t\tUpdateLastNotificationTime(detectedKeyword);\r\n\t\t\t}\r\n\t\t}\r\n\t\tcatch (Exception)\r\n\t\t{\r\n\t\t}\r\n\t}\r\n\r\n\tprivate bool IsNotificationAllowed(string keyword)\r\n\t{\r\n\t\tif (!lastNotificationTime.ContainsKey(keyword))\r\n\t\t{\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\tDateTime dateTime = lastNotificationTime[keyword];\r\n\t\treturn (DateTime.Now - dateTime).TotalSeconds >= 120.0;\r\n\t}\r\n\r\n\tprivate void UpdateLastNotificationTime(string keyword)\r\n\t{\r\n\t\tlastNotificationTime[keyword] = DateTime.Now;\r\n\t}\r\n\r\n\tprivate bool IsAIService(string url)\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tstring text = url;\r\n\t\t\tint num = url.IndexOf(':');\r\n\t\t\tif (num > 0)\r\n\t\t\t{\r\n\t\t\t\ttext = url.Substring(0, num);\r\n\t\t\t}\r\n\t\t\tstring text2 = text.ToLower();\r\n\t\t\tforeach (string aiKeyWord in aiKeyWords)\r\n\t\t\t{\r\n\t\t\t\tif (text2.Contains(aiKeyWord.ToLower()))\r\n\t\t\t\t{\r\n\t\t\t\t\treturn true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tcatch (Exception)\r\n\t\t{\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\r\n\tprivate async Task<HttpResponse> ForwardRequestAsync(HttpRequest request)\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tHttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(request.FullUrl);\r\n\t\t\thttpRequest.Method = request.Method;\r\n\t\t\tstring[] headers = request.Headers;\r\n\t\t\tforeach (string header in headers)\r\n\t\t\t{\r\n\t\t\t\tif (header.StartsWith(\"Host:\", StringComparison.OrdinalIgnoreCase) || header.StartsWith(\"Content-Length:\", StringComparison.OrdinalIgnoreCase))\r\n\t\t\t\t{\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t\tint colonIndex = header.IndexOf(':');\r\n\t\t\t\tif (colonIndex <= 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t\tstring name = header.Substring(0, colonIndex).Trim();\r\n\t\t\t\tstring value = header.Substring(colonIndex + 1).Trim();\r\n\t\t\t\tif (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value))\r\n\t\t\t\t{\r\n\t\t\t\t\ttry\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\thttpRequest.Headers.Add(name, value);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tcatch\r\n\t\t\t\t\t{\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tusing HttpWebResponse response = (HttpWebResponse)(await httpRequest.GetResponseAsync());\r\n\t\t\tusing Stream responseStream = response.GetResponseStream();\r\n\t\t\tStringBuilder responseBuilder = new StringBuilder();\r\n\t\t\tStringBuilder stringBuilder = responseBuilder;\r\n\t\t\tStringBuilder stringBuilder2 = stringBuilder;\r\n\t\t\tStringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(7, 3, stringBuilder);\r\n\t\t\thandler.AppendLiteral(\"HTTP/\");\r\n\t\t\thandler.AppendFormatted(response.ProtocolVersion);\r\n\t\t\thandler.AppendLiteral(\" \");\r\n\t\t\thandler.AppendFormatted((int)response.StatusCode);\r\n\t\t\thandler.AppendLiteral(\" \");\r\n\t\t\thandler.AppendFormatted(response.StatusDescription);\r\n\t\t\tstringBuilder2.AppendLine(ref handler);\r\n\t\t\tstring[] allKeys = response.Headers.AllKeys;\r\n\t\t\tforeach (string headerName in allKeys)\r\n\t\t\t{\r\n\t\t\t\tstring headerValue = response.Headers[headerName];\r\n\t\t\t\tstringBuilder = responseBuilder;\r\n\t\t\t\tStringBuilder stringBuilder3 = stringBuilder;\r\n\t\t\t\thandler = new StringBuilder.AppendInterpolatedStringHandler(2, 2, stringBuilder);\r\n\t\t\t\thandler.AppendFormatted(headerName);\r\n\t\t\t\thandler.AppendLiteral(\": \");\r\n\t\t\t\thandler.AppendFormatted(headerValue);\r\n\t\t\t\tstringBuilder3.AppendLine(ref handler);\r\n\t\t\t}\r\n\t\t\tresponseBuilder.AppendLine();\r\n\t\t\tif (responseStream != null)\r\n\t\t\t{\r\n\t\t\t\tbyte[] buffer = new byte[4096];\r\n\t\t\t\twhile (true)\r\n\t\t\t\t{\r\n\t\t\t\t\tint num;\r\n\t\t\t\t\tint bytesRead = (num = await responseStream.ReadAsync(buffer, 0, buffer.Length));\r\n\t\t\t\t\tif (num <= 0)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tresponseBuilder.Append(Encoding.UTF8.GetString(buffer, 0, bytesRead));\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn new HttpResponse\r\n\t\t\t{\r\n\t\t\t\tStatusCode = (int)response.StatusCode,\r\n\t\t\t\tHeaders = response.Headers,\r\n\t\t\t\tBody = responseBuilder.ToString()\r\n\t\t\t};\r\n\t\t}\r\n\t\tcatch (Exception ex)\r\n\t\t{\r\n\t\t\tException ex2 = ex;\r\n\t\t\treturn new HttpResponse\r\n\t\t\t{\r\n\t\t\t\tStatusCode = 500,\r\n\t\t\t\tBody = \"Error: \" + ex2.Message\r\n\t\t\t};\r\n\t\t}\r\n\t}\r\n\r\n\tprivate async Task SendBlockedResponseAsync(NetworkStream stream, string blockedKeyword)\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tstring blockedHtml = \"\\r\\n<!DOCTYPE html>\\r\\n<html>\\r\\n<head>\\r\\n <meta charset='UTF-8'>\\r\\n <title>Truy cập bị chặn</title>\\r\\n <style>\\r\\n body { \\r\\n font-family: Arial, sans-serif; \\r\\n text-align: center; \\r\\n background-color: #f8f9fa;\\r\\n margin: 0;\\r\\n padding: 50px;\\r\\n }\\r\\n .warning-box {\\r\\n background-color: #fff3cd;\\r\\n border: 2px solid #ffc107;\\r\\n border-radius: 10px;\\r\\n padding: 30px;\\r\\n max-width: 600px;\\r\\n margin: 0 auto;\\r\\n box-shadow: 0 4px 6px rgba(0,0,0,0.1);\\r\\n }\\r\\n .warning-icon {\\r\\n font-size: 48px;\\r\\n color: #dc3545;\\r\\n margin-bottom: 20px;\\r\\n }\\r\\n h1 {\\r\\n color: #dc3545;\\r\\n margin-bottom: 20px;\\r\\n }\\r\\n .keyword {\\r\\n background-color: #f8d7da;\\r\\n color: #721c24;\\r\\n padding: 5px 10px;\\r\\n border-radius: 5px;\\r\\n font-weight: bold;\\r\\n }\\r\\n </style>\\r\\n</head>\\r\\n<body>\\r\\n <div class='warning-box'>\\r\\n <div class='warning-icon'>\\ud83d\\udeab</div>\\r\\n <h1>TRUY CẬP BỊ CHẶN</h1>\\r\\n <p>Hệ thống đã phát hiện bạn đang cố gắng truy cập:</p>\\r\\n <p class='keyword'>\" + blockedKeyword + \"</p>\\r\\n <p><strong>Đây là một trang web/dịch vụ không được phép sử dụng trong kỳ thi.</strong></p>\\r\\n <p>Vui lòng tập trung vào làm bài thi và không truy cập các trang web không liên quan!</p>\\r\\n <hr>\\r\\n <p><em>Rikkei Education Service - Hệ thống giám sát thi trực tuyến</em></p>\\r\\n </div>\\r\\n</body>\\r\\n</html>\";\r\n\t\t\tstring responseText = \"HTTP/1.1 403 Forbidden\\r\\n\";\r\n\t\t\tresponseText += \"Content-Type: text/html; charset=UTF-8\\r\\n\";\r\n\t\t\tresponseText += $\"Content-Length: {Encoding.UTF8.GetByteCount(blockedHtml)}\\r\\n\";\r\n\t\t\tresponseText += \"Connection: close\\r\\n\";\r\n\t\t\tresponseText += \"\\r\\n\";\r\n\t\t\tresponseText += blockedHtml;\r\n\t\t\tbyte[] responseBytes = Encoding.UTF8.GetBytes(responseText);\r\n\t\t\tawait stream.WriteAsync(responseBytes, 0, responseBytes.Length);\r\n\t\t}\r\n\t\tcatch (Exception)\r\n\t\t{\r\n\t\t}\r\n\t}\r\n\r\n\tprivate async Task SendResponseAsync(NetworkStream stream, HttpResponse response)\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tstring responseText = $\"HTTP/1.1 {response.StatusCode} OK\\r\\n\";\r\n\t\t\tresponseText += \"Content-Type: text/html\\r\\n\";\r\n\t\t\tresponseText += $\"Content-Length: {response.Body?.Length ?? 0}\\r\\n\";\r\n\t\t\tresponseText += \"\\r\\n\";\r\n\t\t\tresponseText += response.Body;\r\n\t\t\tbyte[] responseBytes = Encoding.UTF8.GetBytes(responseText);\r\n\t\t\tawait stream.WriteAsync(responseBytes, 0, responseBytes.Length);\r\n\t\t}\r\n\t\tcatch (Exception)\r\n\t\t{\r\n\t\t}\r\n\t}\r\n}\r\n",
5
+ "language": "csharp",
6
  "createdAt": 1758178379912,
7
+ "updatedAt": 1758178396255
8
  }