Files
Sdf1_login/login.php
T
ypsdf1 b8ab513377 125续15l-8: 登录页协议弹窗做markdown渲染, 不再干巴巴
之前弹窗直接 textContent 端原文(裸###/裸-/裸**), 到php高度自由化了还做不出渲染
修复:
- login.php 新增 renderMarkdownLite+inlineMd+esc(与player.php同范式), 标题/列表/加粗/斜体/代码/引用/链接
- 弹窗 body 改 innerHTML 渲染, 占位文本(加载中/失败/未配置)仍用 textContent 防注入
- .ag-body white-space pre-wrap→normal, 加 markdown 渲染样式(ag-h/ag-h2/ag-h3/ag-quote/code/li)
渲染验证: player.md 标题分级/列表/加粗/代码/引用块全部正常
2026-11-20 00:34:45 +08:00

859 lines
42 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
require_once __DIR__ . '/security.php'; // 第四层:全局限流(2026-09-30)
// ★ 人机验证码(2026-10-02):按 config.php 的 CAPTCHA_PROVIDER 选择 CF/VA,密钥在 captcha_keys.php
require_once __DIR__ . '/captcha_guard.php';
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SDF1 - Web登录</title>
<style>
:root {
--bg: #0d1117; --card: #161b22; --border: #30363d;
--text: #e6edf3; --dim: #8b949e; --accent: #58a6ff;
--green: #3fb950; --red: #f85149; --yellow: #d29922;
}
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
background: var(--bg); color: var(--text);
font-family: 'Segoe UI', system-ui, sans-serif;
min-height: 100vh; display: flex; justify-content: center; align-items: center;
}
.login-card {
background: var(--card); border: 1px solid var(--border);
border-radius: 12px; padding: 40px; width: 400px; max-width: 90%;
text-align: center;
}
.login-card h1 { color: var(--accent); margin-bottom: 8px; font-size: 24px; }
.login-card .subtitle { color: var(--dim); margin-bottom: 32px; font-size: 14px; }
.status-box {
padding: 20px; border-radius: 8px; margin-bottom: 24px;
font-size: 14px; line-height: 1.8;
}
.status-box.loading { background: rgba(88,166,255,0.1); border: 1px solid var(--accent); }
.status-box.success { background: rgba(63,185,80,0.1); border: 1px solid var(--green); }
.status-box.error { background: rgba(248,81,73,0.1); border: 1px solid var(--red); }
.spinner {
display: inline-block; width: 20px; height: 20px;
border: 2px solid var(--dim); border-top-color: var(--accent);
border-radius: 50%; animation: spin 0.8s linear infinite;
vertical-align: middle; margin-right: 8px;
}
@keyframes spin { to { transform: rotate(360deg); } }
.btn {
padding: 12px 24px; border: none; border-radius: 6px;
cursor: pointer; font-size: 14px; font-weight: 600;
transition: all 0.2s; text-decoration: none; display: inline-block;
}
.btn-primary { background: var(--accent); color: #fff; }
.btn-primary:hover { background: #79c0ff; }
.btn-dim { background: var(--border); color: var(--dim); }
.btn-dim:hover { background: #484f58; color: var(--text); }
.actions { display: flex; gap: 8px; justify-content: center; }
.player-name { color: var(--green); font-weight: 600; font-size: 16px; }
/* ===== 用户协议勾选门控 ===== */
.agreement-box {
margin: 16px 0 4px; padding: 12px 14px;
background: rgba(88,166,255,0.06); border: 1px solid var(--border);
border-radius: 8px; text-align: left;
}
.agreement-box .ag-row { display: flex; align-items: flex-start; gap: 10px; }
.agreement-box input[type=checkbox] {
margin-top: 3px; width: 16px; height: 16px; flex-shrink: 0;
accent-color: var(--accent); cursor: pointer;
}
.agreement-box .ag-text { font-size: 13px; color: var(--dim); line-height: 1.6; }
.agreement-box .ag-text b { color: var(--text); }
.agreement-box .ag-link {
display: inline-block; margin-top: 6px; font-size: 12px; color: var(--accent);
cursor: pointer; text-decoration: underline;
}
.agreement-box .ag-tip { font-size: 11px; color: var(--yellow); margin-top: 6px; }
/* 阅读弹窗:滚动到底部才解锁勾选 */
.ag-modal-mask {
position: fixed; inset: 0; background: rgba(0,0,0,0.6);
display: none; align-items: center; justify-content: center; z-index: 999;
}
.ag-modal-mask.show { display: flex; }
.ag-modal {
background: var(--card); border: 1px solid var(--border); border-radius: 12px;
width: 520px; max-width: 92%; max-height: 80vh; display: flex; flex-direction: column;
overflow: hidden;
}
.ag-modal .ag-head {
padding: 14px 18px; border-bottom: 1px solid var(--border);
display: flex; justify-content: space-between; align-items: center;
}
.ag-modal .ag-head h3 { margin: 0; font-size: 15px; color: var(--accent); }
.ag-modal .ag-close { cursor: pointer; color: var(--dim); font-size: 20px; line-height: 1; }
.ag-body {
padding: 14px 18px; overflow-y: auto; flex: 1;
font-size: 13px; line-height: 1.75; color: var(--text); white-space: normal;
word-break: break-word;
}
/* 协议 markdown 渲染样式(标题/列表/加粗/引用/代码/段落) */
.ag-body h1, .ag-body .ag-h { font-size: 18px; font-weight: 700; color: var(--accent); margin: 14px 0 8px; }
.ag-body .ag-h2 { font-size: 15px; font-weight: 700; color: var(--accent); margin: 12px 0 6px; }
.ag-body .ag-h3 { font-size: 14px; font-weight: 600; color: var(--text); margin: 10px 0 5px; }
.ag-body ul { margin: 6px 0 8px 4px; padding-left: 18px; }
.ag-body li { margin: 3px 0; }
.ag-body .ag-quote { border-left: 3px solid var(--yellow); padding: 6px 12px; margin: 8px 0; background: rgba(210,153,34,0.08); border-radius: 4px; }
.ag-body code { background: rgba(136,136,136,0.2); padding: 1px 5px; border-radius: 3px; font-size: 0.9em; }
.ag-body .ag-p { margin: 4px 0; }
.ag-foot {
padding: 12px 18px; border-top: 1px solid var(--border);
display: flex; justify-content: space-between; align-items: center; gap: 10px;
}
.ag-foot .ag-progress { font-size: 12px; color: var(--dim); }
.ag-foot .ag-btn {
padding: 8px 18px; border-radius: 6px; border: none; cursor: pointer; font-size: 13px; font-weight: 600;
background: var(--accent); color: #fff;
}
.ag-foot .ag-btn:disabled { background: var(--border); color: var(--dim); cursor: not-allowed; }
</style>
</head>
<body>
<div class="login-card">
<h1>SDF1 Web登录</h1>
<p class="subtitle" id="subtitle">Token验证中...</p>
<!-- Token验证状态 -->
<div id="tokenSection">
<div id="statusBox" class="status-box loading">
<span class="spinner"></span> 正在验证登录Token...
</div>
</div>
<!-- 密码验证(Token通过后显示) -->
<div id="passwordSection" style="display:none">
<div id="pwdStatusBox" class="status-box" style="display:none"></div>
<div style="text-align:left;margin-bottom:16px">
<label style="color:var(--dim);font-size:13px;display:block;margin-bottom:4px">玩家名</label>
<input type="text" id="playerName" placeholder="玩家名" readonly
style="width:100%;padding:10px 14px;background:var(--bg);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:14px;outline:none;box-sizing:border-box;opacity:0.7">
</div>
<!-- ★ 切换标签:密码/邮箱 -->
<div style="display:flex;gap:8px;margin-bottom:16px">
<button class="btn btn-primary" id="tabPassword" onclick="switchLoginTab('password')" style="flex:1">游戏密码</button>
<button class="btn btn-dim" id="tabEmail" onclick="switchLoginTab('email')" style="flex:1">邮箱验证码</button>
</div>
<!-- 密码登录 -->
<div id="loginPasswordTab">
<div style="text-align:left;margin-bottom:20px">
<label style="color:var(--dim);font-size:13px;display:block;margin-bottom:4px">游戏内密码</label>
<input type="password" id="password" placeholder="输入游戏内密码" maxlength="32"
style="width:100%;padding:10px 14px;background:var(--bg);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:14px;outline:none;box-sizing:border-box">
<p style="color:var(--dim);font-size:12px;margin-top:8px;text-align:left">密码由游戏服务器验证,Web端不存储密码</p>
</div>
<?php echo cgWidgetHtml(); ?>
<button class="btn btn-primary" style="width:100%" onclick="doPasswordLogin()">登录到Web端</button>
</div>
<!-- 邮箱验证码登录 -->
<div id="loginEmailTab" style="display:none">
<div style="text-align:left;margin-bottom:12px">
<label style="color:var(--dim);font-size:13px;display:block;margin-bottom:4px">绑定邮箱</label>
<input type="text" id="maskedEmail" readonly placeholder="加载中..."
style="width:100%;padding:10px 14px;background:var(--bg);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:14px;outline:none;box-sizing:border-box;opacity:0.7">
</div>
<div style="display:flex;gap:8px;margin-bottom:20px">
<input type="text" id="emailCode" placeholder="6位验证码" maxlength="6"
style="flex:1;padding:10px 14px;background:var(--bg);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:14px;outline:none;box-sizing:border-box">
<button class="btn btn-primary" id="sendCodeBtn" onclick="sendEmailCode()" style="white-space:nowrap">发送验证码</button>
</div>
<button class="btn btn-primary" style="width:100%" onclick="doEmailLogin()">登录到Web端</button>
</div>
</div>
<!-- ★ 用户协议送达:勾选门控(rules 目录无协议时整段隐藏) -->
<div id="agreementSection" class="agreement-box" style="display:none">
<div class="ag-row">
<input type="checkbox" id="agreementCb">
<div class="ag-text" id="agText">
我已阅读并同意 <b id="agTitle">用户协议</b> 的全部条款。
<br><span class="ag-link" onclick="openAgreement()">📄 查看协议原文(须读完)</span>
<div class="ag-tip" id="agTip" style="display:none"></div>
</div>
</div>
</div>
<!-- 登录按钮区 -->
<div class="actions" id="actions" style="display:none"></div>
<!-- ★ 协议阅读弹窗:滚到底部才能勾选 -->
<div class="ag-modal-mask" id="agModalMask">
<div class="ag-modal">
<div class="ag-head">
<h3 id="agModalTitle">服务器用户协议</h3>
<span class="ag-close" onclick="closeAgreement()">×</span>
</div>
<div class="ag-body" id="agModalBody"></div>
<div class="ag-foot">
<span class="ag-progress" id="agProgress">尚未阅读</span>
<span style="display:flex;gap:8px">
<button class="ag-btn" id="agRetryBtn" onclick="loadAgreementContent()"
style="background:var(--border);color:var(--text)">重试加载</button>
<button class="ag-btn" id="agModalBtn" disabled onclick="confirmAgreement()">我已完成阅读</button>
</span>
</div>
</div>
</div>
</div>
<script>
const TOKEN = new URLSearchParams(location.search).get('token') || '';
const statusBox = document.getElementById('statusBox');
const actionsDiv = document.getElementById('actions');
const tokenSection = document.getElementById('tokenSection');
const passwordSection = document.getElementById('passwordSection');
const subtitle = document.getElementById('subtitle');
const pwdStatusBox = document.getElementById('pwdStatusBox');
// ===== 安全拦截:无Token则拒绝访问 =====
if (!TOKEN) {
document.body.innerHTML = `
<div style="text-align:center;padding:60px 20px;">
<h1 style="color:#f85149;margin-bottom:20px">🚫 访问被拒绝</h1>
<p style="color:var(--dim);font-size:16px;line-height:1.8">
Web登录必须通过游戏内Token验证。<br>
请在游戏中执行 <b style="color:var(--accent)"> <b>/web</b><br>
然后点击上方链接登录Web端。
</p>
</div>
`;
console.error('[登录页面] 无Token访问被拒绝');
throw new Error('NoToken');
}
// ===== 用户协议送达门控 =====
// 语义:rules 目录无 .md → 整段隐藏(无需勾选、不要求签章);
// 有协议 → 必须勾选"已阅"且读过弹窗(滚到底部)才能登录;已签过 → 默认勾选。
let AG = { loaded: false, skipped: true, need: false, fingerprint: '', title: '服务器用户协议', already: false };
let AG_READ = false; // 本次会话是否完整阅读过协议
let AG_LOADED = false; // ★ 协议原文是否真正拉取成功并填入弹窗(堵"加载中就被判读到底"的绕过)
let AG_HAS_CONTENT = false; // ★ 弹窗 body 是否含实际协议文本(非"加载中"/"加载失败"占位)
// 加载协议状态(登录页打开即调)
async function loadAgreementStatus(player) {
try {
const url = new URL('./api/sync.php', location.href);
url.searchParams.set('action', 'rules_status');
if (player) url.searchParams.set('player', player);
const res = await fetch(url, { method: 'POST', headers: {'Content-Type': 'application/json'} });
const data = await res.json();
if (data.success && data.data) {
AG.skipped = !!data.data.skipped;
AG.need = !AG.skipped;
AG.fingerprint = data.data.fingerprint || '';
AG.title = data.data.title || AG.title;
AG.already = !!data.data.already_signed;
} else {
AG.skipped = true; // 接口异常时降级为跳过(不阻塞登录,避免 PHP 故障锁死用户)
AG.need = false;
}
} catch (e) {
AG.skipped = true; AG.need = false; // 网络异常降级跳过,不锁死登录
}
AG.loaded = true;
applyAgreementUI();
}
function applyAgreementUI() {
const sec = document.getElementById('agreementSection');
const cb = document.getElementById('agreementCb');
if (!AG.loaded) return;
if (AG.skipped) {
sec.style.display = 'none';
setAgreementGate(false);
return;
}
sec.style.display = 'block';
document.getElementById('agTitle').textContent = AG.title;
if (AG.already) {
cb.checked = true;
AG_READ = true; // 已签过:本次会话视为已读,直接放行
} else {
cb.checked = false;
AG_READ = false;
}
setAgreementGate(true);
}
// 勾选框只在「已勾选 且 已阅读」时可勾(已签玩家自动满足)
function setAgreementGate(on) {
const cb = document.getElementById('agreementCb');
const tip = document.getElementById('agTip');
if (!on) { cb.disabled = false; tip.style.display = 'none'; syncLoginButtons(); return; }
// 需要协议:未读且未签 → 锁勾选框,提示先阅读
if (AG.already) { cb.disabled = false; tip.style.display = 'none'; syncLoginButtons(); return; }
if (AG_READ) { cb.disabled = false; tip.style.display = 'none'; syncLoginButtons(); return; }
cb.disabled = true;
cb.checked = false;
tip.style.display = 'block';
tip.textContent = '请先点击上方「查看协议原文」完整阅读(滚动至底部)后,方可勾选。';
syncLoginButtons();
}
document.addEventListener('DOMContentLoaded', () => {
// 勾选联动
document.getElementById('agreementCb').addEventListener('change', (e) => {
if (e.target.checked) {
// 勾选成功 = 触发签章(PHP 同步写 rules_ack + 生成回执)
fireAgreementMark();
document.getElementById('agTip').style.display = 'none';
}
syncLoginButtons();
});
});
// 打开阅读弹窗
function openAgreement() {
if (!AG.need) return;
loadAgreementContent();
const mask = document.getElementById('agModalMask');
mask.classList.add('show');
const body = document.getElementById('agModalBody');
body.scrollTop = 0;
updateAgProgress();
}
function closeAgreement() {
document.getElementById('agModalMask').classList.remove('show');
}
// 拉协议原文填充弹窗
let AG_LOADING = false; // 加载锁,防「重试加载」狂点并发
async function loadAgreementContent() {
if (AG_LOADING) return;
AG_LOADING = true;
const retryBtn = document.getElementById('agRetryBtn');
if (retryBtn) { retryBtn.disabled = true; retryBtn.style.opacity = '0.5'; }
const body = document.getElementById('agModalBody');
// 复位加载态:未成功前 AG_LOADED 必须 false,updateAgProgress 才会锁按钮
AG_LOADED = false;
AG_HAS_CONTENT = false;
AG_READ = false; // 重新打开弹窗要重新读
body.textContent = '加载中...';
updateAgProgress();
try {
const url = new URL('./api/sync.php', location.href);
url.searchParams.set('action', 'rules_content');
const res = await fetch(url, { method: 'POST', headers: {'Content-Type': 'application/json'} });
const data = await res.json();
if (data.success && data.data && data.data.has_agreement && (data.data.content || '').trim() !== '') {
body.innerHTML = renderMarkdownLite(data.data.content); // ★ 渲染 markdown(标题/列表/加粗/引用)
document.getElementById('agModalTitle').textContent = data.data.title || AG.title;
AG_LOADED = true; // ★ 原文到位
AG_HAS_CONTENT = true; // ★ 有实际内容
} else {
body.textContent = '(服务器未配置用户协议)';
// 无协议内容 → 本不该要求阅读;若 need=true 却拉不到正文,按"未配置"处理放行
AG_LOADED = true;
AG_HAS_CONTENT = false;
}
// 滚到顶部,让用户从头读
setTimeout(() => { body.scrollTop = 0; updateAgProgress(); }, 30);
} catch (e) {
body.textContent = '协议加载失败:' + e.message + '\n\n请点击「重试加载」后再阅读';
AG_LOADED = false; // ★ 加载失败 → 锁死按钮,必须重试成功才允许读
AG_HAS_CONTENT = false;
updateAgProgress();
} finally {
AG_LOADING = false;
if (retryBtn) { retryBtn.disabled = false; retryBtn.style.opacity = '1'; }
}
}
// 阅读进度:滚到底部(容差 8px)→ 解锁勾选
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('agModalBody').addEventListener('scroll', updateAgProgress);
});
function updateAgProgress() {
const body = document.getElementById('agModalBody');
const prog = document.getElementById('agProgress');
const btn = document.getElementById('agModalBtn');
// ★ 核心防绕过:协议原文未真正加载成功(AG_LOADED)且无实际内容(AG_HAS_CONTENT)
// 时,一律锁死按钮,绝不能因"加载中..."短文本 scrollHeight 小就误判"已读至底部"
if (!AG_LOADED || !AG_HAS_CONTENT) {
prog.textContent = AG_LOADED ? '无需阅读(无协议正文)' : '协议加载中,请稍候…';
prog.style.color = 'var(--yellow)';
btn.disabled = true;
if (AG.already) {
// 已签玩家不需要再读,允许放行
btn.disabled = false;
}
setAgreementGate(AG.need);
return;
}
// 已签玩家:无需阅读,按钮可直接放行
if (AG.already) {
AG_READ = true;
prog.textContent = '已签署,无需再读 ✓';
prog.style.color = 'var(--green)';
btn.disabled = false;
setAgreementGate(AG.need);
return;
}
// 未签:必须滚到实际内容底部(容差 8px)才解锁
const remain = body.scrollHeight - body.clientHeight - body.scrollTop;
if (remain <= 8) {
AG_READ = true;
prog.textContent = '已读至底部 ✓';
prog.style.color = 'var(--green)';
btn.disabled = false;
setAgreementGate(AG.need);
} else {
prog.textContent = '请向下滚动至协议末尾';
prog.style.color = 'var(--dim)';
btn.disabled = true; // ★ 没读到底 → 按钮禁用,无法点"我已完成阅读"
}
}
// 点「我已完成阅读」→ 关闭弹窗并自动勾选
// ===== 轻量 markdown → HTML 渲染(登录弹窗用,无外部依赖,与 player.php 同范式)=====
function renderMarkdownLite(md) {
if (!md) return '';
const lines = String(md).split(/\r?\n/);
let html = '';
let inList = false;
const closeList = () => { if (inList) { html += '</ul>'; inList = false; } };
for (let raw of lines) {
let s = raw;
// 表格分隔线丢弃
if (s.trim().match(/^\|?[\s:|-]+\|?$/) && s.trim().length > 1 && s.includes('-')) { closeList(); continue; }
// 代码围栏 ``` 整行丢弃(后端已剥 json 块,双保险)
if (s.trim().startsWith('```')) { closeList(); continue; }
// 标题 #/##/###
const hm = s.match(/^(#{1,6})\s+(.*)$/);
if (hm) {
closeList();
const lvl = hm[1].length;
const cls = lvl <= 2 ? (lvl === 1 ? 'ag-h' : 'ag-h2') : 'ag-h3';
html += `<div class="${cls}">${inlineMd(hm[2])}</div>`;
continue;
}
// 无序列表 -/*/+
if (s.match(/^\s*[-*+]\s+/)) {
if (!inList) { html += '<ul>'; inList = true; }
const item = s.replace(/^\s*[-*+]\s+/, '');
html += `<li>${inlineMd(item)}</li>`;
continue;
}
closeList();
// 引用 >
if (s.match(/^\s*>/)) {
html += `<div class="ag-quote">${inlineMd(s.replace(/^\s*>\s?/, ''))}</div>`;
continue;
}
// 空行
if (s.trim() === '') { html += '<div style="height:8px"></div>'; continue; }
// 普通段落
html += `<div class="ag-p">${inlineMd(s)}</div>`;
}
closeList();
return html;
}
// 行内 markdown:加粗/斜体/代码/链接
function inlineMd(s) {
let t = esc(s);
t = t.replace(/`([^`]*)`/g, '<code>$1</code>');
t = t.replace(/(\*\*|__)(.+?)\1/g, '<b>$2</b>');
t = t.replace(/(^|[^*])(\*)([^*]+)\*(?!\*)/g, '$1<i>$3</i>');
t = t.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" rel="noopener" style="color:var(--accent);text-decoration:underline">$1</a>');
return t;
}
// HTML 转义
function esc(s) { return String(s ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c])); }
// ★ 防绕过二次校验:必须 AG_LOADED && AG_HAS_CONTENT && (AG_READ 或 AG.already),否则拒绝
function confirmAgreement() {
if (!AG_LOADED || !AG_HAS_CONTENT) {
alert('协议原文尚未加载完成,无法确认。请点击「重试加载」。');
return;
}
if (!AG.already && !AG_READ) {
alert('请先向下滚动阅读至协议末尾。');
return;
}
closeAgreement();
const cb = document.getElementById('agreementCb');
if (!cb.checked) {
cb.checked = true;
fireAgreementMark();
document.getElementById('agTip').style.display = 'none';
}
syncLoginButtons();
}
// 勾选时同步写签章(PHP rules_ack + 回执文件)
let AG_MARKED = false;
async function fireAgreementMark() {
if (AG_MARKED) return;
const player = document.getElementById('playerName')?.value?.trim() || '';
if (!player) return;
AG_MARKED = true;
try {
const url = new URL('./api/sync.php', location.href);
url.searchParams.set('action', 'rules_mark');
const res = await fetch(url, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({player: player, fingerprint: AG.fingerprint})
});
const data = await res.json();
if (!data.success) console.warn('[agreement] 签章回执:', data.message);
} catch (e) { console.warn('[agreement] 签章失败(不阻塞登录):', e.message); }
}
// 三条登录路按钮的可用性 = 协议门是否放行
function agreementGatePass() {
if (!AG.loaded || AG.skipped || !AG.need) return true;
const cb = document.getElementById('agreementCb');
return !!(cb && cb.checked);
}
function syncLoginButtons() {
const pass = agreementGatePass();
// 密码/邮箱登录按钮
document.querySelectorAll('#loginPasswordTab .btn-primary, #loginEmailTab .btn-primary').forEach(b => {
b.disabled = !pass;
});
const hint = document.getElementById('agTip');
}
// 拦截:未过协议门 → 禁止发起登录
function requireAgreement() {
if (agreementGatePass()) return true;
const tip = document.getElementById('agTip');
if (tip) { tip.style.display = 'block'; tip.textContent = '请先勾选「已阅用户协议」并完成阅读。'; }
alert('请先阅读并勾选「已阅用户协议」后再登录');
return false;
}
// ===== 有Token → 验证Token =====
tokenSection.style.display = 'block';
// ★ 加载协议门控(player.php 已签过则自动勾选)
loadAgreementStatus('');
doTokenLogin();
// ===== 未签玩家:勾选门放行后点「进入 Web 端」完成跳转 =====
function enterWeb(player) {
// 二次校验协议门(防止用户没真正勾选就点按钮)
if (AG.need && !AG.already) {
if (!agreementGatePass()) {
alert('请先完整阅读并勾选「已阅用户协议」');
return;
}
}
fireAgreementMark();
statusBox.className = 'status-box success';
statusBox.innerHTML = '✅ 已签署用户协议!<br><br>欢迎, <span class="player-name">' + player + '</span><br><small style="color:var(--dim)">正在跳转到玩家商城...</small>';
fetch('./api/sync.php?action=web_access_check', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({web_token: TOKEN, access_action: 'view'})
}).catch(() => {});
setTimeout(() => {
window.location.href = 'player.php?login=' + encodeURIComponent(player) + '&token=' + encodeURIComponent(TOKEN);
}, 500);
}
// ===== Token验证 =====
async function doTokenLogin() {
try {
const apiUrl = './api/sync.php?action=validate_weblogin_token';
const res = await fetch(apiUrl, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({web_token: TOKEN})
});
const text = await res.text();
let data;
try {
data = JSON.parse(text);
} catch (parseErr) {
statusBox.className = 'status-box error';
statusBox.innerHTML = '❌ 服务器响应异常<br><br><code style="font-size:11px;word-break:break-all;color:var(--dim)">' + text.substring(0, 300) + '</code>';
actionsDiv.style.display = 'flex';
actionsDiv.innerHTML = '<span style="color:var(--dim);font-size:13px">请在游戏中重新执行 <b>/sdf1_login weblogin</b></span>';
return;
}
if (data.success && data.data) {
const player = data.data.player;
localStorage.setItem('sdf1_player', player);
localStorage.setItem('sdf1_token', TOKEN);
localStorage.setItem('sdf1_login_time', Date.now());
// ★ 协议门控:先加载该玩家签署状态。
// 语义(用户明令):已签署 → 无感登录,按原逻辑直接跳转,不拦截;
// 仅「有协议且未签」才停留要求签署。无协议(skipped) → 同样无感放行。
await loadAgreementStatus(player);
const needSign = (AG.need && !AG.already);
if (needSign) {
// 仅未签玩家:停留 + 展示勾选门 + 「进入 Web 端」按钮
statusBox.className = 'status-box success';
statusBox.innerHTML = '✅ Token验证成功!<br><br>欢迎, <span class="player-name">' + player + '</span><br><small style="color:var(--yellow)">首次使用请勾选「已阅用户协议」完成签署后再进入。</small>';
applyAgreementUI();
document.getElementById('agreementSection').style.display = AG.need ? 'block' : 'none';
actionsDiv.style.display = 'flex';
actionsDiv.innerHTML = '<button class="btn btn-primary" style="width:100%" onclick="enterWeb(' + JSON.stringify(player) + ')">进入 Web 端</button>';
return;
}
// ★ 已签 / 无协议 → 无感登录:直接跳转(fireAgreementMark 幂等,未签才补写)
fireAgreementMark();
// ★ Token验证成功 → 直接跳转到player.php(跳过密码,token本身即身份证明)
statusBox.className = 'status-box success';
statusBox.innerHTML = '✅ Token验证成功!<br><br>欢迎, <span class="player-name">' + player + '</span><br><small style="color:var(--dim)">正在跳转到玩家商城...</small>';
// ★ 同时写入web_session_log(让validateWebAccess能识别在线状态)
fetch('./api/sync.php?action=web_access_check', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({web_token: TOKEN, access_action: 'view'})
}).catch(() => {});
setTimeout(() => {
// ★ 跳转时带上token,确保player.php一定能读到
window.location.href = 'player.php?login=' + encodeURIComponent(player) + '&token=' + encodeURIComponent(TOKEN);
}, 800);
} else {
statusBox.className = 'status-box error';
statusBox.innerHTML = '❌ 登录失败<br><br>' + (data.message || 'Token无效或已过期');
actionsDiv.style.display = 'flex';
actionsDiv.innerHTML = '<span style="color:var(--dim);font-size:13px">请在游戏中重新执行 <b>/sdf1_login weblogin</b></span>';
}
} catch (e) {
statusBox.className = 'status-box error';
statusBox.innerHTML = '❌ 连接失败<br><br>' + e.message;
}
}
// ===== 密码登录 =====
async function doPasswordLogin() {
const player = document.getElementById('playerName').value.trim();
const password = document.getElementById('password').value;
// ★ 协议门:未签先要求签署(已签/无协议自动放行,requireAgreement 幂等)
if (!requireAgreement()) return;
fireAgreementMark(); // 放行后补写/确认签章(幂等)
if (!password) { showPwdError('请输入密码'); return; }
// ★ 人机验证(2026-10-02):CF 渲染完即有 token(基本无感);VA 没做会在这里拉起验证
let cap = {};
if (window.CaptchaGuard) {
try { cap = await CaptchaGuard.payload(); }
catch (e) { showPwdError(e.message || '请先完成人机验证'); return; }
}
pwdStatusBox.className = 'status-box loading';
pwdStatusBox.style.display = 'block';
pwdStatusBox.innerHTML = '<span class="spinner"></span> 正在验证密码...';
try {
// 1. 提交登录请求
const apiUrl = './api/sync.php';
const reqRes = await fetch(apiUrl + '?action=web_login_request', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(Object.assign({player: player, password: password}, cap))
});
const reqData = await reqRes.json();
if (!reqData.success) {
showPwdError(reqData.message || '提交失败');
return;
}
const requestId = reqData.data.request_id;
// 2. 轮询结果
pwdStatusBox.innerHTML = '<span class="spinner"></span> 等待游戏服务器验证密码...';
let attempts = 0;
const maxAttempts = 60; // 最多等60秒
const pollInterval = setInterval(async () => {
attempts++;
if (attempts > maxAttempts) {
clearInterval(pollInterval);
showPwdError('验证超时,请稍后重试');
return;
}
try {
const pollRes = await fetch(apiUrl + '?action=check_web_login_result&player=' + encodeURIComponent(player) + '&request_id=' + requestId);
const pollText = await pollRes.text();
const pollData = JSON.parse(pollText);
console.log('[poll] status:', pollData.status || pollData.data?.status, 'data:', JSON.stringify(pollData.data).substring(0, 100));
if (pollData.success && pollData.data) {
const result = pollData.data;
if (result.status === 'success') {
clearInterval(pollInterval);
// 登录成功 → 进入玩家商城
pwdStatusBox.className = 'status-box success';
pwdStatusBox.innerHTML = '✅ 登录成功!<br><br>欢迎, <span class="player-name">' + player + '</span><br><small style="color:var(--dim)">正在跳转...</small>';
// ★ token已存入localStorage,跳转player.php带token参数
setTimeout(() => {
window.location.href = 'player.php?login=' + encodeURIComponent(player) + '&token=' + encodeURIComponent(TOKEN);
}, 500);
} else if (result.status === 'failed') {
clearInterval(pollInterval);
showPwdError(result.message || '密码错误');
}
// status === 'pending' → 继续轮询
} else if (pollData.data && pollData.data.status === 'pending') {
// 仍在pending状态,可能是请求过期,继续轮询
console.log('[poll] 请求pending或过期,继续等待...');
} else {
console.warn('[poll] 轮询响应异常:', JSON.stringify(pollData).substring(0, 200));
}
} catch (pollErr) {
console.error('[poll] 轮询异常:', pollErr);
}
}, 1000);
} catch (e) {
showPwdError('连接失败: ' + e.message);
}
}
function showPwdError(msg) {
pwdStatusBox.className = 'status-box error';
pwdStatusBox.style.display = 'block';
pwdStatusBox.innerHTML = '❌ ' + msg;
}
// 回车提交
document.getElementById('password').addEventListener('keydown', function(e) {
if (e.key === 'Enter') doPasswordLogin();
});
document.getElementById('emailCode').addEventListener('keydown', function(e) {
if (e.key === 'Enter') doEmailLogin();
});
// ===== 标签切换 =====
let currentLoginTab = 'password';
function switchLoginTab(tab) {
currentLoginTab = tab;
document.getElementById('loginPasswordTab').style.display = tab === 'password' ? 'block' : 'none';
document.getElementById('loginEmailTab').style.display = tab === 'email' ? 'block' : 'none';
document.getElementById('tabPassword').className = tab === 'password' ? 'btn btn-primary' : 'btn btn-dim';
document.getElementById('tabEmail').className = tab === 'email' ? 'btn btn-primary' : 'btn btn-dim';
document.getElementById('pwdStatusBox').style.display = 'none';
// 切到邮箱时加载脱敏邮箱
if (tab === 'email') loadMaskedEmail();
}
// ===== 加载脱敏邮箱 =====
async function loadMaskedEmail() {
const player = document.getElementById('playerName').value;
try {
const url = new URL('./api/sync.php', location.href);
url.searchParams.set('action', 'get_player_email');
url.searchParams.set('player', player);
const res = await fetch(url, { method: 'POST', headers: {'Content-Type': 'application/json'} });
const data = await res.json();
if (data.success && data.data) {
document.getElementById('maskedEmail').value = data.data.masked_email || '未绑定邮箱';
} else {
document.getElementById('maskedEmail').value = '未绑定邮箱';
}
} catch (e) {
document.getElementById('maskedEmail').value = '加载失败';
}
}
// ===== 发送邮箱验证码 =====
async function sendEmailCode() {
const player = document.getElementById('playerName').value;
const btn = document.getElementById('sendCodeBtn');
btn.disabled = true;
btn.textContent = '发送中...';
try {
const url = new URL('./api/sync.php', location.href);
url.searchParams.set('action', 'send_email_code');
const res = await fetch(url, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({player: player, web_token: TOKEN})
});
const data = await res.json();
if (data.success) {
showPwdSuccess('验证码已发送至 ' + (data.data.masked_email || '**'));
let countdown = 60;
const timer = setInterval(() => {
btn.textContent = countdown + '秒后重发';
countdown--;
if (countdown <= 0) {
clearInterval(timer);
btn.disabled = false;
btn.textContent = '发送验证码';
}
}, 1000);
} else {
showPwdError(data.message || '发送失败');
btn.disabled = false;
btn.textContent = '发送验证码';
}
} catch (e) {
showPwdError('连接失败: ' + e.message);
btn.disabled = false;
btn.textContent = '发送验证码';
}
}
// ===== 邮箱验证码登录 =====
async function doEmailLogin() {
const player = document.getElementById('playerName').value;
const code = document.getElementById('emailCode').value.trim();
// ★ 协议门:未签先要求签署(已签/无协议自动放行)
if (!requireAgreement()) return;
fireAgreementMark(); // 放行后补写/确认签章(幂等)
if (!code) { showPwdError('请输入验证码'); return; }
if (code.length !== 6) { showPwdError('验证码为6位数字'); return; }
pwdStatusBox.className = 'status-box loading';
pwdStatusBox.style.display = 'block';
pwdStatusBox.innerHTML = '<span class="spinner"></span> 正在验证邮箱验证码...';
try {
const url = new URL('./api/sync.php', location.href);
url.searchParams.set('action', 'verify_email_code');
const res = await fetch(url, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({player: player, code: code, web_token: TOKEN})
});
const data = await res.json();
if (data.success) {
localStorage.setItem('sdf1_player', player);
localStorage.setItem('sdf1_token', TOKEN);
pwdStatusBox.className = 'status-box success';
pwdStatusBox.innerHTML = '✅ 邮箱验证成功!<br><br>欢迎, <span class="player-name">' + player + '</span><br><small style="color:var(--dim)">正在跳转...</small>';
setTimeout(() => {
window.location.href = 'player.php?login=' + encodeURIComponent(player);
}, 500);
} else {
showPwdError(data.message || '验证失败');
}
} catch (e) {
showPwdError('连接失败: ' + e.message);
}
}
function showPwdSuccess(msg) {
pwdStatusBox.className = 'status-box success';
pwdStatusBox.style.display = 'block';
pwdStatusBox.innerHTML = '✅ ' + msg;
}
</script>
</body>
</html>