feat(auth): 新增站点登录(nginx auth_request + scrypt 密码 + 签名 Cookie),登录页与退出入口,API 路径保持 Key 鉴权

This commit is contained in:
sgp
2026-11-04 18:43:00 +08:00
parent ca75da8589
commit 28af756b82
6 changed files with 590 additions and 7 deletions
+7 -1
View File
@@ -8,5 +8,11 @@
"maxLimit": 100,
"corsOrigin": "*",
"trustProxy": true,
"adminToken": ""
"adminToken": "",
"auth": {
"username": "",
"passwordHash": "",
"secret": "",
"maxAgeDays": 7
}
}
+46
View File
@@ -0,0 +1,46 @@
#!/usr/bin/env node
/**
* 设置站点登录帐号(写入 config.json,密码只存 scrypt 哈希)
*
* 用法:
* node deploy/set-auth.js <username> <password>
* 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 <username> <password>');
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)');
+143 -1
View File
@@ -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');
}
+30 -4
View File
@@ -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;
+13
View File
@@ -27,6 +27,7 @@
<i class="api-dot"></i><span class="api-text">API</span>
</span>
<a class="hub-btn primary" href="index.html" data-nav>进入设计工作台 <span aria-hidden="true">→</span></a>
<button class="hub-btn" id="btn-logout" title="退出登录">退出</button>
</div>
</header>
@@ -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', '本地');
+350
View File
@@ -0,0 +1,350 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" type="image/svg+xml" href="logo/favicon.svg">
<title>登录 · 画个标</title>
<style>
:root {
--primary: #4f46e5;
--primary-dark: #4338ca;
--bg: #f3f4f6;
--panel: #fff;
--border: #e5e7eb;
--text: #1f2937;
--text-dim: #6b7280;
--text-faint: #9ca3af;
--danger: #dc2626;
--font: "PingFang SC", "Microsoft YaHei", "Segoe UI", sans-serif;
--mono: ui-monospace, "SFMono-Regular", "JetBrains Mono", Consolas, monospace;
}
* { box-sizing: border-box; }
html, body { margin: 0; padding: 0; height: 100%; }
body {
font-family: var(--font);
color: var(--text);
background: var(--bg);
background-image:
radial-gradient(1000px 520px at 8% -10%, rgba(79,70,229,.14), transparent 60%),
radial-gradient(760px 420px at 96% 8%, rgba(14,165,233,.10), transparent 62%);
background-repeat: no-repeat;
-webkit-font-smoothing: antialiased;
}
a { color: inherit; text-decoration: none; }
.login {
display: grid;
grid-template-columns: 1.05fr .95fr;
min-height: 100vh;
}
/* 左:品牌与能力 */
.brand-side {
display: flex;
flex-direction: column;
justify-content: space-between;
padding: 44px 56px;
}
.brand {
display: flex;
align-items: center;
gap: 10px;
}
.brand img { display: block; }
.brand-name { font-size: 18px; font-weight: 700; letter-spacing: .3px; }
.brand-tag {
padding: 2px 8px; font-size: 11px; color: var(--primary);
background: #eef2ff; border-radius: 999px;
}
.pitch { max-width: 440px; }
.pitch h1 {
font-size: 32px;
line-height: 1.35;
letter-spacing: -.5px;
font-weight: 700;
}
.pitch h1 span { color: var(--primary); }
.pitch p {
margin-top: 14px;
font-size: 13.5px;
line-height: 1.85;
color: var(--text-dim);
}
.facts {
display: flex;
flex-wrap: wrap;
gap: 10px;
margin-top: 26px;
}
.fact {
padding: 10px 14px;
background: rgba(255,255,255,.72);
border: 1px solid var(--border);
border-radius: 10px;
}
.fact b {
display: block;
font-size: 17px;
font-weight: 650;
font-variant-numeric: tabular-nums;
}
.fact span { font-size: 11px; color: var(--text-faint); }
.copy { font-size: 11.5px; color: var(--text-faint); }
/* 右:登录卡 */
.form-side {
display: flex;
align-items: center;
justify-content: center;
padding: 40px 32px;
}
.card {
width: 100%;
max-width: 370px;
padding: 30px 28px;
background: var(--panel);
border: 1px solid var(--border);
border-radius: 16px;
box-shadow: 0 26px 70px -34px rgba(31, 41, 55, .38);
}
.card h2 { font-size: 20px; letter-spacing: -.2px; }
.card .sub { margin-top: 7px; font-size: 12px; color: var(--text-dim); }
.field { margin-top: 18px; }
.field label { display: block; margin-bottom: 6px; font-size: 12px; color: var(--text-dim); }
.input-wrap { position: relative; }
.field input {
width: 100%;
height: 40px;
padding: 0 12px;
font-family: inherit;
font-size: 13px;
color: var(--text);
background: #f9fafb;
border: 1px solid var(--border);
border-radius: 9px;
transition: background .15s, border-color .15s, box-shadow .15s;
}
.field input:focus {
outline: none;
background: #fff;
border-color: var(--primary);
box-shadow: 0 0 0 3px rgba(79,70,229,.12);
}
.field input::placeholder { color: var(--text-faint); }
.eye {
position: absolute;
top: 50%;
right: 6px;
transform: translateY(-50%);
width: 30px;
height: 30px;
font-size: 14px;
line-height: 1;
color: var(--text-faint);
background: transparent;
border: 0;
border-radius: 7px;
cursor: pointer;
}
.eye:hover { background: #eef2ff; color: var(--primary); }
.submit {
width: 100%;
height: 40px;
margin-top: 22px;
font-family: inherit;
font-size: 13.5px;
font-weight: 600;
color: #fff;
background: linear-gradient(135deg, var(--primary), var(--primary-dark));
border: 0;
border-radius: 9px;
cursor: pointer;
box-shadow: 0 8px 20px -10px rgba(79,70,229,.8);
transition: filter .15s, transform .15s;
}
.submit:hover { filter: brightness(1.06); }
.submit:active { transform: translateY(1px); }
.submit:disabled { opacity: .7; cursor: default; transform: none; }
.submit:focus-visible { outline: 2px solid var(--primary); outline-offset: 3px; }
.msg {
min-height: 18px;
margin-top: 12px;
font-size: 12px;
line-height: 1.5;
}
.msg.err { color: var(--danger); }
.msg.ok { color: #047857; }
.hint {
margin-top: 20px;
padding-top: 14px;
border-top: 1px solid #f1f3f5;
font-size: 11px;
line-height: 1.7;
color: var(--text-faint);
}
@media (max-width: 920px) {
.login { grid-template-columns: 1fr; }
.brand-side {
padding: 26px 24px 0;
gap: 24px;
}
.pitch h1 { font-size: 24px; }
.pitch p, .facts, .copy { display: none; }
.form-side { padding: 26px 24px 40px; align-items: flex-start; }
.card { box-shadow: 0 14px 40px -26px rgba(31,41,55,.3); }
}
@media (prefers-reduced-motion: reduce) {
* { transition: none !important; }
}
</style>
</head>
<body>
<div class="login">
<aside class="brand-side">
<a class="brand" href="login.html">
<img src="logo/logo-mark.svg" alt="" width="26" height="26">
<span class="brand-name">画个标</span>
<span class="brand-tag">智能设计</span>
</a>
<div class="pitch">
<h1>让品牌设计<br>从<span>一句话</span>开始</h1>
<p>AI 驱动的设计系统:LOGO、头像、海报、动态表情四套工作台,共用同一套素材库与设计技能。</p>
<div class="facts">
<div class="fact"><b>37 万+</b><span>开源图标</span></div>
<div class="fact"><b>130</b><span>设计技能</span></div>
<div class="fact"><b>4 套</b><span>设计工作台</span></div>
</div>
</div>
<div class="copy">© 2026 画个标 · 内部设计系统</div>
</aside>
<main class="form-side">
<form class="card" id="login-form" autocomplete="on">
<h2>登录</h2>
<p class="sub">使用管理员分配的帐号继续访问</p>
<div class="field">
<label for="username">帐号</label>
<input id="username" name="username" type="text" placeholder="admin" autocomplete="username" autocapitalize="off" spellcheck="false" required>
</div>
<div class="field">
<label for="password">密码</label>
<div class="input-wrap">
<input id="password" name="password" type="password" placeholder="请输入密码" autocomplete="current-password" required>
<button class="eye" type="button" id="btn-eye" aria-label="显示密码" title="显示密码">👁</button>
</div>
</div>
<button class="submit" type="submit" id="btn-login">登录</button>
<div class="msg" id="msg" role="status" aria-live="polite"></div>
<p class="hint">帐号由系统管理员分配。连续输错会临时限制登录,请 1 分钟后再试。</p>
</form>
</main>
</div>
<script>
(function () {
'use strict';
var IS_LOCAL = /^(localhost|127\.0\.0\.1|\[::1\])$/.test(location.hostname);
var API_BASE = IS_LOCAL ? 'http://127.0.0.1:7891' : '';
var form = document.getElementById('login-form');
var userEl = document.getElementById('username');
var passEl = document.getElementById('password');
var msgEl = document.getElementById('msg');
var btn = document.getElementById('btn-login');
function setMsg(text, kind) {
msgEl.className = 'msg' + (kind ? ' ' + kind : '');
msgEl.textContent = text || '';
}
// 只允许站内相对路径,防开放重定向
function nextUrl() {
var n = new URLSearchParams(location.search).get('next') || '';
if (n && n[0] === '/' && n[1] !== '/') return n;
return '/home.html';
}
// 已登录则直接跳转
fetch(API_BASE + '/api/v1/auth/me', { credentials: 'include' })
.then(function (r) { return r.ok ? r.json() : Promise.reject(); })
.then(function () { location.replace(nextUrl()); })
.catch(function () { /* 未登录,停留 */ });
passEl.addEventListener('input', function () { setMsg(''); });
document.getElementById('btn-eye').addEventListener('click', function () {
var show = passEl.type === 'password';
passEl.type = show ? 'text' : 'password';
this.textContent = show ? '🙈' : '👁';
this.setAttribute('aria-label', show ? '隐藏密码' : '显示密码');
});
form.addEventListener('submit', function (e) {
e.preventDefault();
var username = userEl.value.trim();
var password = passEl.value;
if (!username || !password) {
setMsg('请输入帐号与密码', 'err');
(!username ? userEl : passEl).focus();
return;
}
btn.disabled = true;
btn.textContent = '登录中…';
setMsg('');
fetch(API_BASE + '/api/v1/auth/login', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: username, password: password })
})
.then(function (res) {
return res.json().catch(function () { return {}; }).then(function (data) {
if (!res.ok || !data.ok) {
var message = (data.error && data.error.message) || '登录失败';
throw new Error(message);
}
return data;
});
})
.then(function () {
setMsg('登录成功,正在进入…', 'ok');
location.replace(nextUrl());
})
.catch(function (err) {
setMsg(err.message || '登录失败,请稍后重试', 'err');
passEl.value = '';
passEl.focus();
btn.disabled = false;
btn.textContent = '登录';
});
});
// 自动聚焦
if (!userEl.value) userEl.focus();
})();
</script>
</body>
</html>