index.ts 3.65 KB
import 'dotenv/config';
import { existsSync, readFileSync, statSync } from 'node:fs';
import { extname, join, normalize } from 'node:path';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
import { Hono } from 'hono';
import { serve } from '@hono/node-server';
import { findAccount, verifyPassword } from './auth';
import { signToken, verifyToken } from './jwt';
import { ensureBootstrapAccount } from './bootstrap';

const app = new Hono();
const PORT = Number(process.env.SERVER_PORT ?? 8787);

// 前端 vite build 产物在仓库根 dist/。生产全栈模式下由本服务同源托管。
const here = path.dirname(fileURLToPath(import.meta.url));
const DIST = path.resolve(here, '../../dist');

const MIME: Record<string, string> = {
  '.html': 'text/html; charset=utf-8',
  '.js': 'text/javascript; charset=utf-8',
  '.css': 'text/css; charset=utf-8',
  '.json': 'application/json; charset=utf-8',
  '.svg': 'image/svg+xml',
  '.png': 'image/png',
  '.ico': 'image/x-icon',
  '.woff2': 'font/woff2',
  '.woff': 'font/woff',
  '.ttf': 'font/ttf',
  '.geojson': 'application/json',
  '.map': 'application/json',
};

if (!process.env.AUTH_SECRET) {
  console.warn('[auth] 未设置 AUTH_SECRET,使用不安全的开发默认密钥;生产环境务必在 .env 配置');
}

app.get('/api/health', (c) => c.json({ ok: true }));

app.post('/api/login', async (c) => {
  let body: { username?: string; password?: string };
  try {
    body = await c.req.json();
  } catch {
    return c.json({ error: 'bad_request' }, 400);
  }
  const { username, password } = body;
  if (!username || !password) return c.json({ error: 'bad_request' }, 400);

  const acct = findAccount(username);
  // 账号不存在与密码错误返回同一错误,避免暴露账号是否存在
  if (!acct || !verifyPassword(password, acct.hash)) {
    return c.json({ error: 'invalid_credentials' }, 401);
  }
  const token = await signToken(username);
  return c.json({ token, user: { username } });
});

app.get('/api/me', async (c) => {
  const auth = c.req.header('Authorization');
  if (!auth?.startsWith('Bearer ')) return c.json({ error: 'no_token' }, 401);
  const payload = await verifyToken(auth.slice(7));
  if (!payload) return c.json({ error: 'invalid_token' }, 401);
  return c.json({ user: { username: payload.username } });
});

// 无状态 JWT:后端不留存会话,登出由前端丢弃 token 完成
app.post('/api/logout', (c) => c.json({ ok: true }));

// 生产全栈模式:同源托管前端静态产物(dist/)并兜底 SPA 路由。
// dev 下 dist 不存在,此兜底返回 503 提示先 build;/api 已由上方路由处理,不会落入此处。
app.get('*', (c) => {
  const { pathname } = new URL(c.req.url);
  if (pathname.startsWith('/api')) return c.json({ error: 'not_found' }, 404);

  const rel = pathname === '/' ? '/index.html' : pathname;
  const filePath = normalize(join(DIST, decodeURIComponent(rel)));
  if (
    !filePath.startsWith(DIST) || // 防目录穿越
    !existsSync(filePath) ||
    !statSync(filePath).isFile()
  ) {
    const index = join(DIST, 'index.html');
    if (existsSync(index)) {
      return c.body(readFileSync(index), 200, { 'Content-Type': 'text/html; charset=utf-8' });
    }
    return c.body('前端未构建:请先运行 pnpm build', 503);
  }
  const mime = MIME[extname(filePath)] ?? 'application/octet-stream';
  return c.body(readFileSync(filePath), 200, { 'Content-Type': mime });
});

// 容器首次启动:无账号文件且配了 BOOTSTRAP_USER/PASSWORD 时初始化默认账号
ensureBootstrapAccount();

serve({ fetch: app.fetch, port: PORT }, (info) => {
  console.log(`[auth] 登录服务已启动: http://localhost:${info.port}`);
});