server.rs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. // This Source Code Form is subject to the terms of the Mozilla Public
  2. // License, v. 2.0. If a copy of the MPL was not distributed with this
  3. // file, You can obtain one at https://mozilla.org/MPL/2.0/.
  4. use crate::ipc::{IpcError, connect_to_greetd, handle_websocket};
  5. use axum::{
  6. Router,
  7. extract::ws::{WebSocket, WebSocketUpgrade},
  8. response::Html,
  9. routing::get,
  10. };
  11. use std::net::SocketAddr;
  12. use tokio::net::TcpListener;
  13. use tracing::{error, info};
  14. /// 启动 HTTP 服务器
  15. pub async fn run_server(port: u16) -> Result<(), IpcError> {
  16. let app = Router::new()
  17. .route("/", get(index_handler))
  18. .route("/ws", get(websocket_handler));
  19. let addr = SocketAddr::from(([127, 0, 0, 1], port));
  20. info!("正在绑定TCP监听端口: {}", addr);
  21. let listener = TcpListener::bind(addr).await.map_err(|e| {
  22. error!("无法绑定端口 {}: {}", port, e);
  23. IpcError::Protocol(e.to_string())
  24. })?;
  25. info!("服务器启动成功,监听端口: {}", port);
  26. axum::serve(listener, app.into_make_service())
  27. .await
  28. .map_err(|e| {
  29. error!("服务器运行错误: {}", e);
  30. IpcError::Protocol(e.to_string())
  31. })?;
  32. Ok(())
  33. }
  34. /// 处理首页请求
  35. async fn index_handler() -> Html<&'static str> {
  36. Html(INDEX_HTML)
  37. }
  38. /// 处理 WebSocket 升级请求
  39. async fn websocket_handler(ws: WebSocketUpgrade) -> impl axum::response::IntoResponse {
  40. ws.on_upgrade(handle_socket)
  41. }
  42. /// 处理 WebSocket 连接
  43. async fn handle_socket(socket: WebSocket) {
  44. // 连接到 greetd IPC
  45. match connect_to_greetd().await {
  46. Ok(ipc_conn) => {
  47. if let Err(e) = handle_websocket(socket, ipc_conn).await {
  48. error!("WebSocket 处理错误: {}", e);
  49. }
  50. }
  51. Err(e) => error!("无法连接到 greetd: {}", e),
  52. }
  53. }
  54. const INDEX_HTML: &str = r#"<!DOCTYPE html>
  55. <html>
  56. <head>
  57. <meta charset="UTF-8" />
  58. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  59. <title>PageOS 登录管理器</title>
  60. <style>
  61. :root {
  62. --primary-color: #2563eb;
  63. --error-color: #dc2626;
  64. }
  65. body {
  66. font-family: "Segoe UI", system-ui, sans-serif;
  67. max-width: 600px;
  68. margin: 0 auto;
  69. padding: 2rem;
  70. background-color: #f8fafc;
  71. }
  72. #auth-container {
  73. border: 1px solid #e2e8f0;
  74. padding: 2rem;
  75. border-radius: 0.5rem;
  76. background: white;
  77. box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  78. }
  79. h1 {
  80. color: var(--primary-color);
  81. margin-bottom: 1.5rem;
  82. text-align: center;
  83. }
  84. input {
  85. box-sizing: border-box;
  86. width: 100%;
  87. padding: 0.75rem;
  88. margin: 0.5rem 0 1rem;
  89. border: 1px solid #e2e8f0;
  90. border-radius: 0.375rem;
  91. font-size: 1rem;
  92. }
  93. button {
  94. width: 100%;
  95. padding: 0.75rem;
  96. background-color: var(--primary-color);
  97. color: white;
  98. border: none;
  99. border-radius: 0.375rem;
  100. font-size: 1rem;
  101. cursor: pointer;
  102. transition: background-color 0.2s;
  103. }
  104. button:hover {
  105. background-color: #1d4ed8;
  106. }
  107. #status-log {
  108. margin-top: 1.5rem;
  109. padding: 1rem;
  110. background: #f1f5f9;
  111. border-radius: 0.375rem;
  112. min-height: 100px;
  113. max-height: 300px;
  114. overflow-y: auto;
  115. font-family: monospace;
  116. font-size: 0.875rem;
  117. }
  118. .error {
  119. color: var(--error-color);
  120. }
  121. @media (max-width: 640px) {
  122. body {
  123. padding: 1rem;
  124. }
  125. #auth-container {
  126. padding: 1.5rem;
  127. }
  128. }
  129. </style>
  130. </head>
  131. <body>
  132. <div id="auth-container">
  133. <h1>PageOS 登录</h1>
  134. <div id="prompt">请输入用户名:</div>
  135. <input
  136. id="username"
  137. type="text"
  138. placeholder="用户名"
  139. autocomplete="username"
  140. />
  141. <input
  142. id="password"
  143. type="password"
  144. placeholder="密码"
  145. style="display: none"
  146. autocomplete="current-password"
  147. />
  148. <button id="submit-btn">提交</button>
  149. <div id="status-log"></div>
  150. </div>
  151. <script>
  152. const ws = new WebSocket(`ws://${window.location.host}/ws`);
  153. const statusLog = document.getElementById("status-log");
  154. const submitBtn = document.getElementById("submit-btn");
  155. let currentState = "username";
  156. ws.onopen = () => {
  157. logMessage("已连接到服务器", "info");
  158. };
  159. ws.onclose = () => {
  160. logMessage("连接已关闭", "warn");
  161. };
  162. ws.onerror = (err) => {
  163. logMessage(`连接错误: ${err}`, "error");
  164. };
  165. ws.onmessage = (event) => {
  166. try {
  167. const msg = JSON.parse(event.data);
  168. logMessage(`收到: ${JSON.stringify(msg)}`, "info");
  169. switch (msg.type) {
  170. case "AUTH_PROMPT":
  171. if (msg.message_type === "secret") {
  172. document.getElementById("password").style.display = "block";
  173. document.getElementById("username").style.display = "none";
  174. currentState = "password";
  175. submitBtn.textContent = "登录";
  176. }
  177. document.getElementById("prompt").textContent = msg.message;
  178. break;
  179. case "AUTH_SUCCESS":
  180. logMessage("✔ 登录成功! 正在启动会话...", "success");
  181. submitBtn.disabled = true;
  182. submitBtn.textContent = "登录成功";
  183. break;
  184. case "AUTH_ERROR":
  185. logMessage(`✖ 错误: ${msg.reason}`, "error");
  186. resetForm();
  187. break;
  188. }
  189. } catch (e) {
  190. logMessage(`消息解析错误: ${e}`, "error");
  191. }
  192. };
  193. submitBtn.addEventListener("click", () => {
  194. if (currentState === "username") {
  195. const username = document.getElementById("username").value.trim();
  196. if (!username) {
  197. logMessage("请输入用户名", "warn");
  198. return;
  199. }
  200. ws.send(JSON.stringify({ type: "AUTH_REQUEST", username }));
  201. } else {
  202. const password = document.getElementById("password").value;
  203. if (!password) {
  204. logMessage("请输入密码", "warn");
  205. return;
  206. }
  207. ws.send(
  208. JSON.stringify({ type: "AUTH_RESPONSE", response: password })
  209. );
  210. }
  211. });
  212. function logMessage(msg, type = "info") {
  213. const time = new Date().toLocaleTimeString();
  214. const div = document.createElement("div");
  215. div.textContent = `${time}: ${msg}`;
  216. if (type === "error") div.className = "error";
  217. statusLog.appendChild(div);
  218. statusLog.scrollTop = statusLog.scrollHeight;
  219. }
  220. function resetForm() {
  221. document.getElementById("username").style.display = "block";
  222. document.getElementById("password").style.display = "none";
  223. document.getElementById("username").value = "";
  224. document.getElementById("password").value = "";
  225. submitBtn.textContent = "提交";
  226. currentState = "username";
  227. }
  228. </script>
  229. </body>
  230. </html>"#;