Jelajahi Sumber

【新增】重新设计登录页面并添加新功能

- 重新设计了登录页面的布局和样式,使其更加美观和易用
- 添加了高级选项,允许用户输入环境变量和启动命令
- 实现了更丰富的用户交互,包括加载状态、提示信息等
- 优化了 WebSocket 消息处理逻辑,支持多种认证方式
- 新增了自定义 HTML 页面路径的参数
PJ568 1 tahun lalu
induk
melakukan
ef46a3b664
8 mengubah file dengan 616 tambahan dan 178 penghapusan
  1. 9 1
      CONTRIBUTING.md
  2. 7 7
      Cargo.lock
  3. 1 1
      Cargo.toml
  4. 1 1
      doc/greetd-ipc.md
  5. 280 0
      doc/login.html
  6. 13 6
      src/ipc.rs
  7. 12 1
      src/main.rs
  8. 293 161
      src/server.rs

+ 9 - 1
CONTRIBUTING.md

@@ -32,4 +32,12 @@
 - 对于 bug 的修复,应该将本次 Pull Request 和相对应 bug 的 issue 关联起来,让别人知道该问题已经被修复;
 - 对于较大的新功能,你需要先提交 Issues,例如 “【新增】添加 XXX 功能”,确认该功能有被添加的必要后,再开始工作;
 - 对于一些主观的样式、交互逻辑调整:如颜色、图标的使用,某些预设配置的增减修改等,一般不予通过。但可以在 Discussions 中进行讨论;
-- 其他如简单的代码优化、文档修正等,只要修改合理都会被接受。
+- 其他如简单的代码优化、文档修正等,只要修改合理都会被接受。
+
+## 设计文档
+
+- [网页 Greeter 实现设计](doc/design.md)
+- [greetd-agreety 技术实现解析](doc/greetd-agreety.md)
+- [greetd-ipc 协议解析记录](doc/greetd-ipc.md)
+- [提示词](doc/prompt.md)
+- [tuigreet 技术实现解析](doc/tuigreet.md)

+ 7 - 7
Cargo.lock

@@ -200,9 +200,9 @@ checksum = "9555578bc9e57714c812a1f84e4fc5b4d21fcb063490c624de019f7464c91268"
 
 [[package]]
 name = "clap"
-version = "4.5.40"
+version = "4.5.41"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "40b6887a1d8685cebccf115538db5c0efe625ccac9696ad45c409d96566e910f"
+checksum = "be92d32e80243a54711e5d7ce823c35c41c9d929dc4ab58e1276f625841aadf9"
 dependencies = [
  "clap_builder",
  "clap_derive",
@@ -210,9 +210,9 @@ dependencies = [
 
 [[package]]
 name = "clap_builder"
-version = "4.5.40"
+version = "4.5.41"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e0c66c08ce9f0c698cbce5c0279d0bb6ac936d8674174fe48f736533b964f59e"
+checksum = "707eab41e9622f9139419d573eca0900137718000c517d47da73045f54331c3d"
 dependencies = [
  "anstream",
  "anstyle",
@@ -222,9 +222,9 @@ dependencies = [
 
 [[package]]
 name = "clap_derive"
-version = "4.5.40"
+version = "4.5.41"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d2c7947ae4cc3d851207c1adb5b5e260ff0cca11446b1d6d1423788e442257ce"
+checksum = "ef4f52386a59ca4c860f7393bcf8abd8dfd91ecccc0f774635ff68e92eeef491"
 dependencies = [
  "heck",
  "proc-macro2",
@@ -600,7 +600,7 @@ checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39"
 
 [[package]]
 name = "pageos-greet"
-version = "1.0.1"
+version = "1.1.0"
 dependencies = [
  "axum",
  "clap",

+ 1 - 1
Cargo.toml

@@ -1,6 +1,6 @@
 [package]
 name = "pageos-greet"
-version = "1.0.1"
+version = "1.1.0"
 authors = ["PJ568 <[email protected]>"]
 edition = "2024"
 license = "MPL-2.0"

+ 1 - 1
doc/greetd-ipc.md

@@ -1,4 +1,4 @@
-# greetd-ipc 协议
+# greetd-ipc 协议解析记录
 
 - PJ568:
 

+ 280 - 0
doc/login.html

@@ -0,0 +1,280 @@
+<!DOCTYPE html>
+<html lang="zh-Hans-CN">
+  <head>
+    <meta charset="UTF-8" />
+    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+    <title>PageOS 登录管理器</title>
+    <link
+      rel="icon"
+      type="image/svg+xml"
+      href="data:image/svg+xml;charset=utf-8;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI1MCIgaGVpZ2h0PSI1MCI+PGNpcmNsZSBjeD0iMjUiIGN5PSIyNSIgcj0iMjAiIGZpbGw9ImdyZXkiIC8+PC9zdmc+"
+    />
+    <style>
+      :root,
+      body {
+        width: 100%;
+        height: 100%;
+        background-color: gray;
+        display: flex;
+        align-items: center;
+        justify-content: center;
+      }
+      h1 {
+        font-size: xx-large;
+      }
+      summary {
+        text-decoration: underline;
+      }
+      button,
+      summary {
+        cursor: pointer;
+      }
+      .auth-container {
+        margin: 1rem;
+        color: black;
+        background-color: white;
+        display: flex;
+        flex-direction: column;
+        gap: 0.5rem;
+        border: 0.1rem solid black;
+        padding: 1rem;
+      }
+      .auth-container .interface {
+        display: none;
+        flex-direction: column;
+        gap: 0.5rem;
+      }
+      .auth-container input {
+        box-sizing: border-box;
+        width: 100%;
+      }
+      .auth-container .loading {
+        color: white;
+        text-align: center;
+        padding: 0.2rem;
+        background-color: grey;
+      }
+      .auth-container .log {
+        border: 0.1rem solid black;
+        padding: 0.5rem;
+        font-size: smaller;
+      }
+      .auth-container .warn {
+        color: yellow;
+      }
+      .auth-container .error {
+        color: red;
+      }
+    </style>
+  </head>
+  <body>
+    <form id="auth">
+      <div class="auth-container">
+        <h1>PageOS 登录</h1>
+        <span class="loading">正加载</span>
+        <div class="interface">
+          <label class="prompt">
+            <div>用户名:</div>
+          </label>
+          <input
+            id="input"
+            type="text"
+            placeholder="请输入用户名"
+            autocomplete="username"
+          />
+          <button type="submit" class="submit-btn">提交</button>
+        </div>
+        <details>
+          <summary>高级</summary>
+          <p>环境变量:</p>
+          <input
+            id="session-env"
+            type="text"
+            placeholder="LANG=zh_CN.UTF-8"
+            autocomplete="session-env"
+          />
+          <p>启动命令:</p>
+          <input
+            id="session-cmd"
+            type="text"
+            value="%SESSION_COMMAND%"
+            placeholder="pageos-core --command 'cage -s -- firefox --kiosk --no-remote http://127.0.0.1:12800'"
+            autocomplete="session-cmd"
+          />
+          <p>日志:</p>
+          <div class="log"></div>
+        </details>
+      </div>
+    </form>
+
+    <script>
+      (function () {
+        // 获取表单元素
+        const loadElm = document.querySelector(".auth-container span.loading");
+        const interface = document.querySelector(".auth-container .interface");
+        const promptElm = document.querySelector(
+          ".auth-container label.prompt"
+        );
+        const inputElm = document.querySelector(".auth-container input#input");
+        const submitBtn = document.querySelector(".auth-container .submit-btn");
+        const statusLog = document.querySelector(".auth-container .log");
+
+        // 显示加载状态
+        function showLoading(message = "正加载") {
+          loadElm.textContent = message;
+          loadElm.style.display = "block";
+          interface.style.display = "none";
+        }
+
+        // 隐藏加载状态
+        function hideLoading() {
+          loadElm.style.display = "none";
+          interface.style.display = "flex";
+          inputElm.focus();
+        }
+
+        // 接口和状态
+        const ws = new WebSocket(`ws://${window.location.host}/ws`);
+        var currentState = "username"; // username: 未创建 greetd 会话, auth: 在会话中验证
+        hideLoading();
+
+        // 显示状态信息
+        function logMessage(msg, type = "info") {
+          const time = new Date().toLocaleTimeString();
+          const div = document.createElement("div");
+          div.textContent = `${time}:${msg}`;
+          if (type === "error") div.className = "error";
+          statusLog.appendChild(div);
+          statusLog.scrollTop = statusLog.scrollHeight;
+        }
+
+        // 新增一条提示信息
+        function addPrompt(text, type = "info") {
+          const message = document.createElement("div");
+          message.textContent = text;
+          message.className = type;
+          promptElm.appendChild(message);
+          promptElm.scrollTop = promptElm.scrollHeight;
+        }
+
+        // 清空提示信息
+        function clearPrompt() {
+          promptElm.innerHTML = "";
+        }
+
+        // 设定页面文字
+        function inerface_text(
+          prompt = "用户名:",
+          type = "info",
+          input_type = "text",
+          placeholder = "请输入用户名"
+        ) {
+          addPrompt(prompt, type);
+          inputElm.type = input_type;
+          inputElm.placeholder = placeholder;
+          inputElm.value = "";
+          hideLoading();
+        }
+
+        // 重置表单
+        function resetForm() {
+          clearPrompt();
+          inerface_text();
+          hideLoading();
+          currentState = "username";
+        }
+
+        // 连接
+        ws.onopen = () => {
+          logMessage("已连接到服务器");
+        };
+
+        // 断开链接
+        ws.onclose = () => {
+          logMessage("连接已关闭", "warn");
+          resetForm();
+        };
+
+        // 连接出错
+        ws.onerror = (err) => {
+          logMessage(`连接错误:${err}`, "error");
+        };
+
+        // 接收消息
+        ws.onmessage = (event) => {
+          try {
+            const msg = JSON.parse(event.data);
+            logMessage(`收到:${JSON.stringify(msg)}`);
+
+            switch (msg.type) {
+              case "AUTH_PROMPT":
+                currentState = "auth";
+                if (msg.message_type === "SECRET") {
+                  inerface_text(msg.message, "info", "password", "请输入密钥");
+                } else if (msg.message_type === "VISIBLE") {
+                  currentState = "auth";
+                  inerface_text(msg.message, "info", "text", "请输入文本");
+                } else if (msg.message_type === "INFO") {
+                  currentState = "auth";
+                  addPrompt(msg.message);
+                } else if (msg.message_type === "ERROR") {
+                  logMessage(`✖ greetd 错误:${msg.message}`, "error");
+                  addPrompt(msg.message, "error");
+                }
+                break;
+              case "AUTH_SUCCESS":
+                logMessage("✔ 登录成功! 正在启动会话……");
+                showLoading("登录成功,正启动会话");
+                const envStr = document.getElementById("session-env").value;
+                const cmdStr = document.getElementById("session-cmd").value;
+                // 将命令字符串分割为参数数组,处理带引号的参数
+                const cmd =
+                  cmdStr
+                    .match(/[^\s"']+|"([^"]*)"|'([^']*)'/g)
+                    ?.map((arg) => arg.replace(/^["']|["']$/g, "")) || [];
+                // 将环境变量字符串分割为键值对数组
+                const env =
+                  envStr
+                    .match(/[^\s"']+|"([^"]*)"|'([^']*)'/g)
+                    ?.map((arg) => arg.replace(/^["']|["']$/g, "")) || [];
+                ws.send(JSON.stringify({ type: "START_SESSION", cmd, env }));
+                break;
+              case "AUTH_ERROR":
+                logMessage(`✖ 错误:${msg.reason}`, "error");
+                resetForm();
+                break;
+            }
+            hideLoading();
+          } catch (e) {
+            logMessage(`消息解析错误:${e}`, "error");
+            addPrompt(`消息解析错误:${e}`, "error");
+          }
+        };
+
+        document.getElementById("auth").addEventListener("submit", (e) => {
+          e.preventDefault();
+          console.log("表单提交已触发");
+          if (currentState === "username") {
+            const username = inputElm.value.trim();
+            if (!username) {
+              logMessage("请输入用户名", "warn");
+              addPrompt("请输入用户名", "warn");
+              return;
+            }
+            showLoading();
+            ws.send(JSON.stringify({ type: "AUTH_REQUEST", username }));
+          } else {
+            const response = inputElm.value;
+            if (!response) {
+              logMessage("请输入信息", "warn");
+              addPrompt("请输入信息", "warn");
+              return;
+            }
+            showLoading();
+            ws.send(JSON.stringify({ type: "AUTH_RESPONSE", response }));
+          }
+        });
+      })();
+    </script>
+  </body>
+</html>

+ 13 - 6
src/ipc.rs

@@ -36,26 +36,26 @@ pub enum WsMessage {
 
 #[derive(Error, Debug)]
 pub enum IpcError {
-    #[error("IPC连接错误: {0}")]
+    #[error("IPC 连接错误: {0}")]
     Connection(#[from] std::io::Error),
     #[error("消息序列化错误: {0}")]
     Serialization(#[from] serde_json::Error),
     #[error("协议错误: {0}")]
     Protocol(String),
-    #[error("WebSocket错误: {0}")]
+    #[error("WebSocket 错误: {0}")]
     WebSocket(String),
-    #[error("IPC协议错误: {0}")]
+    #[error("IPC 协议错误: {0}")]
     IpcProtocol(#[from] greetd_ipc::codec::Error),
 }
 
 /// 连接到 greetd IPC 服务
 pub async fn connect_to_greetd() -> Result<UnixStream, IpcError> {
     let sock_path = env::var("GREETD_SOCK")
-        .map_err(|_| IpcError::Protocol("GREETD_SOCK环境变量未设置".into()))?;
+        .map_err(|_| IpcError::Protocol("GREETD_SOCK 环境变量未设置".into()))?;
     UnixStream::connect(&sock_path).await.map_err(Into::into)
 }
 
-/// WebSocket消息 -> greetd IPC请求
+/// WebSocket 消息 -> greetd IPC 请求
 pub fn ws_to_ipc(msg: WsMessage) -> Result<Request, IpcError> {
     match msg {
         WsMessage::AuthRequest { username } => Ok(Request::CreateSession { username }),
@@ -63,7 +63,7 @@ pub fn ws_to_ipc(msg: WsMessage) -> Result<Request, IpcError> {
             response: Some(response),
         }),
         WsMessage::StartSession { cmd, env } => Ok(Request::StartSession { cmd, env }),
-        _ => Err(IpcError::Protocol("无效的WebSocket消息类型".into())),
+        _ => Err(IpcError::Protocol("无效的 WebSocket 消息类型".into())),
     }
 }
 
@@ -111,6 +111,13 @@ pub async fn handle_websocket(
         let ws_msg = ipc_to_ws(resp);
         let json = serde_json::to_string(&ws_msg)?;
 
+        // 如果是 StartSession 成功响应,则退出进程
+        if let WsMessage::AuthSuccess = ws_msg {
+            if let Request::StartSession { .. } = ipc_msg {
+                std::process::exit(0);
+            }
+        }
+
         ws.send(axum::extract::ws::Message::Text(json.into()))
             .await
             .map_err(|e| IpcError::WebSocket(e.to_string()))?;

+ 12 - 1
src/main.rs

@@ -26,6 +26,10 @@ struct Args {
     /// 启动子进程命令 (父进程退出时会自动终止子进程)
     #[arg(short, long)]
     launch_command: Option<String>,
+
+    /// 自定义 HTML 页面路径
+    #[arg(long)]
+    page: Option<std::path::PathBuf>,
 }
 
 #[tokio::main]
@@ -63,7 +67,14 @@ async fn main() {
 
     // 启动服务器
     info!("启动服务器,监听端口: {}", args.port);
-    if let Err(e) = run_server(args.port).await {
+    let html_content = match args.page {
+        Some(path) => std::fs::read_to_string(path).unwrap_or_else(|_| {
+            error!("无法读取自定义HTML文件,使用默认页面");
+            "none".to_string()
+        }),
+        None => "none".to_string(),
+    };
+    if let Err(e) = run_server(args.port, html_content).await {
         error!("服务器启动失败: {}", e);
         process::exit(1);
     }

+ 293 - 161
src/server.rs

@@ -13,10 +13,47 @@ use std::net::SocketAddr;
 use tokio::net::TcpListener;
 use tracing::{error, info};
 
+// 简单的 HTML 转义
+fn html_escape(s: &str) -> String {
+    s.replace('&', "&")
+        .replace('<', "<")
+        .replace('>', ">")
+        .replace('\"', "\"")
+        .replace('\'', "\'")
+}
+
 /// 启动 HTTP 服务器
-pub async fn run_server(port: u16) -> Result<(), IpcError> {
+pub async fn run_server(port: u16, html_content: String) -> Result<(), IpcError> {
     let app = Router::new()
-        .route("/", get(index_handler))
+        .route(
+            "/",
+            get(move || {
+                let session_command = std::env::var("SESSION_COMMAND").unwrap_or_default();
+                let escaped_session_command = html_escape(&session_command);
+                async move {
+                    let mut content = if html_content != "none".to_string() {
+                        html_content.clone()
+                    } else {
+                        index_handler().await
+                    };
+                    // 确保替换所有占位符
+                    // 优先替换带引号的占位符,再替换不带引号的
+                    if escaped_session_command.is_empty() {
+                        content = content
+                            .replace("\"%SESSION_COMMAND%\"", "\"\"")
+                            .replace("%SESSION_COMMAND%", "");
+                    } else {
+                        content = content
+                            .replace(
+                                "\"%SESSION_COMMAND%\"",
+                                &format!("\"{}\"", &escaped_session_command),
+                            )
+                            .replace("%SESSION_COMMAND%", &escaped_session_command);
+                    }
+                    Html(content)
+                }
+            }),
+        )
         .route("/ws", get(websocket_handler));
 
     let addr = SocketAddr::from(([127, 0, 0, 1], port));
@@ -36,8 +73,8 @@ pub async fn run_server(port: u16) -> Result<(), IpcError> {
 }
 
 /// 处理首页请求
-async fn index_handler() -> Html<&'static str> {
-    Html(INDEX_HTML)
+async fn index_handler() -> String {
+    INDEX_HTML.to_string()
 }
 
 /// 处理 WebSocket 升级请求
@@ -57,189 +94,284 @@ async fn handle_socket(socket: WebSocket) {
         Err(e) => error!("无法连接到 greetd: {}", e),
     }
 }
+
 const INDEX_HTML: &str = r#"<!DOCTYPE html>
-<html>
+<html lang="zh-Hans-CN">
   <head>
     <meta charset="UTF-8" />
     <meta name="viewport" content="width=device-width, initial-scale=1.0" />
     <title>PageOS 登录管理器</title>
+    <link
+      rel="icon"
+      type="image/svg+xml"
+      href="data:image/svg+xml;charset=utf-8;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI1MCIgaGVpZ2h0PSI1MCI+PGNpcmNsZSBjeD0iMjUiIGN5PSIyNSIgcj0iMjAiIGZpbGw9ImdyZXkiIC8+PC9zdmc+"
+    />
     <style>
-      :root {
-        --primary-color: #2563eb;
-        --error-color: #dc2626;
-      }
+      :root,
       body {
-        font-family: "Segoe UI", system-ui, sans-serif;
-        max-width: 600px;
-        margin: 0 auto;
-        padding: 2rem;
-        background-color: #f8fafc;
-      }
-      #auth-container {
-        border: 1px solid #e2e8f0;
-        padding: 2rem;
-        border-radius: 0.5rem;
-        background: white;
-        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
+        width: 100%;
+        height: 100%;
+        background-color: gray;
+        display: flex;
+        align-items: center;
+        justify-content: center;
       }
       h1 {
-        color: var(--primary-color);
-        margin-bottom: 1.5rem;
-        text-align: center;
+        font-size: xx-large;
+      }
+      summary {
+        text-decoration: underline;
+      }
+      button,
+      summary {
+        cursor: pointer;
+      }
+      .auth-container {
+        margin: 1rem;
+        color: black;
+        background-color: white;
+        display: flex;
+        flex-direction: column;
+        gap: 0.5rem;
+        border: 0.1rem solid black;
+        padding: 1rem;
       }
-      input {
+      .auth-container .interface {
+        display: none;
+        flex-direction: column;
+        gap: 0.5rem;
+      }
+      .auth-container input {
         box-sizing: border-box;
         width: 100%;
-        padding: 0.75rem;
-        margin: 0.5rem 0 1rem;
-        border: 1px solid #e2e8f0;
-        border-radius: 0.375rem;
-        font-size: 1rem;
       }
-      button {
-        width: 100%;
-        padding: 0.75rem;
-        background-color: var(--primary-color);
+      .auth-container .loading {
         color: white;
-        border: none;
-        border-radius: 0.375rem;
-        font-size: 1rem;
-        cursor: pointer;
-        transition: background-color 0.2s;
-      }
-      button:hover {
-        background-color: #1d4ed8;
+        text-align: center;
+        padding: 0.2rem;
+        background-color: grey;
       }
-      #status-log {
-        margin-top: 1.5rem;
-        padding: 1rem;
-        background: #f1f5f9;
-        border-radius: 0.375rem;
-        min-height: 100px;
-        max-height: 300px;
-        overflow-y: auto;
-        font-family: monospace;
-        font-size: 0.875rem;
+      .auth-container .log {
+        border: 0.1rem solid black;
+        padding: 0.5rem;
+        font-size: smaller;
       }
-      .error {
-        color: var(--error-color);
+      .auth-container .warn {
+        color: yellow;
       }
-      @media (max-width: 640px) {
-        body {
-          padding: 1rem;
-        }
-        #auth-container {
-          padding: 1.5rem;
-        }
+      .auth-container .error {
+        color: red;
       }
     </style>
   </head>
   <body>
-    <div id="auth-container">
-      <h1>PageOS 登录</h1>
-      <div id="prompt">请输入用户名:</div>
-      <input
-        id="username"
-        type="text"
-        placeholder="用户名"
-        autocomplete="username"
-      />
-      <input
-        id="password"
-        type="password"
-        placeholder="密码"
-        style="display: none"
-        autocomplete="current-password"
-      />
-      <button id="submit-btn">提交</button>
-      <div id="status-log"></div>
-    </div>
+    <form id="auth">
+      <div class="auth-container">
+        <h1>PageOS 登录</h1>
+        <span class="loading">正加载</span>
+        <div class="interface">
+          <label class="prompt">
+            <div>用户名:</div>
+          </label>
+          <input
+            id="input"
+            type="text"
+            placeholder="请输入用户名"
+            autocomplete="username"
+          />
+          <button type="submit" class="submit-btn">提交</button>
+        </div>
+        <details>
+          <summary>高级</summary>
+          <p>环境变量:</p>
+          <input
+            id="session-env"
+            type="text"
+            placeholder="LANG=zh_CN.UTF-8"
+            autocomplete="session-env"
+          />
+          <p>启动命令:</p>
+          <input
+            id="session-cmd"
+            type="text"
+            value="%SESSION_COMMAND%"
+            placeholder="pageos-core --command 'cage -s -- firefox --kiosk --no-remote http://127.0.0.1:12800'"
+            autocomplete="session-cmd"
+          />
+          <p>日志:</p>
+          <div class="log"></div>
+        </details>
+      </div>
+    </form>
 
     <script>
-      const ws = new WebSocket(`ws://${window.location.host}/ws`);
-      const statusLog = document.getElementById("status-log");
-      const submitBtn = document.getElementById("submit-btn");
-      let currentState = "username";
-
-      ws.onopen = () => {
-        logMessage("已连接到服务器", "info");
-      };
-
-      ws.onclose = () => {
-        logMessage("连接已关闭", "warn");
-      };
-
-      ws.onerror = (err) => {
-        logMessage(`连接错误: ${err}`, "error");
-      };
-
-      ws.onmessage = (event) => {
-        try {
-          const msg = JSON.parse(event.data);
-          logMessage(`收到: ${JSON.stringify(msg)}`, "info");
-
-          switch (msg.type) {
-            case "AUTH_PROMPT":
-              if (msg.message_type === "secret") {
-                document.getElementById("password").style.display = "block";
-                document.getElementById("username").style.display = "none";
-                currentState = "password";
-                submitBtn.textContent = "登录";
-              }
-              document.getElementById("prompt").textContent = msg.message;
-              break;
-            case "AUTH_SUCCESS":
-              logMessage("✔ 登录成功! 正在启动会话...", "success");
-              submitBtn.disabled = true;
-              submitBtn.textContent = "登录成功";
-              break;
-            case "AUTH_ERROR":
-              logMessage(`✖ 错误: ${msg.reason}`, "error");
-              resetForm();
-              break;
-          }
-        } catch (e) {
-          logMessage(`消息解析错误: ${e}`, "error");
+      (function () {
+        // 获取表单元素
+        const loadElm = document.querySelector(".auth-container span.loading");
+        const interface = document.querySelector(".auth-container .interface");
+        const promptElm = document.querySelector(
+          ".auth-container label.prompt"
+        );
+        const inputElm = document.querySelector(".auth-container input#input");
+        const submitBtn = document.querySelector(".auth-container .submit-btn");
+        const statusLog = document.querySelector(".auth-container .log");
+
+        // 显示加载状态
+        function showLoading(message = "正加载") {
+          loadElm.textContent = message;
+          loadElm.style.display = "block";
+          interface.style.display = "none";
         }
-      };
-
-      submitBtn.addEventListener("click", () => {
-        if (currentState === "username") {
-          const username = document.getElementById("username").value.trim();
-          if (!username) {
-            logMessage("请输入用户名", "warn");
-            return;
-          }
-          ws.send(JSON.stringify({ type: "AUTH_REQUEST", username }));
-        } else {
-          const password = document.getElementById("password").value;
-          if (!password) {
-            logMessage("请输入密码", "warn");
-            return;
-          }
-          ws.send(
-            JSON.stringify({ type: "AUTH_RESPONSE", response: password })
-          );
+
+        // 隐藏加载状态
+        function hideLoading() {
+          loadElm.style.display = "none";
+          interface.style.display = "flex";
+          inputElm.focus();
         }
-      });
-
-      function logMessage(msg, type = "info") {
-        const time = new Date().toLocaleTimeString();
-        const div = document.createElement("div");
-        div.textContent = `${time}: ${msg}`;
-        if (type === "error") div.className = "error";
-        statusLog.appendChild(div);
-        statusLog.scrollTop = statusLog.scrollHeight;
-      }
 
-      function resetForm() {
-        document.getElementById("username").style.display = "block";
-        document.getElementById("password").style.display = "none";
-        document.getElementById("username").value = "";
-        document.getElementById("password").value = "";
-        submitBtn.textContent = "提交";
-        currentState = "username";
-      }
+        // 接口和状态
+        const ws = new WebSocket(`ws://${window.location.host}/ws`);
+        var currentState = "username"; // username: 未创建 greetd 会话, auth: 在会话中验证
+        hideLoading();
+
+        // 显示状态信息
+        function logMessage(msg, type = "info") {
+          const time = new Date().toLocaleTimeString();
+          const div = document.createElement("div");
+          div.textContent = `${time}:${msg}`;
+          if (type === "error") div.className = "error";
+          statusLog.appendChild(div);
+          statusLog.scrollTop = statusLog.scrollHeight;
+        }
+
+        // 新增一条提示信息
+        function addPrompt(text, type = "info") {
+          const message = document.createElement("div");
+          message.textContent = text;
+          message.className = type;
+          promptElm.appendChild(message);
+          promptElm.scrollTop = promptElm.scrollHeight;
+        }
+
+        // 清空提示信息
+        function clearPrompt() {
+          promptElm.innerHTML = "";
+        }
+
+        // 设定页面文字
+        function inerface_text(
+          prompt = "用户名:",
+          type = "info",
+          input_type = "text",
+          placeholder = "请输入用户名"
+        ) {
+          addPrompt(prompt, type);
+          inputElm.type = input_type;
+          inputElm.placeholder = placeholder;
+          inputElm.value = "";
+          hideLoading();
+        }
+
+        // 重置表单
+        function resetForm() {
+          clearPrompt();
+          inerface_text();
+          hideLoading();
+          currentState = "username";
+        }
+
+        // 连接
+        ws.onopen = () => {
+          logMessage("已连接到服务器");
+        };
+
+        // 断开链接
+        ws.onclose = () => {
+          logMessage("连接已关闭", "warn");
+          resetForm();
+        };
+
+        // 连接出错
+        ws.onerror = (err) => {
+          logMessage(`连接错误:${err}`, "error");
+        };
+
+        // 接收消息
+        ws.onmessage = (event) => {
+          try {
+            const msg = JSON.parse(event.data);
+            logMessage(`收到:${JSON.stringify(msg)}`);
+
+            switch (msg.type) {
+              case "AUTH_PROMPT":
+                currentState = "auth";
+                if (msg.message_type === "SECRET") {
+                  inerface_text(msg.message, "info", "password", "请输入密钥");
+                } else if (msg.message_type === "VISIBLE") {
+                  currentState = "auth";
+                  inerface_text(msg.message, "info", "text", "请输入文本");
+                } else if (msg.message_type === "INFO") {
+                  currentState = "auth";
+                  addPrompt(msg.message);
+                } else if (msg.message_type === "ERROR") {
+                  logMessage(`✖ greetd 错误:${msg.message}`, "error");
+                  addPrompt(msg.message, "error");
+                }
+                break;
+              case "AUTH_SUCCESS":
+                logMessage("✔ 登录成功! 正在启动会话……");
+                showLoading("登录成功,正启动会话");
+                const envStr = document.getElementById("session-env").value;
+                const cmdStr = document.getElementById("session-cmd").value;
+                // 将命令字符串分割为参数数组,处理带引号的参数
+                const cmd =
+                  cmdStr
+                    .match(/[^\s"']+|"([^"]*)"|'([^']*)'/g)
+                    ?.map((arg) => arg.replace(/^["']|["']$/g, "")) || [];
+                // 将环境变量字符串分割为键值对数组
+                const env =
+                  envStr
+                    .match(/[^\s"']+|"([^"]*)"|'([^']*)'/g)
+                    ?.map((arg) => arg.replace(/^["']|["']$/g, "")) || [];
+                ws.send(JSON.stringify({ type: "START_SESSION", cmd, env }));
+                break;
+              case "AUTH_ERROR":
+                logMessage(`✖ 错误:${msg.reason}`, "error");
+                resetForm();
+                break;
+            }
+            hideLoading();
+          } catch (e) {
+            logMessage(`消息解析错误:${e}`, "error");
+            addPrompt(`消息解析错误:${e}`, "error");
+          }
+        };
+
+        document.getElementById("auth").addEventListener("submit", (e) => {
+          e.preventDefault();
+          console.log("表单提交已触发");
+          if (currentState === "username") {
+            const username = inputElm.value.trim();
+            if (!username) {
+              logMessage("请输入用户名", "warn");
+              addPrompt("请输入用户名", "warn");
+              return;
+            }
+            showLoading();
+            ws.send(JSON.stringify({ type: "AUTH_REQUEST", username }));
+          } else {
+            const response = inputElm.value;
+            if (!response) {
+              logMessage("请输入信息", "warn");
+              addPrompt("请输入信息", "warn");
+              return;
+            }
+            showLoading();
+            ws.send(JSON.stringify({ type: "AUTH_RESPONSE", response }));
+          }
+        });
+      })();
     </script>
   </body>
 </html>"#;