diff --git a/README.md b/README.md index 4648e19..6a4d8f6 100644 --- a/README.md +++ b/README.md @@ -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`。 --- diff --git a/app/config.example.yml b/app/config.example.yml index 294beb8..896bab1 100644 --- a/app/config.example.yml +++ b/app/config.example.yml @@ -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)。 diff --git a/app/server/auth.js b/app/server/auth.js new file mode 100644 index 0000000..02966b6 --- /dev/null +++ b/app/server/auth.js @@ -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 }; diff --git a/app/server/config.js b/app/server/config.js index 3f73061..07f61df 100644 --- a/app/server/config.js +++ b/app/server/config.js @@ -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; diff --git a/app/server/public/index.html b/app/server/public/index.html index 7629ffc..75ecba6 100644 --- a/app/server/public/index.html +++ b/app/server/public/index.html @@ -21,7 +21,11 @@

Agent 任务台

-
+
+ + @@ -111,6 +115,6 @@ - + diff --git a/app/server/public/js/app.js b/app/server/public/js/app.js index c1aa4c4..bf698b3 100644 --- a/app/server/public/js/app.js +++ b/app/server/public/js/app.js @@ -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); diff --git a/app/server/public/login.html b/app/server/public/login.html new file mode 100644 index 0000000..f3b1432 --- /dev/null +++ b/app/server/public/login.html @@ -0,0 +1,71 @@ + + + + + + Agent 任务台 · 登录 + + + + + + + + + + + diff --git a/app/server/server.js b/app/server/server.js index 185ae14..7870c34 100644 --- a/app/server/server.js +++ b/app/server/server.js @@ -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)')); }); }); diff --git a/docs/DEPLOY.md b/docs/DEPLOY.md index e86d700..5bac6b0 100644 --- a/docs/DEPLOY.md +++ b/docs/DEPLOY.md @@ -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. 升级流程 diff --git a/docs/auth.js b/docs/auth.js new file mode 100644 index 0000000..ec45a48 --- /dev/null +++ b/docs/auth.js @@ -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 }; diff --git a/docs/index.html b/docs/index.html new file mode 100644 index 0000000..3ae6277 --- /dev/null +++ b/docs/index.html @@ -0,0 +1,255 @@ + + + + + + 小财记账 + + + + + + + +
+ + + + + + + + + + + + + + + + +
+ + + + + + + + +