feat: require standalone admin login before the web workbench

This commit is contained in:
AttilaNet
2026-11-10 19:03:22 +08:00
parent 664db51d3b
commit 0230a933b0
12 changed files with 710 additions and 41 deletions
+25 -12
View File
@@ -3,7 +3,7 @@ import {el, $, $$, clone, getPath, setPath, pathKey, textValue, number, chinaTim
import {PageView, PAGES} from './pages.js';
import {notice, dialog, confirm, filePicker, fileBase64} from './ui.js';
const state = {accounts:new Map(),active:null,schema:null,meta:null,ready:false,polling:false,seq:0};
const state = {accounts:new Map(),active:null,schema:null,meta:null,ready:false,polling:false,seq:0,redirecting:false};
const current = () => state.accounts.get(state.active);
const currentPage = () => { const account=current(); return account?.pages.get(account.page); };
const terminal = new Set(['succeeded','failed','cancelled']);
@@ -16,7 +16,7 @@ function makeAccount(summary) {
}
function setStatus(message) { $('#status-text').textContent=message; $('#status-text').title=message; }
function error(error) { notice(error.message || String(error),true); setStatus(error.message || String(error)); }
function error(error) { if(state.redirecting)return;notice(error.message || String(error),true); setStatus(error.message || String(error)); }
function renderAccountTabs() {
const root=$('#account-tabs');
@@ -304,7 +304,7 @@ async function command(name,account=current()) {
if(name==='add-account'||name==='add-demo')return await addAccount(name==='add-demo');
if(name==='about')return dialog('关于牧场助手',el('div',{},el('p',{text:`牧羊人之心牧场助手 Web ${state.meta?.version || '2.0.0.dev1'}`}),el('p',{text:`游戏数据版本 ${state.meta?.gameVersion || '1.9.68'}`}),el('p',{class:'info-note',text:'与桌面助手共用核心策略。配置在服务端自动保存;运行开关在重启和恢复会话后保持关闭。'})),{info:true});
if(name==='updates')return await showUpdates();
if(name==='admin-logout'){await api.logout();state.ready=false;location.reload();return;}
if(name==='admin-logout'){hideWorkbench();try{await api.logout();}finally{requireAuth();}return;}
if(!account)throw new Error('请先新增或选择账号。');
if(name==='debug'){account.logs.debug=!account.logs.debug;account.logs.entries=[];account.logs.next=0;account.logs.generation=(account.logs.generation || 0)+1;$('#debug-log').checked=account.logs.debug;setLogVisible(true);renderLogs(true);await fetchLogs(account);return;}
if(name==='save'){await flushConfig(account);notice('策略已保存。');return;}
@@ -464,21 +464,33 @@ async function tick() {
if(!state.ready||state.polling)return;state.polling=true;
try{
const account=current();await Promise.allSettled([syncAccounts(),...([...state.accounts.values()].flatMap(item=>[...item.jobs.values()].map(job=>pollJob(item,job))))]);
if(account&&state.accounts.has(account.id)){fetchLogs(account);const page=account.pages.get(account.page);if(page&&Date.now()-(page.lastLoad||0)>4000)loadPage(page);}
if(state.ready&&account&&state.accounts.has(account.id)){fetchLogs(account);const page=account.pages.get(account.page);if(page&&Date.now()-(page.lastLoad||0)>4000)loadPage(page);}
}finally{state.polling=false;}
}
async function requireAuth() {
state.ready=false;const root=$('#auth-dialog');if(!root.open)root.showModal();$('#admin-password').focus();
function hideWorkbench() {
state.ready=false;
$('#app').hidden=true;$('#notice').hidden=true;
$$('dialog[open]').forEach(root=>root.close());
$$('.context-menu').forEach(root=>root.remove());
$$('input[type="password"]').forEach(input=>input.value='');
state.accounts.forEach(account=>{clearTimeout(account.saveTimer);account.pages.forEach(page=>clearTimeout(page.loadTimer));});
}
function requireAuth() {
if(state.redirecting)return;
state.redirecting=true;hideWorkbench();location.replace('/login');
}
async function bootstrap() {
try{
const auth=await api.auth();if(auth.required&&!auth.authenticated){requireAuth();return;}
const auth=await api.auth();if(state.redirecting)return;if(auth.required&&!auth.authenticated){requireAuth();return;}
$('#app').hidden=false;
const [meta,schema]=await Promise.all([api.meta(),api.schema()]);state.meta=meta;state.schema=schema;
if(state.redirecting)return;
$('#app-version').textContent=meta.version || '2.0.0.dev1';$('#game-version').textContent=meta.gameVersion || '1.9.68';$('#access-mode').textContent=auth.access_mode==='local'||auth.access_mode==='loopback'?'本机工作台':auth.required?'管理工作台':'本机工作台';
await syncAccounts();state.ready=true;setStatus('工作台已连接');
}catch(failure){setStatus(failure.message);$('#page-host').replaceChildren(el('div',{class:'initial-state'},el('p',{text:failure.message}),el('button',{text:'重新连接',onClick:bootstrap})));}
await syncAccounts();if(state.redirecting)return;state.ready=true;setStatus('工作台已连接');
}catch(failure){if(failure.status===401||$('#app').hidden){requireAuth();return;}if(state.redirecting)return;setStatus(failure.message);$('#page-host').replaceChildren(el('div',{class:'initial-state'},el('p',{text:failure.message}),el('button',{text:'重新连接',onClick:bootstrap})));}
}
PAGES.forEach(([key,label])=>$('#page-tabs').append(el('button',{type:'button',class:'page-tab',role:'tab','data-page':key,'aria-selected':String(key==='login'),tabindex:key==='login'?0:-1,text:label,onClick:()=>selectPage(key)})));
@@ -503,9 +515,10 @@ $('#log-resizer').addEventListener('pointerdown',event=>{resize={y:event.clientY
$('#log-resizer').addEventListener('pointermove',event=>{if(resize)setLogHeight(resize.height+resize.y-event.clientY);});
$('#log-resizer').addEventListener('pointerup',()=>{if(!resize)return;resize=null;const account=current();if(account?.config)editConfig(account,['log_sizes'],[$('#workspace').clientHeight,Number($('#log-resizer').getAttribute('aria-valuenow'))]);});
$('#log-resizer').addEventListener('keydown',event=>{if(!['ArrowUp','ArrowDown','Home','End'].includes(event.key))return;event.preventDefault();const height=Number(event.currentTarget.getAttribute('aria-valuenow'));const next=setLogHeight(event.key==='Home'?64:event.key==='End'?480:height+(event.key==='ArrowUp'?16:-16));if(current()?.config)editConfig(current(),['log_sizes'],[$('#workspace').clientHeight,next]);});
$('#auth-form').addEventListener('submit',async event=>{event.preventDefault();const input=$('#admin-password');const password=input.value;input.value='';const button=$('button',event.currentTarget);button.disabled=true;try{await api.login(password);$('#auth-dialog').close();$('#auth-error').hidden=true;await bootstrap();}catch(failure){$('#auth-error').textContent=failure.message;$('#auth-error').hidden=false;input.focus();}finally{button.disabled=false;}});
$('#auth-dialog').addEventListener('cancel',event=>event.preventDefault());window.addEventListener('auth-required',requireAuth);
window.addEventListener('beforeunload',event=>{if([...state.accounts.values()].some(account=>account.edits.size||account.savePromise)){event.preventDefault();event.returnValue='';}});
window.addEventListener('auth-required',requireAuth);
window.addEventListener('pagehide',hideWorkbench);
window.addEventListener('pageshow',event=>{if(event.persisted){state.redirecting=false;bootstrap();}});
window.addEventListener('beforeunload',event=>{if(!state.redirecting&&[...state.accounts.values()].some(account=>account.edits.size||account.savePromise)){event.preventDefault();event.returnValue='';}});
setInterval(()=>{$('#clock').textContent=new Date().toLocaleTimeString('zh-CN',{hour12:false});},1000);
setInterval(tick,1000);
bootstrap();
+1 -2
View File
@@ -10,7 +10,7 @@
<script type="module" src="/static/app.js"></script>
</head>
<body>
<div id="app" class="workbench" aria-label="牧羊人之心牧场助手">
<div id="app" class="workbench" aria-label="牧羊人之心牧场助手" hidden>
<header class="window-header">
<nav id="menu-bar" class="menu-bar" aria-label="主菜单">
<details class="menu"><summary accesskey="a">账号<span class="access-key">(A)</span></summary><div class="menu-popup">
@@ -44,7 +44,6 @@
</div>
<div id="notice" class="notice" role="status" hidden></div>
<dialog id="action-dialog" aria-labelledby="dialog-title"><form id="dialog-form"><header class="dialog-header"><h1 id="dialog-title"></h1><button type="button" class="dialog-close" aria-label="关闭对话框">×</button></header><div id="dialog-content" class="dialog-content"></div><p id="dialog-error" class="error-text" role="alert" hidden></p><footer class="dialog-footer"><button type="button" id="dialog-cancel">取消</button><button type="submit" id="dialog-confirm" class="primary">确认</button></footer></form></dialog>
<dialog id="auth-dialog" aria-labelledby="auth-title"><form id="auth-form"><h1 id="auth-title">登录管理工作台</h1><p>请输入此 Web 工作台的管理密码。</p><label class="field">管理密码<input id="admin-password" type="password" autocomplete="current-password" required></label><p id="auth-error" class="error-text" role="alert" hidden></p><div class="dialog-footer"><button type="submit" class="primary">登录</button></div></form></dialog>
<noscript>此工作台需要启用 JavaScript 才能连接本地服务。</noscript>
</body>
</html>
+26
View File
@@ -0,0 +1,26 @@
:root {
font-family: "Segoe UI", "Microsoft YaHei UI", "Microsoft YaHei", system-ui, sans-serif;
font-size: 13px;
color: #202832;
background: #f1f3f5;
font-synthesis: none;
color-scheme: light;
}
* { box-sizing: border-box; }
[hidden] { display: none !important; }
body { margin: 0; min-height: 100dvh; display: grid; place-items: center; padding: 24px 16px; }
.admin-login { width: 100%; max-width: 370px; padding: 24px; background: #fff; border: 1px solid #cbd1d8; border-radius: 5px; }
h1 { margin: 0 0 12px; font-size: 18px; font-weight: 600; }
p { margin: 0; line-height: 1.65; overflow-wrap: anywhere; }
#auth-description { color: #55616e; margin-bottom: 20px; }
form { display: flex; flex-direction: column; gap: 8px; }
input, button { font: inherit; min-width: 0; min-height: 36px; padding: 7px 10px; border: 1px solid #afb8c2; border-radius: 3px; }
input { width: 100%; background: #fff; color: inherit; caret-color: #245d9b; }
button { margin-top: 8px; background: #245d9b; color: #fff; border-color: #245d9b; cursor: pointer; }
button:hover { background: #1c4d83; }
button:disabled { cursor: default; opacity: .58; }
input:focus-visible, button:focus-visible { outline: 2px solid #245d9b; outline-offset: 2px; }
#auth-status { color: #55616e; }
#auth-error { color: #99251e; white-space: pre-wrap; }
noscript { display: block; margin-top: 16px; line-height: 1.65; }
::selection { background: #c5dbf5; color: #142b46; }
+26
View File
@@ -0,0 +1,26 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light">
<title>管理登录 · 牧羊人之心牧场助手</title>
<link rel="icon" href="data:,">
<link rel="stylesheet" href="/static/login.css">
<script type="module" src="/static/login.js"></script>
</head>
<body>
<main class="admin-login" aria-labelledby="auth-title">
<h1 id="auth-title">登录管理工作台</h1>
<p id="auth-description">请输入此 Web 工作台的管理密码。</p>
<form id="auth-form" method="post" action="/api/auth/login" aria-describedby="auth-description">
<label for="admin-password">管理密码</label>
<input id="admin-password" name="password" type="password" autocomplete="current-password" required aria-describedby="auth-error" disabled>
<p id="auth-status" role="status">正在检查登录状态…</p>
<p id="auth-error" role="alert" hidden></p>
<button type="submit" disabled>登录</button>
</form>
<noscript>请启用 JavaScript 后登录管理工作台。</noscript>
</main>
</body>
</html>
+99
View File
@@ -0,0 +1,99 @@
const form = document.querySelector('#auth-form');
const input = document.querySelector('#admin-password');
const button = form.querySelector('button[type="submit"]');
const status = document.querySelector('#auth-status');
const error = document.querySelector('#auth-error');
let busy = false;
let leaving = false;
function setBusy(value, message = '') {
busy = value;
input.disabled = value;
button.disabled = value;
form.setAttribute('aria-busy', String(value));
status.textContent = message;
status.hidden = !message;
}
function showError(message) {
error.textContent = message;
error.hidden = false;
}
function openWorkbench() {
leaving = true;
input.value = '';
setBusy(true, '正在进入工作台…');
location.replace('/');
}
async function authRequest(path, body) {
let response;
try {
response = await fetch(path, {
method: body === undefined ? 'GET' : 'POST',
credentials: 'same-origin',
cache: 'no-store',
headers: body === undefined ? {Accept: 'application/json'} : {Accept: 'application/json', 'Content-Type': 'application/json'},
body,
});
} catch {
throw new Error('无法连接 Web 服务,请检查服务是否仍在运行后重试。');
}
const data = await response.json().catch(() => null);
if (!response.ok) {
const message = typeof data?.detail === 'string' ? data.detail : data?.error?.message;
throw new Error(message || `请求未完成(HTTP ${response.status}),请重试。`);
}
if (!data || typeof data.required !== 'boolean' || typeof data.authenticated !== 'boolean') {
throw new Error('无法确认登录状态,请重试。');
}
return data;
}
async function checkAuth() {
setBusy(true, '正在检查登录状态…');
error.hidden = true;
try {
const auth = await authRequest('/api/auth/status');
if (!auth.required || auth.authenticated) openWorkbench();
} catch (failure) {
showError(failure.message);
} finally {
if (!leaving) {
setBusy(false);
input.focus();
}
}
}
form.addEventListener('submit', async event => {
event.preventDefault();
if (busy || leaving || !form.reportValidity()) return;
const body = JSON.stringify({password: input.value});
input.value = '';
error.hidden = true;
setBusy(true, '正在登录…');
try {
const auth = await authRequest('/api/auth/login', body);
if (!auth.required || auth.authenticated) openWorkbench();
else showError('登录未完成,请重新输入管理密码。');
} catch (failure) {
showError(failure.message);
} finally {
if (!leaving) {
setBusy(false);
input.focus();
}
}
});
window.addEventListener('pagehide', () => { input.value = ''; });
window.addEventListener('pageshow', event => {
if (event.persisted) {
leaving = false;
input.value = '';
checkAuth();
}
});
checkAuth();