liufumingren 78cee0fe1a feat(doc): 首页登录分流 + 文档站(简易 CMS / 静态 HTML / sitemap)
- 首页:`/` 未登录原地显示登录页(不再跳 /login),已登录直接进 `/dashboard`;
  看板路由由 `/` 迁到 `/dashboard`,侧边栏「首页」与无权限回跳同步;
  桌面端「工具 → 打开配置页」的 `/?token=` 免登录仍然可用
- 文档站:`/doc/**` 由后端整站生成静态 HTML(顶部分类 tab 全局切换、左侧栏目 → 内容页、
  右侧本页目录);`/sitemap.txt` 新链接追加到末尾,下架 / 删除的会被清理
- 平台管理 · 文档管理(`/admin/doc`):分类 / 栏目 / 内容页(Markdown)简易 CMS,
  内容页有编辑表单与列表,保存后自动重生成目录与静态页面
- 登录页右下角、顶栏(登录后)、看板右上角新增进入文档站的链接
- 部署:nginx 模板为 `/doc`、`/doc/`、`/sitemap.txt` 增加反代(否则会落到 SPA 回退);
  Vite dev server 增加同名代理;`middleware/frontend.js` 排除这些路径
- 登录页插画改为内联 SVG(沿用工作区已有的未提交改动)
- 测试:新增 Markdown 渲染单测;后端 218 个用例通过,前端 typecheck / build 通过

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-07 20:33:46 +08:00

112 lines
4.8 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const fs = require('fs');
const path = require('path');
const httpProxy = require('http-proxy');
const serve = require('koa-static');
/**
* 前端入口:**后端不再渲染任何页面**,`/` 这一侧要么反代给前端 dev server、要么托管前端构建产物
*
* - **开发(`env=local`)**:把非 `/api`、`/health` 的请求反向代理到前端 dev server
* (`config.frontend.devServer`,默认 `http://127.0.0.1:7301`,即 `frontend && npm run dev`)。
* 这样联调只开一个地址(后端 `:7300`),前端的热更新也照常生效(含 HMR 的 WebSocket 升级)。
* - **生产**:托管 `config.frontend.distDir`(默认 `../frontend/dist`)里的静态资源,
* 找不到文件且浏览器要 HTML 时回退到 `index.html`(SPA 深链刷新不会 404)。
* - **单测(`env=unittest`)**:整体跳过(不连前端、也不要求 dist 存在),
* 于是未匹配的路径还是走框架/路由自己的 404。
*
* 只接管 GET/HEAD 的「非接口」请求:`/api/*`、`/health` 一律交给后面的路由。
*/
module.exports = (options, app) => {
const cfg = app.config.frontend || {};
const env = app.config.env;
const isDev = env === 'local';
const enabled = Boolean(cfg.enable) && env !== 'unittest';
const distDir = cfg.distDir;
const indexFile = path.join(distDir, 'index.html');
// 静态中间件(生产用):只管真实文件,交给 koa-static 处理缓存/条件请求
const staticMw = enabled && !isDev ? serve(distDir, { index: false, defer: false }) : null;
if (enabled && isDev) {
app.logger.info('[frontend] dev 反代已启用: %s(页面请求转发给前端 dev server)', cfg.devServer);
// 前端 dev server 的 HMR 走 WebSocket:HTTP server 的 upgrade 事件也得转过去,
// 否则页面能打开、但改代码不会热更新(升级请求没人管会直接断开)
app.once('server', server => {
server.on('upgrade', (req, socket, head) => {
const url = String(req.url || '');
if (url.startsWith('/api/') || url === '/health') return; // 接口侧不接管
getProxy(cfg.devServer).ws(req, socket, head, { target: cfg.devServer });
});
});
} else if (enabled && staticMw) {
app.logger.info('[frontend] 静态托管已启用: %s(存在 index.html = %s)', distDir, fs.existsSync(indexFile));
}
return async function frontend(ctx, next) {
if (!enabled || !isFrontendRequest(ctx)) return next();
if (isDev) return proxyToDevServer(ctx, cfg.devServer);
// 生产:先当静态资源找,找不到再回退 index.html(SPA 路由)
await staticMw(ctx, async () => {});
if (ctx.status !== 404) return;
if (!fs.existsSync(indexFile)) {
ctx.status = 503;
ctx.type = 'html';
ctx.body = '<h1>前端还没构建</h1><p>请在 frontend/ 执行 <code>npm run build</code>(或用 FRONTEND_DIST 指定目录)。</p>';
return;
}
ctx.type = 'html';
ctx.body = fs.createReadStream(indexFile);
};
};
/** 只接管「页面」请求:非接口 + GET/HEAD;`/download/*` 是安装包静态资源,不接管 */
function isFrontendRequest(ctx) {
if (ctx.method !== 'GET' && ctx.method !== 'HEAD') return false;
if (ctx.path.startsWith('/download/')) return false;
// 文档站(/doc/**)与 sitemap 是后端生成并落盘的静态文件,不交给 SPA
if (ctx.path === '/sitemap.txt' || ctx.path === '/doc' || ctx.path.startsWith('/doc/')) return false;
return !ctx.path.startsWith('/api/') && ctx.path !== '/api' && ctx.path !== '/health';
}
/** 开发:反代到前端 dev server(含 HMR 的 WebSocket 升级) */
function proxyToDevServer(ctx, target) {
// koa 不再自己写响应,完全交给反代
ctx.respond = false;
const proxy = getProxy(target);
proxy.web(ctx.req, ctx.res, { target }, (err) => {
if (ctx.res.headersSent) return;
ctx.status = 502;
ctx.type = 'html';
ctx.body = `<h1>前端 dev server 连不上</h1><p>${err.message}</p>`
+ `<p>请先启动前端:<code>cd frontend; npm run dev</code>(目标 ${target})</p>`;
});
}
/** 按 target 缓存代理实例(同一个 target 复用连接池) */
const proxies = new Map();
function getProxy(target) {
if (proxies.has(target)) return proxies.get(target);
// ws: true —— 允许 `proxy.ws()` 把 HMR 的升级请求转过去
const proxy = httpProxy.createProxyServer({ changeOrigin: true, xfwd: true, ws: true });
proxy.on('error', (err, req, res) => {
// HTTP 请求的错误在 proxyToDevServer 的回调里处理;这里只兑底(避免 unhandled error 抛到进程)
if (res && !res.headersSent && res.writeHead) {
res.writeHead(502, { 'Content-Type': 'text/plain; charset=utf-8' });
}
void err;
});
proxies.set(target, proxy);
return proxy;
}