add user auth

This commit is contained in:
2026-08-31 21:08:46 +08:00
parent edc0349708
commit 85266f3879
11 changed files with 569 additions and 19 deletions
+2 -2
View File
@@ -502,7 +502,7 @@ models:
- **前端**:单页 H5 + Vanilla JS + SSE(不引入重型框架)
- **数据库**:SQLite
- **部署**:Docker Compose
- **认证**:nginx-proxy basic auth(简单多用户登录,不做任务隔离)
- **认证**:内置多用户登录(用户名/明文密码配在 `config.yml` 的 `auth.users`,登录页 + HttpOnly cookie,不做任务隔离;不用 nginx htpasswd,因手机浏览器原生下载不带 Basic 头会失败)
### 8.2 系统组件
@@ -800,7 +800,7 @@ networks:
### 13.2 nginx-proxy 对外暴露
前置的 nginx-proxy 需与业务容器共用外部网络 `my-app-network`。compose 通过 `VIRTUAL_HOST`/`VIRTUAL_PORT`/`CERT_NAME` 接入;域名 `agent.ai.foresh.com` 的 DNS 指向 nginx-proxy 所在宿主机。多个用户共享同一认证,不做任务隔离;SSE 需关代理缓冲(`proxy_buffering off`),见 `docs/DEPLOY.md`。
前置的 nginx-proxy 需与业务容器共用外部网络 `my-app-network`。compose 通过 `VIRTUAL_HOST`/`VIRTUAL_PORT`/`CERT_NAME` 接入;域名 `agent.ai.foresh.com` 的 DNS 指向 nginx-proxy 所在宿主机。认证用应用内置的多用户登录(`config.yml` 的 `auth.users`,登录页 `/login`),nginx 层不再配 htpasswd;多用户共享同一任务库,不做任务隔离;SSE 需关代理缓冲(`proxy_buffering off`),见 `docs/DEPLOY.md`。
---
+13 -3
View File
@@ -37,10 +37,20 @@ model_hold:
active_max_ms: 1800000 # 30 分钟
sweep_ms: 10000 # 10 秒
# 内置 basic auth(可选)。若已在前面放 nginx-proxy 做认证,此处留空即可。
# 登录认证(推荐启用):多用户,用户名/明文密码直接配在这里(自用场景)。
# 登录页 /login,会话 token 以 HttpOnly cookie 下发(替代 nginx htpasswd:
# 手机浏览器原生下载不带 Basic 认证头,cookie 则会自动携带,下载不再失败)。
# 仍兼容 Authorization: Basic 头(curl/API 脚本可用)。
# secret:签名密钥;留空则启动时随机生成(重启后需重新登录)。
# 整段删除或 users 留空则不启用认证。
# auth:
# user: admin
# password: "change-me"
# secret: "change-me" # 选填;建议固定,避免重启掉登录态
# ttl_ms: 2592000000 # 选填,登录态有效期,默认 30 天
# users:
# - user: admin
# password: "change-me"
# - user: alice
# password: "s3cret"
# MCP 服务(可配多个;与内置工具分开)。启动时对每个服务调 tools/list 发现工具,
# 追加到内置工具之后一起发给模型;调用经 tools/call 转发。headers 是任意请求头(如 Authorization)。
+161
View File
@@ -0,0 +1,161 @@
// 多用户会话认证:用户名/明文密码配在 config.yml 的 auth.users,登录后签发 HMAC 签名 token,
// 以 HttpOnly cookie 下发(SameSite=Lax,浏览器在 XHR 与原生下载导航中都会自动携带)。
// 替代原先 nginx htpasswd 的 basic auth:手机浏览器原生下载不带 Basic 认证头,导致下载失败。
const express = require('express');
const crypto = require('crypto');
const path = require('path');
const COOKIE_NAME = 'agent_token';
const DEFAULT_TTL_MS = 30 * 24 * 3600 * 1000; // 30 天
function b64url(buf) {
return Buffer.from(buf).toString('base64url').replace(/=+$/, '');
}
function timingEqual(a, b) {
// 先哈希再定长比较:timingSafeEqual 要求等长 buffer,哈希后既定长又避免长度旁路
const ha = crypto.createHash('sha256').update(String(a)).digest();
const hb = crypto.createHash('sha256').update(String(b)).digest();
return crypto.timingSafeEqual(ha, hb);
}
// ---------- token:payloadB64url.signature(无状态,密钥变更/重启即失效) ----------
function signToken(username, expires, secret) {
const payload = b64url(Buffer.from(JSON.stringify({ u: username, exp: expires }), 'utf8'));
const sig = crypto.createHmac('sha256', secret).update(payload).digest('hex');
return payload + '.' + sig;
}
function readToken(token, secret) {
if (!token || typeof token !== 'string') return null;
const i = token.lastIndexOf('.');
if (i <= 0) return null;
const payload = token.slice(0, i);
const sig = token.slice(i + 1);
const expected = crypto.createHmac('sha256', secret).update(payload).digest('hex');
if (!timingEqual(sig, expected)) return null;
try {
const data = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));
if (!data || typeof data.u !== 'string' || !Number.isFinite(data.exp) || data.exp < Date.now()) return null;
return { user: data.u };
} catch (_) { return null; }
}
// ---------- cookie / basic 凭据解析 ----------
function parseCookies(req) {
const out = {};
const raw = req.headers.cookie;
if (!raw) return out;
for (const part of raw.split(';')) {
const i = part.indexOf('=');
if (i > 0) out[part.slice(0, i).trim()] = decodeURIComponent(part.slice(i + 1).trim());
}
return out;
}
// Authorization: Basic 兼容层(curl / API 脚本用;浏览器页面下载走 cookie)
function basicAuthUser(req, users) {
const h = req.headers.authorization;
if (!h || !h.startsWith('Basic ')) return null;
let decoded;
try { decoded = Buffer.from(h.slice(6), 'base64').toString('utf8'); } catch (_) { return null; }
const i = decoded.indexOf(':');
if (i < 0) return null;
const name = decoded.slice(0, i);
const pass = decoded.slice(i + 1);
for (const u of users) {
if (timingEqual(u.user, name) && timingEqual(u.password, pass)) return u.user;
}
return null;
}
// ---------- 免认证路径(登录页自身需要的资源) ----------
const PUBLIC_EXACT = new Set(['/login', '/logout', '/api/login', '/api/logout', '/api/health']);
function isPublicPath(p) {
if (PUBLIC_EXACT.has(p)) return true;
if (p.startsWith('/css/')) return true; // 登录页复用 style.css
if (p === '/favicon.ico') return true;
return false;
}
// 带签名 token 的临时下载链接(files.js 自己验签),此处放行由路由层拒绝伪造请求
function isSignedDownload(req) {
return req.method === 'GET' && /\/files\/download$/.test(req.path) && !!req.query.t;
}
// cfg.auth = { users: [{user, password}], secret?, ttl_ms? }
// users 为空则整个认证关闭(cfg.auth 为 null)。
function createAuth(cfg) {
const router = express.Router();
const users = (cfg.auth && cfg.auth.users) || [];
if (!users.length) {
return { enabled: false, middleware: (req, res, next) => next(), router };
}
const secret = (cfg.auth.secret && String(cfg.auth.secret)) || crypto.randomBytes(32).toString('hex');
if (!cfg.auth.secret) {
console.log('[auth] 未配置 auth.secret,已使用随机密钥:进程重启后所有登录态失效');
}
const ttlMs = Number(cfg.auth.ttl_ms) || DEFAULT_TTL_MS;
const validUsers = new Map(users.map(u => [String(u.user), String(u.password)]));
function setAuthCookie(res, username) {
const token = signToken(username, Date.now() + ttlMs, secret);
res.setHeader('Set-Cookie', COOKIE_NAME + '=' + encodeURIComponent(token)
+ '; Path=/; HttpOnly; SameSite=Lax; Max-Age=' + Math.floor(ttlMs / 1000));
}
function clearAuthCookie(res) {
res.setHeader('Set-Cookie', COOKIE_NAME + '=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0');
}
function sessionUser(req) {
const token = parseCookies(req)[COOKIE_NAME];
const data = readToken(token, secret);
// 用户可能已从配置中删除:token 有效但用户不存在也视为未登录
if (data && validUsers.has(data.user)) return data.user;
return null;
}
// ----- 登录/登出 API -----
router.post('/api/login', (req, res) => {
const { user, password } = req.body || {};
const expect = validUsers.get(String(user || ''));
if (expect == null || !timingEqual(expect, String(password == null ? '' : password))) {
return res.status(401).json({ error: '用户名或密码错误' });
}
setAuthCookie(res, String(user));
res.json({ ok: true, user: String(user) });
});
router.post('/api/logout', (req, res) => {
clearAuthCookie(res);
res.json({ ok: true });
});
router.get('/api/me', (req, res) => {
res.json({ user: sessionUser(req) });
});
// ----- 登录页 / 登出跳转 -----
router.get('/login', (req, res) => {
if (sessionUser(req)) return res.redirect('/');
res.sendFile(path.join(__dirname, 'public', 'login.html'));
});
router.get('/logout', (req, res) => {
clearAuthCookie(res);
res.redirect('/login');
});
// ----- 全局认证中间件:cookie 或 Basic 任一通过;否则 API 回 401、页面跳登录页 -----
const middleware = (req, res, next) => {
const fromBasic = basicAuthUser(req, users);
const user = fromBasic || sessionUser(req);
if (user) { req.user = user; return next(); }
if (isPublicPath(req.path) || isSignedDownload(req)) return next();
if (req.path.startsWith('/api/')) return res.status(401).json({ error: '未登录' });
return res.redirect('/login');
};
return { enabled: true, middleware, router };
}
module.exports = { createAuth, COOKIE_NAME };
+14 -1
View File
@@ -14,7 +14,9 @@ const DEFAULTS = {
// 「绑定模型但闲置」的会话(从未发言、无未回应消息)同样按此租约释放,防建而不用霸占模型。
model_hold: { idle_release_ms: 180000, active_max_ms: 1800000, sweep_ms: 10000 },
models: [],
auth: null, // { user, password },为空则不启用内置 basic auth(可交给 nginx-proxy)
// 登录认证:{ users: [{user, password}], secret?, ttl_ms? },密码明文存配置(自用场景)。
// users 为空则不启用认证(可交给前置 nginx-proxy,但手机浏览器原生下载不带 Basic 头,不推荐)。
auth: null,
// MCP 服务列表:每项 {name?, url, headers?};启动时发现其工具并追加到内置工具之后。
// 注意与内置工具(definitions.json)严格分离:这里只配外部 MCP 服务。
mcp_servers: [],
@@ -55,6 +57,17 @@ function loadConfig(configPath) {
cfg.workspace_root = path.resolve(cfg.workspace_root);
if (!cfg.db_path) cfg.db_path = path.join(cfg.workspace_root, '.agent.db');
// auth 规范化:多用户 auth.users: [{user, password}];兼容旧的单用户 auth.{user,password}
if (cfg.auth && !Array.isArray(cfg.auth.users)) {
cfg.auth.users = cfg.auth.user ? [{ user: cfg.auth.user, password: cfg.auth.password }] : [];
}
if (cfg.auth && Array.isArray(cfg.auth.users)) {
cfg.auth.users = cfg.auth.users
.filter(u => u && u.user)
.map(u => ({ user: String(u.user), password: String(u.password == null ? '' : u.password) }));
if (!cfg.auth.users.length) cfg.auth = null;
}
// 兼容旧配置:顶层 web_search.{url,authorization} 自动转为一条 mcp_servers(authorization 即一条 header)
if (raw.web_search && raw.web_search.url && !raw.mcp_servers) {
const ws = raw.web_search;
+6 -2
View File
@@ -21,7 +21,11 @@
</svg>
<h2>Agent 任务台</h2>
</div>
<div style="display:flex; gap:2px;">
<div style="display:flex; gap:2px; align-items:center;">
<span id="whoami" class="hidden" style="color:rgba(255,255,255,0.85); font-size:12px; margin-right:6px; max-width:80px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;"></span>
<button class="icon-btn hidden" id="logout-btn" onclick="ui.logout()" title="退出登录">
<svg viewBox="0 0 24 24"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"></path><polyline points="16 17 21 12 16 7"></polyline><line x1="21" y1="12" x2="9" y2="12"></line></svg>
</button>
<button class="icon-btn" id="create-session-btn" onclick="ui.openCreate()" title="新建任务">
<svg viewBox="0 0 24 24"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>
</button>
@@ -111,6 +115,6 @@
<div class="toast hidden" id="toast"></div>
<!-- 发版时更新 v 参数,避免移动端浏览器缓存旧 JS -->
<script src="/js/app.js?v=20260831d"></script>
<script src="/js/app.js?v=20260831e"></script>
</body>
</html>
+16 -1
View File
@@ -30,6 +30,7 @@ async function req(method, url, body, isForm) {
opt.body = body;
}
const res = await fetch(url, opt);
if (res.status === 401) { location.href = '/login'; throw new Error('未登录'); }
if (!res.ok) {
let msg = 'HTTP ' + res.status;
try { msg = (await res.json()).error || msg; } catch (_) {}
@@ -361,7 +362,7 @@ function updatePhaseUI(d) {
// ---------- 文件 ----------
// 下载:先换一枚短时效签名链接,再 window.location.href 交给浏览器原生下载。
// (fetch+blob 在移动端浏览器会被改名 uuid.bin;原生导航下载按服务端
// Content-Disposition 保留原名,同源自动带 Basic 认证头。)
// Content-Disposition 保留原名,同源自动携带登录 cookie。)
async function downloadFile(name) {
if (!state.sessionId) return;
try {
@@ -496,8 +497,21 @@ const ui = {
loadFiles();
} catch (e) { toast('删除失败:' + e.message); }
},
logout() { location.href = '/logout'; },
};
// ---------- 登录态:显示当前用户;未启用认证(/api/me 404)则隐藏退出按钮 ----------
async function initAuth() {
try {
const me = await req('GET', '/api/me');
if (me && me.user) {
$('whoami').textContent = me.user;
$('whoami').classList.remove('hidden');
$('logout-btn').classList.remove('hidden');
}
} catch (_) { /* 未启用认证 */ }
}
// ---------- 输入框行为 ----------
document.addEventListener('input', e => {
if (e.target.id === 'msg-input') {
@@ -519,4 +533,5 @@ document.addEventListener('keydown', e => {
showList();
loadSessions();
loadModels();
initAuth();
setInterval(loadSessions, 8000);
+71
View File
@@ -0,0 +1,71 @@
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Agent 任务台 · 登录</title>
<meta name="theme-color" content="#1e3c72">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<link rel="stylesheet" href="/css/style.css">
<style>
.login-wrap {
position: fixed; inset: 0; display: flex; align-items: center; justify-content: center;
background: linear-gradient(135deg, #1e3c72, #2a5299);
}
.login-card {
background: #fff; border-radius: 14px; padding: 28px 22px 22px; width: 84%; max-width: 340px;
}
.login-card h2 { font-size: 18px; margin-bottom: 18px; text-align: center; color: #223; }
.login-card input {
display: block; width: 100%; box-sizing: border-box;
border: 1px solid #dde; border-radius: 8px; padding: 11px 12px;
font-size: 15px; margin-bottom: 12px; outline: none;
}
.login-card input:focus { border-color: #2a5299; }
.login-error { color: #d2483c; font-size: 13px; min-height: 18px; margin: 6px 0 0; text-align: center; }
</style>
</head>
<body>
<div class="login-wrap">
<form class="login-card" id="login-form" onsubmit="return doLogin(event)">
<h2>Agent 任务台</h2>
<input type="text" id="login-user" placeholder="用户名" autocomplete="username" autocapitalize="none" autocorrect="off">
<input type="password" id="login-pass" placeholder="密码" autocomplete="current-password">
<button class="primary-btn" id="login-btn" type="submit">登录</button>
<p class="login-error" id="login-error"></p>
</form>
</div>
<script>
'use strict';
async function doLogin(e) {
e.preventDefault();
const btn = document.getElementById('login-btn');
const errEl = document.getElementById('login-error');
errEl.textContent = '';
btn.disabled = true;
try {
const res = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
user: document.getElementById('login-user').value.trim(),
password: document.getElementById('login-pass').value,
}),
});
if (!res.ok) {
let msg = 'HTTP ' + res.status;
try { msg = (await res.json()).error || msg; } catch (_) {}
throw new Error(msg);
}
location.href = '/';
} catch (e2) {
errEl.textContent = e2.message || '登录失败';
btn.disabled = false;
}
return false;
}
document.getElementById('login-user').focus();
</script>
</body>
</html>
+7 -9
View File
@@ -7,6 +7,7 @@ const fs = require('fs');
const { loadConfig } = require('./config');
const { initDb } = require('./db');
const { createBus } = require('./sse');
const { createAuth } = require('./auth');
const engine = require('./engine');
const mcp = require('./mcp');
@@ -22,15 +23,11 @@ const server = http.createServer(app);
app.use(express.json({ limit: '2mb' }));
// 可选 basic auth(若前置 nginx 已做,可不启用)
if (cfg.auth && cfg.auth.user) {
const expected = 'Basic ' + Buffer.from(cfg.auth.user + ':' + cfg.auth.password).toString('base64');
app.use((req, res, next) => {
if (req.headers.authorization === expected) return next();
res.set('WWW-Authenticate', 'Basic realm="agent"');
res.status(401).end('需要认证');
});
}
// 登录认证(cookie 会话):users 配在 config.yml 的 auth.users;留空则不启用。
// 相比 nginx htpasswd 的 basic auth,cookie 在手机浏览器原生下载时也会自动携带,下载不再失败。
const auth = createAuth(cfg);
app.use(auth.router); // /login、/logout、/api/login 等免认证端点
app.use(auth.middleware); // 其余请求需登录态(cookie 或 Basic 头)
app.use(express.static(path.join(__dirname, 'public')));
@@ -55,5 +52,6 @@ mcp.init(cfg).then(() => {
console.log(' models=' + cfg.models.map(m => m.id + '@' + m.url).join(', '));
const mcpList = (cfg.mcp_servers || []).map(s => s.name + '@' + s.url).join(', ');
console.log(' mcp_servers=' + (mcpList || '(none)'));
console.log(' auth=' + (auth.enabled ? 'login (' + cfg.auth.users.map(u => u.user).join(', ') + ')' : '(disabled)'));
});
});
+1 -1
View File
@@ -47,7 +47,7 @@ compose 已通过 `VIRTUAL_HOST` / `VIRTUAL_PORT` / `CERT_NAME` 接入 nginx-pro
}
}
```
- 认证交给 nginx-proxy(htpasswd)或在此 config 里启用内置 `auth`(见 config.example.yml 注释),二选一即可。
- 认证建议直接在 `config.yml` 配置多用户登录(`auth.users`,见 config.example.yml 注释):登录页 `/login`,会话 token 走 HttpOnly cookie。不建议再用 nginx-proxy 的 htpasswd basic auth:手机浏览器原生下载不会携带 Basic 认证头,会导致下载失败;cookie 则会自动携带。若迁移到内置登录,记得去掉 nginx 上对应的 htpasswd 配置。
## 4. 升级流程
+23
View File
@@ -0,0 +1,23 @@
// 认证与授权中间件
const jwt = require('jsonwebtoken');
const JWT_SECRET = process.env.JWT_SECRET || 'xiaocai-secret-2024';
function authMiddleware(req, res, next) {
const authHeader = req.headers.authorization;
if (!authHeader) return res.status(401).json({ error: '未登录' });
const token = authHeader.split(' ')[1];
try {
const decoded = jwt.verify(token, JWT_SECRET);
req.user = decoded;
next();
} catch (e) {
res.status(401).json({ error: '登录已过期' });
}
}
function adminOnly(req, res, next) {
if (!req.user.isAdmin) return res.status(403).json({ error: '仅管理员可执行此操作' });
next();
}
module.exports = { authMiddleware, adminOnly, JWT_SECRET };
+255
View File
@@ -0,0 +1,255 @@
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>小财记账</title>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<meta name="theme-color" content="#1e3c72">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<link rel="stylesheet" href="/css/style.css">
</head>
<body>
<div class="app" id="app">
<!-- 登录 -->
<div id="login-page" class="modal-overlay">
<div class="modal">
<h2>登录小财记账</h2>
<input type="text" id="login-user" placeholder="用户名">
<input type="password" id="login-pass" placeholder="密码">
<button class="primary-btn" onclick="login()" style="width:100%;">登录</button>
<p id="login-error" style="color:red; margin-top:8px;"></p>
<div class="version" id="version-text"></div>
</div>
</div>
<!-- 主界面 -->
<div id="main-page" class="hidden" style="display:flex; flex-direction:column; height:100%;">
<!-- 群聊列表页 -->
<div id="list-page" style="display:flex; flex-direction:column; height:100%;">
<div class="header">
<div class="header-left" onclick="Store.logout()">
<svg width="24" height="24" viewBox="0 0 24 24" stroke="#fff" fill="none" stroke-width="1.5">
<rect x="3" y="3" width="18" height="18" rx="3"/><line x1="9" y1="9" x2="15" y2="9"/><line x1="9" y1="13" x2="15" y2="13"/><line x1="9" y1="17" x2="12" y2="17"/>
</svg>
<h2>小财记账</h2>
</div>
<div style="display:flex; gap:2px;">
<button class="icon-btn visible" id="create-room-btn" onclick="openCreateRoom()" title="新建群聊">
<svg viewBox="0 0 24 24"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>
</button>
</div>
</div>
<div class="chat-list" id="chat-list-container"></div>
<div class="summary-card" onclick="openSummary()">
<div>
<h4>采购汇总</h4>
<div class="summary-preview" id="summary-preview">加载中...</div>
</div>
<svg width="20" height="20" viewBox="0 0 24 24" stroke="#888" fill="none" stroke-width="2"><polyline points="9 18 15 12 9 6"></polyline></svg>
</div>
</div>
<!-- 采购清单页 -->
<div id="purchase-page" class="hidden" style="display:flex; flex-direction:column; height:100%;">
<div class="header">
<button class="icon-btn back-btn" onclick="showList()">
<svg viewBox="0 0 24 24"><polyline points="15 18 9 12 15 6"></polyline></svg>
</button>
<span class="chat-title" id="purchase-page-title">采购清单</span>
<button class="icon-btn" onclick="openChatFromPurchase()" title="聊天">
<svg viewBox="0 0 24 24"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path></svg>
</button>
</div>
<div class="purchase-panel-body" id="purchase-panel-body"></div>
<!-- 新建采购输入栏 -->
<div class="input-area">
<label class="file-upload-btn" title="上传图片">
<input type="file" id="purchase-file-input" accept="image/*" multiple style="display:none;" onchange="handlePurchaseFileSelect(event)">
<svg viewBox="0 0 24 24"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><circle cx="8.5" cy="8.5" r="1.5"></circle><polyline points="21 15 16 10 5 21"></polyline></svg>
</label>
<textarea id="purchase-msg-input" placeholder="输入采购信息..." rows="1"></textarea>
<button class="send-btn" onclick="sendFromPurchase()">
<svg viewBox="0 0 24 24"><line x1="22" y1="2" x2="11" y2="13"></line><polygon points="22 2 15 22 11 13 2 9 22 2"></polygon></svg>
</button>
</div>
</div>
<!-- 聊天窗口 -->
<div id="chat-page" class="chat-window hidden">
<div class="chat-header">
<button class="icon-btn back-btn" onclick="backToPurchase()">
<svg viewBox="0 0 24 24"><polyline points="15 18 9 12 15 6"></polyline></svg>
</button>
<span class="chat-title" id="current-chat-name"></span>
<button class="icon-btn" onclick="backToPurchase()" title="关闭聊天">
<svg viewBox="0 0 24 24"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
</button>
</div>
<div class="messages" id="messages-container"></div>
<div class="input-area">
<label class="file-upload-btn" title="上传图片">
<input type="file" id="file-input" accept="image/*" multiple style="display:none;" onchange="handleFileSelect(event)">
<svg viewBox="0 0 24 24"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><circle cx="8.5" cy="8.5" r="1.5"></circle><polyline points="21 15 16 10 5 21"></polyline></svg>
</label>
<textarea id="msg-input" placeholder="输入消息..." rows="1"></textarea>
<button class="send-btn" onclick="sendMessage()">
<svg viewBox="0 0 24 24"><line x1="22" y1="2" x2="11" y2="13"></line><polygon points="22 2 15 22 11 13 2 9 22 2"></polygon></svg>
</button>
</div>
</div>
</div>
<!-- 弹窗 -->
<div id="create-modal" class="modal-overlay hidden" onclick="if(event.target===this)closeCreateModal()">
<div class="modal">
<button class="modal-close-btn" onclick="closeCreateModal()">
<svg viewBox="0 0 24 24"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
</button>
<h3>新建项目群聊</h3>
<input type="text" id="new-room-name" placeholder="群聊名称">
<input type="text" id="white-list" placeholder="白名单成员(逗号分隔,留空全员可见)">
<button class="primary-btn" onclick="confirmCreateRoom()">创建</button>
</div>
</div>
<div id="manage-modal" class="modal-overlay hidden" onclick="if(event.target===this)closeManageModal()">
<div class="modal">
<button class="modal-close-btn" onclick="closeManageModal()">
<svg viewBox="0 0 24 24"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
</button>
<h3 id="manage-title">编辑群聊</h3>
<input type="text" id="manage-room-name" placeholder="群聊名称">
<input type="text" id="manage-white-list" placeholder="白名单成员(逗号分隔)">
<button class="primary-btn" onclick="saveRoom()">保存</button>
<button class="close-modal" style="background:#e53e3e;color:#fff;margin-top:8px;" onclick="deleteRoom()">删除群聊</button>
</div>
</div>
<!-- 采购汇总弹窗 -->
<div id="summary-modal" class="modal-overlay hidden" onclick="if(event.target===this)closeSummaryModal()">
<div class="modal">
<button class="modal-close-btn" onclick="closeSummaryModal()">
<svg viewBox="0 0 24 24"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
</button>
<h3 id="summary-title"></h3>
<div id="summary-content"></div>
</div>
</div>
<!-- 采购详情编辑弹窗 -->
<div id="detail-modal" class="modal-overlay hidden" onclick="if(event.target===this)closeDetailModal()">
<div class="modal detail-modal">
<div class="detail-header">
<input type="text" id="edit-item" class="detail-title-input" placeholder="物品名称">
<button class="icon-btn" onclick="closeDetailModal()">
<svg viewBox="0 0 24 24"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
</button>
</div>
<div class="edit-form">
<!-- 金额组:折叠 -->
<div class="edit-group">
<div class="edit-group-summary" onclick="toggleEditGroup('amount-group')">
<label>金额</label>
<span id="amount-summary">0</span>
<svg class="group-arrow" viewBox="0 0 24 24"><polyline points="6 9 12 15 18 9"></polyline></svg>
</div>
<div class="edit-group-detail hidden" id="amount-group">
<div class="edit-row"><label>数量</label><input type="number" id="edit-quantity" inputmode="decimal" min="0" step="1" oninput="updateAmountSummary()"></div>
<div class="edit-row"><label>单价</label><input type="number" id="edit-unit-price" inputmode="decimal" min="0" step="0.01" oninput="updateAmountSummary()"></div>
<div class="edit-row"><label>邮费</label><input type="number" id="edit-freight" inputmode="decimal" min="0" step="0.01" oninput="updateAmountSummary()"></div>
</div>
</div>
<!-- 状态组:折叠 -->
<div class="edit-group">
<div class="edit-group-summary" onclick="toggleEditGroup('status-group')">
<label>状态</label>
<span id="status-summary">待付款</span>
<svg class="group-arrow" viewBox="0 0 24 24"><polyline points="6 9 12 15 18 9"></polyline></svg>
</div>
<div class="edit-group-detail hidden" id="status-group">
<div class="edit-row">
<label>付款</label>
<select id="edit-payment-method" onchange="updateStatusSummary()">
<option>未指定</option><option>支付宝</option><option>微信</option><option>银行卡</option><option>现金</option><option>对公转账</option>
</select>
</div>
<div class="edit-row">
<label>发票</label>
<select id="edit-invoice-type" onchange="updateStatusSummary()">
<option>无票</option><option>普票</option><option>专票</option>
</select>
</div>
<div class="edit-row">
<label>状态</label>
<select id="edit-status" onchange="updateStatusSummary()">
<option>待付款</option><option>已付款</option><option>已收货</option><option>已完成</option>
</select>
</div>
</div>
</div>
<div class="edit-row">
<label>申请人</label><input type="text" id="edit-applicant">
</div>
<div class="edit-row">
<label>时间</label><input type="text" id="edit-time" placeholder="yyyy/MM/dd HH:mm:ss">
</div>
<div class="edit-row">
<label>备注</label><textarea id="edit-remarks" rows="2"></textarea>
</div>
<!-- 附件 -->
<div class="edit-section">
<div class="edit-section-header">
<span>附件</span>
<label class="attach-add-btn" title="添加附件">
<input type="file" id="detail-file-input" accept="image/*" multiple style="display:none;" onchange="handleDetailFileUpload(event)">
<svg viewBox="0 0 24 24"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>
</label>
</div>
<div class="attach-gallery" id="edit-attachments"></div>
</div>
<!-- 操作历史(折叠) -->
<details class="edit-section" id="edit-history-section">
<summary class="edit-section-header history-summary"><span>操作历史</span><svg class="section-arrow" viewBox="0 0 24 24"><polyline points="6 9 12 15 18 9"/></svg></summary>
<ul class="history-list" id="edit-history"></ul>
</details>
<!-- 按钮 -->
<div class="edit-buttons">
<button class="save-btn" onclick="savePurchase()">保存</button>
<button class="danger-btn" id="delete-purchase-btn" onclick="deletePurchaseDetail()">删除</button>
</div>
</div>
</div>
</div>
</div>
<script src="/js/store.js"></script>
<script src="/js/chat.js"></script>
<script src="/js/ws.js"></script>
<script src="/js/purchases.js"></script>
<script src="/js/auth.js"></script>
<script>
// 版本号
(function() {
document.getElementById('version-text').textContent = 'v3.0.1-260829';
})();
document.addEventListener('input', function(e) {
if (e.target.id === 'msg-input' || e.target.id === 'purchase-msg-input') {
e.target.style.height = 'auto';
e.target.style.height = e.target.scrollHeight + 'px';
}
});
document.addEventListener('keydown', function(e) {
if (e.target.id === 'msg-input' && e.key === 'Enter' && !e.ctrlKey) { e.preventDefault(); sendMessage(); }
if (e.target.id === 'purchase-msg-input' && e.key === 'Enter' && !e.ctrlKey) { e.preventDefault(); sendFromPurchase(); }
});
init();
</script>
</body>
</html>