feat(auth): 新增站点登录(nginx auth_request + scrypt 密码 + 签名 Cookie),登录页与退出入口,API 路径保持 Key 鉴权
This commit is contained in:
+143
-1
@@ -30,7 +30,14 @@ const DEFAULT_CONFIG = {
|
||||
corsOrigin: '*',
|
||||
trustProxy: true,
|
||||
// 管理后台口令;为空则管理接口关闭
|
||||
adminToken: ''
|
||||
adminToken: '',
|
||||
// 站点登录(nginx auth_request 子请求校验);为空则登录功能关闭
|
||||
auth: {
|
||||
username: '',
|
||||
passwordHash: '',
|
||||
secret: '',
|
||||
maxAgeDays: 7
|
||||
}
|
||||
};
|
||||
|
||||
function loadConfig() {
|
||||
@@ -312,6 +319,136 @@ async function handleAdmin(req, res, pathname) {
|
||||
return fail(res, 405, 'METHOD_NOT_ALLOWED', '不支持的方法');
|
||||
}
|
||||
|
||||
/* ============================ 站点登录 ============================ */
|
||||
|
||||
const COOKIE_NAME = 'hgb_session';
|
||||
const loginBuckets = new Map();
|
||||
|
||||
/** scrypt 密码哈希:scrypt$salt$hash */
|
||||
function hashPassword(pw) {
|
||||
const salt = crypto.randomBytes(16).toString('hex');
|
||||
const hash = crypto.scryptSync(String(pw), salt, 64).toString('hex');
|
||||
return 'scrypt$' + salt + '$' + hash;
|
||||
}
|
||||
|
||||
function verifyPassword(pw, stored) {
|
||||
const parts = String(stored || '').split('$');
|
||||
if (parts.length !== 3 || parts[0] !== 'scrypt') return false;
|
||||
const calc = crypto.scryptSync(String(pw), parts[1], 64).toString('hex');
|
||||
return safeEqual(calc, parts[2]);
|
||||
}
|
||||
|
||||
function authReady() {
|
||||
const a = CONFIG.auth || {};
|
||||
return !!(a.username && a.passwordHash && a.secret);
|
||||
}
|
||||
|
||||
function signSession(payload) {
|
||||
const body = Buffer.from(JSON.stringify(payload)).toString('base64url');
|
||||
const sig = crypto.createHmac('sha256', CONFIG.auth.secret).update(body).digest('base64url');
|
||||
return body + '.' + sig;
|
||||
}
|
||||
|
||||
function verifySession(token) {
|
||||
const parts = String(token || '').split('.');
|
||||
if (parts.length !== 2) return null;
|
||||
const expect = crypto.createHmac('sha256', CONFIG.auth.secret).update(parts[0]).digest('base64url');
|
||||
if (!safeEqual(parts[1], expect)) return null;
|
||||
try {
|
||||
const p = JSON.parse(Buffer.from(parts[0], 'base64url').toString('utf8'));
|
||||
if (!p.exp || p.exp < Date.now()) return null;
|
||||
if (p.u !== CONFIG.auth.username) return null;
|
||||
return p;
|
||||
} catch (e) { return null; }
|
||||
}
|
||||
|
||||
function parseCookies(req) {
|
||||
const out = {};
|
||||
String(req.headers.cookie || '').split(';').forEach(function (s) {
|
||||
const i = s.indexOf('=');
|
||||
if (i > 0) {
|
||||
try { out[s.slice(0, i).trim()] = decodeURIComponent(s.slice(i + 1).trim()); }
|
||||
catch (e) { /* ignore */ }
|
||||
}
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
function currentSession(req) {
|
||||
return verifySession(parseCookies(req)[COOKIE_NAME]);
|
||||
}
|
||||
|
||||
function clientIp(req) {
|
||||
return String(req.headers['x-real-ip'] || req.headers['x-forwarded-for'] || req.socket.remoteAddress || '').split(',')[0].trim();
|
||||
}
|
||||
|
||||
function loginRateLimit(ip) {
|
||||
const now = Date.now();
|
||||
let b = loginBuckets.get(ip);
|
||||
if (!b || now - b.window >= 60000) { b = { window: now, count: 0 }; loginBuckets.set(ip, b); }
|
||||
b.count += 1;
|
||||
return b.count <= 8;
|
||||
}
|
||||
|
||||
function sessionCookie(req, token, maxAge) {
|
||||
const proto = String(req.headers['x-forwarded-proto'] || '').toLowerCase();
|
||||
const secure = proto === 'https';
|
||||
return COOKIE_NAME + '=' + token + '; Path=/; HttpOnly; SameSite=Lax; Max-Age=' + maxAge + (secure ? '; Secure' : '');
|
||||
}
|
||||
|
||||
async function handleAuth(req, res, pathname) {
|
||||
const method = req.method;
|
||||
|
||||
// 登录
|
||||
if (pathname === '/api/v1/auth/login' && method === 'POST') {
|
||||
if (!authReady()) return fail(res, 503, 'AUTH_DISABLED', '登录功能未启用');
|
||||
const ip = clientIp(req);
|
||||
if (!loginRateLimit(ip)) return fail(res, 429, 'TOO_MANY_ATTEMPTS', '尝试过于频繁,请 1 分钟后再试');
|
||||
|
||||
let body;
|
||||
try { body = await readJsonBody(req); }
|
||||
catch (e) { return fail(res, 400, e.code || 'BAD_REQUEST', '请求体格式错误'); }
|
||||
|
||||
const username = String(body.username || '').trim();
|
||||
const password = String(body.password || '');
|
||||
if (!username || !password) return fail(res, 400, 'BAD_REQUEST', '请输入帐号与密码');
|
||||
|
||||
const okUser = safeEqual(username, CONFIG.auth.username);
|
||||
const okPass = verifyPassword(password, CONFIG.auth.passwordHash);
|
||||
if (!okUser || !okPass) return fail(res, 401, 'BAD_CREDENTIALS', '帐号或密码错误');
|
||||
|
||||
const days = Number(CONFIG.auth.maxAgeDays) || 7;
|
||||
const maxAge = days * 24 * 3600;
|
||||
const token = signSession({ u: CONFIG.auth.username, exp: Date.now() + maxAge * 1000 });
|
||||
return send(res, 200, { ok: true, data: { username: CONFIG.auth.username } }, {
|
||||
'Set-Cookie': sessionCookie(req, token, maxAge)
|
||||
});
|
||||
}
|
||||
|
||||
// 退出
|
||||
if (pathname === '/api/v1/auth/logout' && method === 'POST') {
|
||||
return send(res, 200, { ok: true, data: { ok: true } }, {
|
||||
'Set-Cookie': sessionCookie(req, '', 0)
|
||||
});
|
||||
}
|
||||
|
||||
// 当前登录态
|
||||
if (pathname === '/api/v1/auth/me' && method === 'GET') {
|
||||
const s = currentSession(req);
|
||||
if (!s) return fail(res, 401, 'UNAUTHORIZED', '未登录');
|
||||
return ok(res, { username: s.u, expiresAt: new Date(s.exp).toISOString() });
|
||||
}
|
||||
|
||||
// nginx auth_request 子请求:200 = 放行,401 = 跳登录
|
||||
if (pathname === '/api/v1/auth/verify' && method === 'GET') {
|
||||
if (!authReady()) return fail(res, 503, 'AUTH_DISABLED', '登录功能未启用');
|
||||
if (!currentSession(req)) return fail(res, 401, 'UNAUTHORIZED', '未登录');
|
||||
return send(res, 200, '', { 'Content-Type': 'text/plain; charset=utf-8' });
|
||||
}
|
||||
|
||||
return fail(res, 404, 'NOT_FOUND', '未知认证端点');
|
||||
}
|
||||
|
||||
/* ============================ 检索 ============================ */
|
||||
|
||||
function parseLimit(v) {
|
||||
@@ -506,6 +643,11 @@ async function handle(req, res) {
|
||||
return handleAdmin(req, res, pathname);
|
||||
}
|
||||
|
||||
// 站点登录:登录/退出/登录态/nginx 子请求(免 API Key)
|
||||
if (pathname.indexOf('/api/v1/auth/') === 0) {
|
||||
return handleAuth(req, res, pathname);
|
||||
}
|
||||
|
||||
if (req.method !== 'GET') {
|
||||
return fail(res, 405, 'METHOD_NOT_ALLOWED', '仅支持 GET');
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user