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
+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)'));
});
});