From 28af756b82ace863188d94343a3522cba4aa06d7 Mon Sep 17 00:00:00 2001 From: sgp Date: Wed, 4 Nov 2026 18:43:00 +0800 Subject: [PATCH] =?UTF-8?q?feat(auth):=20=E6=96=B0=E5=A2=9E=E7=AB=99?= =?UTF-8?q?=E7=82=B9=E7=99=BB=E5=BD=95=EF=BC=88nginx=20auth=5Frequest=20+?= =?UTF-8?q?=20scrypt=20=E5=AF=86=E7=A0=81=20+=20=E7=AD=BE=E5=90=8D=20Cooki?= =?UTF-8?q?e=EF=BC=89=EF=BC=8C=E7=99=BB=E5=BD=95=E9=A1=B5=E4=B8=8E?= =?UTF-8?q?=E9=80=80=E5=87=BA=E5=85=A5=E5=8F=A3=EF=BC=8CAPI=20=E8=B7=AF?= =?UTF-8?q?=E5=BE=84=E4=BF=9D=E6=8C=81=20Key=20=E9=89=B4=E6=9D=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- api/config.example.json | 8 +- api/deploy/set-auth.js | 46 +++++ api/server.js | 144 +++++++++++++- deploy/drawlogo-zhuig-com.conf | 36 +++- home.html | 13 ++ login.html | 350 +++++++++++++++++++++++++++++++++ 6 files changed, 590 insertions(+), 7 deletions(-) create mode 100644 api/deploy/set-auth.js create mode 100644 login.html diff --git a/api/config.example.json b/api/config.example.json index 1819047..2bde56d 100644 --- a/api/config.example.json +++ b/api/config.example.json @@ -8,5 +8,11 @@ "maxLimit": 100, "corsOrigin": "*", "trustProxy": true, - "adminToken": "" + "adminToken": "", + "auth": { + "username": "", + "passwordHash": "", + "secret": "", + "maxAgeDays": 7 + } } diff --git a/api/deploy/set-auth.js b/api/deploy/set-auth.js new file mode 100644 index 0000000..def52cb --- /dev/null +++ b/api/deploy/set-auth.js @@ -0,0 +1,46 @@ +#!/usr/bin/env node +/** + * 设置站点登录帐号(写入 config.json,密码只存 scrypt 哈希) + * + * 用法: + * node deploy/set-auth.js + * node deploy/set-auth.js admin 'admin123&aa' + * + * 说明: + * - 会保留现有 auth.secret(已有会话不失效);首次运行自动生成 + * - 修改后需重启服务:sudo systemctl restart drawlogo-api + */ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const crypto = require('crypto'); + +const username = process.argv[2]; +const password = process.argv[3]; + +if (!username || !password) { + console.error('用法: node deploy/set-auth.js '); + process.exit(1); +} + +const file = path.join(__dirname, '..', 'config.json'); +if (!fs.existsSync(file)) { + console.error('未找到 config.json,请先 cp config.example.json config.json'); + process.exit(1); +} + +const cfg = JSON.parse(fs.readFileSync(file, 'utf8')); +const salt = crypto.randomBytes(16).toString('hex'); +const hash = crypto.scryptSync(password, salt, 64).toString('hex'); + +cfg.auth = cfg.auth || {}; +cfg.auth.username = username; +cfg.auth.passwordHash = 'scrypt$' + salt + '$' + hash; +cfg.auth.secret = cfg.auth.secret || crypto.randomBytes(32).toString('hex'); +cfg.auth.maxAgeDays = cfg.auth.maxAgeDays || 7; + +fs.writeFileSync(file, JSON.stringify(cfg, null, 2)); +try { fs.chmodSync(file, 0o600); } catch (e) { /* Windows 忽略 */ } + +console.log('已设置登录帐号: ' + username + '(scrypt 哈希已写入 config.json)'); diff --git a/api/server.js b/api/server.js index c71831d..4b2f784 100644 --- a/api/server.js +++ b/api/server.js @@ -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'); } diff --git a/deploy/drawlogo-zhuig-com.conf b/deploy/drawlogo-zhuig-com.conf index 459b857..6afffab 100644 --- a/deploy/drawlogo-zhuig-com.conf +++ b/deploy/drawlogo-zhuig-com.conf @@ -1,4 +1,4 @@ -# 画个标 - drawlogo.zhuig.com(纯静态站,无后端) +# 画个标 - drawlogo.zhuig.com(纯静态站 + 素材 API + 站点登录) server { listen 80; listen [::]:80; @@ -34,23 +34,49 @@ server { # 默认入口:设计中枢首页(home.html),找不到时回落到 LOGO 工作台 index home.html index.html; - # 静态资源长期缓存(带 ?v= 版本号的 JS/CSS) + # ===== 站点登录(auth_request 子请求到 Node) ===== + location = /_auth { + internal; + proxy_pass http://127.0.0.1:7891/api/v1/auth/verify; + proxy_pass_request_body off; + proxy_set_header Content-Length ""; + proxy_set_header Cookie $http_cookie; + proxy_set_header X-Real-IP $remote_addr; + } + + # 登录页、管理后台、品牌资源免系统登录 + location = /login.html { } + location = /api-admin.html { } + location ^~ /logo/ { } + + # 静态资源(需登录) location ~* \.(js|css|woff2|ttf|svg|png|jpg|jpeg|gif|ico)$ { + auth_request /_auth; + error_page 401 = @to_login; expires 30d; add_header Cache-Control "public, immutable"; } - # HTML 不缓存(保证入口页及时更新) + # HTML 不缓存(需登录) location ~* \.html$ { + auth_request /_auth; + error_page 401 = @to_login; add_header Cache-Control "no-cache, no-store, must-revalidate"; } - # 默认首页 + # 默认首页(需登录) location / { + auth_request /_auth; + error_page 401 = @to_login; try_files $uri $uri/ $uri/index.html =404; } + location @to_login { + return 302 /login.html?next=$uri; + } + # 素材 API 反代(必须 ^~:否则 /api/.../*.svg 会被上面的 \.svg$ 正则截走) + # 不启用系统登录:外部项目用 API Key 鉴权 location ^~ /api/ { proxy_pass http://127.0.0.1:7891; proxy_set_header Host $host; @@ -65,4 +91,4 @@ server { access_log /var/log/nginx/drawlogo_zhuig_access.log; error_log /var/log/nginx/drawlogo_zhuig_error.log; -} \ No newline at end of file +} diff --git a/home.html b/home.html index 4164f63..4ebfee3 100644 --- a/home.html +++ b/home.html @@ -27,6 +27,7 @@ API 进入设计工作台 + @@ -337,6 +338,18 @@ // 本地静态预览没有 /api/ 服务,直接跳过探测,避免控制台出现 ERR_ABORTED var IS_LOCAL = /^(localhost|127\.0\.0\.1|\[::1\])$/.test(location.hostname); + var API_BASE = IS_LOCAL ? 'http://127.0.0.1:7891' : ''; + + // 退出登录 + var logoutBtn = $('#btn-logout'); + if (logoutBtn) { + logoutBtn.addEventListener('click', function () { + logoutBtn.disabled = true; + fetch(API_BASE + '/api/v1/auth/logout', { method: 'POST', credentials: 'include' }) + .catch(function () { /* 忽略 */ }) + .then(function () { location.href = 'login.html'; }); + }); + } if (IS_LOCAL) { setApi('idle', '本地'); diff --git a/login.html b/login.html new file mode 100644 index 0000000..236ace2 --- /dev/null +++ b/login.html @@ -0,0 +1,350 @@ + + + + + + +登录 · 画个标 + + + + + + + + +