index.ts
7.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
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 type { Context } from 'hono';
import { serve } from '@hono/node-server';
import { getConnInfo } from '@hono/node-server/conninfo';
import { findAccount, verifyPassword } from './auth';
import { signToken, verifyToken } from './jwt';
import { ensureBootstrapAccount } from './bootstrap';
import { CaptchaRateLimited, createCaptcha, verifyCaptcha } from './captcha';
const app = new Hono();
const PORT = Number(process.env.SERVER_PORT ?? 8787);
// 前端 vite build 产物在仓库根 dist/。生产全栈模式下由本服务同源托管。
// 三层 .. 是本文件所在深度:packages/server/src → 仓库根。少一层就变成 packages/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 }));
/**
* 客户端 IP。反代在就信 `X-Forwarded-For` 的第一段(Nginx `$proxy_add_x_forwarded_for`
* 会把真实来源放最前),没有再退回 socket 地址。
*
* 为什么不一律用 socket 地址:容器里若前面挂了一层 Nginx,所有请求的来源都是那个
* 内网 IP,按 IP 限流就退化成「全站共用一个额度」,10 次失败能把所有人一起锁住。
* 为什么不一律信 XFF:没有反代时这个头是客户端随便写的,等于没限流。两种部署形态
* 都要能跑,所以先信头、再退回 socket —— 被伪造的风险由「限流只是第二层」兜底。
*/
function clientIp(c: Context): string {
const xff = c.req.header('x-forwarded-for');
if (xff) {
const first = xff.split(',')[0]?.trim();
if (first) return first;
}
try {
return getConnInfo(c).remote.address ?? 'unknown';
} catch {
return 'unknown';
}
}
/**
* 登录失败计数(第二层防线,第一层是图形验证码)。
*
* 语义:同一 IP 在 10 分钟内失败 10 次后,后续登录直接 429,直到窗口滑过去。
* 只在「密码错」时记失败,成功即清零;验证码错不算(那属于填错图,不该让人锁账号,
* 而且验证码本身就是一次性的,已经限了速率)。
*/
const LOGIN_FAIL_LIMIT = 10;
const LOGIN_FAIL_WINDOW_MS = 10 * 60 * 1000;
const loginFails = new Map<string, { count: number; resetAt: number }>();
function loginBlocked(ip: string): boolean {
const rec = loginFails.get(ip);
if (!rec) return false;
if (Date.now() >= rec.resetAt) {
loginFails.delete(ip);
return false;
}
return rec.count >= LOGIN_FAIL_LIMIT;
}
function noteLoginFail(ip: string): void {
const now = Date.now();
const rec = loginFails.get(ip);
if (!rec || now >= rec.resetAt) {
loginFails.set(ip, { count: 1, resetAt: now + LOGIN_FAIL_WINDOW_MS });
} else {
rec.count += 1;
}
}
/** 图形验证码:服务端渲染 SVG,只把 id 与图片给前端,明文码留在服务端 */
app.get('/api/captcha', (c) => {
try {
const challenge = createCaptcha(clientIp(c));
// no-store:验证码必须每次都是新的,任何一层缓存都会让人反复看到同一张图
return c.json(challenge, 200, { 'Cache-Control': 'no-store, max-age=0' });
} catch (err) {
if (err instanceof CaptchaRateLimited) {
return c.json({ error: 'too_many_requests', message: '验证码请求过于频繁,请稍后再试' }, 429);
}
throw err;
}
});
app.post('/api/login', async (c) => {
let body: {
username?: string;
password?: string;
captchaId?: string;
captchaCode?: string;
};
try {
body = await c.req.json();
} catch {
return c.json({ error: 'bad_request' }, 400);
}
const { username, password, captchaId, captchaCode } = body;
const ip = clientIp(c);
if (loginBlocked(ip)) {
return c.json({ error: 'too_many_attempts', message: '尝试次数过多,请 10 分钟后再试' }, 429);
}
// 验证码先于密码校验:这一步很便宜,且能在做 scrypt(有意慢)之前挡掉自动化请求
const verdict = verifyCaptcha(captchaId, captchaCode);
if (verdict !== 'ok') {
return c.json(
{
error: verdict === 'missing' ? 'captcha_required' : 'captcha_invalid',
message:
verdict === 'expired'
? '验证码已过期,请点击图片换一张'
: '验证码不正确,请重新输入',
},
400,
);
}
if (!username || !password) return c.json({ error: 'bad_request' }, 400);
const acct = findAccount(username);
// 账号不存在与密码错误返回同一错误,避免暴露账号是否存在
if (!acct || !verifyPassword(password, acct.hash)) {
noteLoginFail(ip);
return c.json({ error: 'invalid_credentials', message: '用户名或密码错误' }, 401);
}
loginFails.delete(ip);
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}`);
});