fix: 缺陷审计批次(231 例)+ 复核补钉(①–⑦)

一、审计修复(另一侧完成,我复核通过)
- 认证/限流:_client_ip 归一、限流统一走 rate_limit._SlidingTable(超限只淘汰最旧 key,
  不再整表 clear 自毁)、每用户会话上限 10 + 过期清理
- 邮件验证码:锁内原子占位 → 锁外发信 → 成功落码,失败回滚冷却(并发不再双发)
- 租赁:rentals 部分唯一索引(同 order_id 只允许一行 expired=0,迁移前先查重)、
  开锁幂等落库、Timer 代号机制(取消/重排同临界区)、minutes=null 兜底、
  自动还车 30s×6 → 1m/2m/5m/10m 退避
- 安全:ring 四接口登录 + 任务归属校验(Bearer 或 ?token=,校验 sessions 表)、
  共享还车坐标不再伪造、代开锁 IntegrityError 兜底、token 配置原子写(fsync + 0600)
- 入口鉴权:8 个历史/分析接口未登录 401(HTTP 与 rtn_code 同时给)、
  analysis.html 带 Bearer + 未登录门 + 截断提示、历史查询 LIMIT 60000 并回传 truncated
- UX 四个 P0:计时条出现、真实单走 /api/order/return 而 reminder 走 /api/rental/return、
  定位失败不伪造坐标(三选一弹窗)、地图/配置/脚本失败统一落到可自救失败卡片
- 测试:新增 6 个文件 62 例;既有 test_history_30d 只补登录前置

二、我复核时发现并修掉的 7 处
① email_verify.record_cooldown 的 expires 写成 now,会被 send_code 开头的
   _cleanup_locked 整条删掉 —— 任何人发一次验证码就废掉「未注册邮箱」的冷却,
   找回密码又能枚举邮箱是否注册。改为活过冷却窗口,并补 3 例测试
② timer.py 两处落库(自动续租 INSERT、sync 复活 UPDATE)没防新唯一索引:
   撞索引抛 IntegrityError 会让巡检线程退出,该单从此没有计时器/自动还车(上游还在计费)。
   新增 _active_rental_id_for_order(),捕获后复用存活行
③ (0,0) 当合法坐标会先发给上游:/record/return 不校验范围,宽松后端会把车"还"在海里。
   新增 _coords_usable(),不可用就跳过原始点;候选列表永远丢掉第 0 项
④ boot_smoke.py 按旧契约要求 200,加鉴权后永远失败 → HTTPError 401 视为「未登录,预期」
⑤ 自动还车「不放弃」缺绝对上限:加 AUTO_RETURN_GIVE_UP_SECONDS=6h,到点只告警一次并停手
⑥ 索引谓词 aligned 到查重口径:COALESCE(expired,0)=0,旧定义自动重建
⑦ 访问日志脱敏:?token= / ?ticket= / ?access_token= 的值替换为 ***(werkzeug + root logger)
   否则容器日志里就是明文会话令牌
配套改写 tests/test_rental_dedup.py::test_return_accepts_zero_coordinates →
test_return_treats_zero_coordinates_as_missing(原断言把 (0,0) 当合法值发上游)

三、验证
- python -m pytest -q → 234 passed(基线 231,净增 3)
- node 5 套 → 44 pass / 0 fail
- 14 个 .py ast.parse、node --check dist/app.js → 全部通过
- boot_smoke.py → exit=0;未登录 /api/history/stats、/api/analysis/overview、
  /api/ring_progress/* 实测 401,/api/config 200
- 行为级:传 (0,0) 时上游只收到候选点;合法坐标仍先发上报值;唯一索引拦住重复插入
This commit is contained in:
zzy
2026-11-17 09:58:16 +08:00
parent 7a5840e0c3
commit f34ed304bc
59 changed files with 6487 additions and 802 deletions
+64 -10
View File
@@ -633,6 +633,51 @@
_toastTimer = setTimeout(() => { el.style.display = 'none'; }, 2600);
}
// ===== 登录态(BUG-02)=====
// 本页的 8 个数据分析接口已改成「登录用户才可访问」,所以这里所有请求都必须带
// Authorization;未登录 / token 失效时给一句确定的话并回主页面登录,而不是让
// 面板一直停在"加载中"。
const AUTH_STORAGE_KEY = "auth_token";
let _authRedirectTimer = null;
let _statsRefreshTimer = null;
function getAuthToken() {
try { return localStorage.getItem(AUTH_STORAGE_KEY) || ""; } catch (e) { return ""; }
}
function authHeaders(extra) {
const headers = Object.assign({}, extra || {});
const token = getAuthToken();
if (token) headers["Authorization"] = "Bearer " + token;
return headers;
}
// 401 判定:HTTP 状态与 body 里的 rtn_code 任一命中都算(后端两者都给)
function isAuthError(resp, json) {
return (resp && resp.status === 401) || (json && json.rtn_code === 401);
}
function handleAuthRequired(message) {
if (_authRedirectTimer) return; // 并发请求只跳一次
if (_statsRefreshTimer) { clearTimeout(_statsRefreshTimer); _statsRefreshTimer = null; }
showToast(message || "请先在主页面登录");
_authRedirectTimer = setTimeout(() => { window.location.replace("/"); }, 1800);
}
// 未登录时页面不该是空白:一句结论 + 一个回主页的出口,同时自动跳回
function showLoginGateCard(message) {
handleAuthRequired(message);
if (document.getElementById("analysis-auth-gate")) return;
const gate = document.createElement("div");
gate.id = "analysis-auth-gate";
gate.style.cssText = "position:fixed;inset:0;z-index:9998;display:flex;align-items:center;" +
"justify-content:center;background:rgba(247,247,248,.97);padding:24px;text-align:center;";
gate.innerHTML = '<div style="max-width:320px">' +
'<div style="font-size:17px;font-weight:700;margin-bottom:8px">请先在主页面登录</div>' +
'<div style="font-size:13px;color:#666;line-height:1.7;margin-bottom:18px">' +
'车辆历史轨迹能还原到具体车辆与时间,只对已登录账号开放。</div>' +
'<a href="/" style="display:inline-block;padding:12px 22px;border-radius:10px;' +
'background:#1c1c1f;color:#f8f8f6;font-size:15px;font-weight:600;text-decoration:none">' +
'去主页面登录</a></div>';
document.body.appendChild(gate);
}
// 数据导出:生成直链 → UA 检测(与主页面 detectInAppBrowser 同规则)→
// 内嵌浏览器弹复制提示,普通浏览器直接下载
function detectInAppBrowserName() {
@@ -647,17 +692,17 @@
return null;
}
async function exportHistoryCsv() {
const authToken = localStorage.getItem("auth_token");
if (!authToken) { showToast("请先在主页面登录"); return; }
const authToken = getAuthToken();
if (!authToken) { showLoginGateCard(); return; }
showToast("正在生成导出链接...");
try {
const resp = await fetch(API_BASE + '/api/export/create', {
method: 'POST',
headers: { 'Content-Type': 'application/json',
'Authorization': `Bearer ${authToken}` },
headers: authHeaders({ 'Content-Type': 'application/json' }),
body: JSON.stringify({ type: 'history_csv' })
});
const data = await resp.json();
if (isAuthError(resp, data)) { showLoginGateCard(data.message); return; }
if (data.rtn_code !== 0) { showToast(data.message || "生成导出链接失败"); return; }
const url = new URL(data.data.url, window.location.href).href;
const app = detectInAppBrowserName();
@@ -696,9 +741,11 @@
// 初始化
async function init() {
// 未登录直接给登录门,不发请求(发了也是 401)
if (!getAuthToken()) { showLoginGateCard(); return; }
await loadStats();
await loadBikeList();
setTimeout(loadStats, 5000); // 5秒后刷新一次
_statsRefreshTimer = setTimeout(loadStats, 5000); // 5秒后刷新一次
}
// 加载统计
@@ -707,8 +754,10 @@
if (errEl) { errEl.style.display = 'none'; }
try {
const statsDays = (document.getElementById('stats-days') || {}).value || 1;
const resp = await fetch(API_BASE + '/api/history/stats?days=' + statsDays);
const resp = await fetch(API_BASE + '/api/history/stats?days=' + statsDays,
{ headers: authHeaders() });
const json = await resp.json();
if (isAuthError(resp, json)) { showLoginGateCard(json && json.message); return; }
if (json.rtn_code === 0) {
const d = json.data;
@@ -772,8 +821,9 @@
// 加载车辆列表
async function loadBikeList() {
try {
const resp = await fetch(API_BASE + '/api/history/bikes');
const resp = await fetch(API_BASE + '/api/history/bikes', { headers: authHeaders() });
const json = await resp.json();
if (isAuthError(resp, json)) { showLoginGateCard(json && json.message); return; }
if (json.rtn_code === 0) {
const bikes = (json.data && json.data.bikes) || [];
const options = ['<option value="">全部车辆</option>'];
@@ -982,17 +1032,20 @@
const url = bikeCode
? `${API_BASE}/api/history/trajectory?bike_code=${bikeCode}&days=${days}`
: `${API_BASE}/api/history/all_trajectory?days=${days}`;
const resp = await fetch(url);
const resp = await fetch(url, { headers: authHeaders() });
const json = await resp.json();
if (isAuthError(resp, json)) { showLoginGateCard(json && json.message); return; }
if (json.rtn_code === 0) {
currentTrajData = json.data;
renderTrajectory(json.data);
// 截断提示:窗口内点位超上限被截断时明确告知,不静默少画
// (上限由后端 HISTORY_ALL_TRAJECTORY_LIMIT 给出,前端不再硬编码数字)
const hint = document.getElementById('traj-hint');
if (hint) {
const cap = bikeCode ? '3000' : String(json.data.limit || 60000);
hint.textContent = json.data.truncated
? `⚠ 点位较多,仅绘制了前 ${bikeCode ? '3000' : '200000'} 条,其余已省略(可缩小时间范围查看完整轨迹)`
? `⚠ 点位较多,仅绘制了前 ${cap} 条,其余已省略(可缩小时间范围查看完整轨迹)`
: '';
}
} else {
@@ -1266,8 +1319,9 @@
}
try {
const resp = await fetch(`${API_BASE}/api/history/heatmap`);
const resp = await fetch(`${API_BASE}/api/history/heatmap`, { headers: authHeaders() });
const json = await resp.json();
if (isAuthError(resp, json)) { showLoginGateCard(json && json.message); return; }
if (json.rtn_code === 0) {
if (!heatMapReady) {
+26 -5
View File
@@ -149,7 +149,7 @@
</div>
<!-- 用车计时状态栏 -->
<div class="rental-bar" id="rental-bar" onclick="showReturnModal()">
<div class="rental-bar" id="rental-bar" onclick="showRentalReturn()">
<div class="rental-bar-left">
<svg class="icon" viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2"><path d="M19 11H5m0 0l2-4h10l2 4m-14 0h14m0-4H5m14 4v4a2 2 0 01-2 2H7a2 2 0 01-2-2v-4m4-5h6l1 3H8l1-3m10 5a2 2 0 100 4 2 2 0 000-4z"/></svg>
<span class="rental-bar-time" id="rental-time">--:--</span>
@@ -159,7 +159,7 @@
<button class="rental-bar-btn" id="rental-add-round-btn" onclick="event.stopPropagation(); addRoundForCurrent()" title="追加一轮续租" style="display:none;">
<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="9"/><path d="M12 8v8M8 12h8"/></svg> +1轮
</button>
<button class="rental-bar-btn" onclick="event.stopPropagation(); confirmReturn()"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 6h18M8 6V4h8v2m-9 4v6m6-6v6m6-6v6M5 6V4a1 1 0 011-1h12a1 1 0 011 1v2"/></svg> 还车</button>
<button class="rental-bar-btn" onclick="event.stopPropagation(); showRentalReturn()"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 6h18M8 6V4h8v2m-9 4v6m6-6v6m6-6v6M5 6V4a1 1 0 011-1h12a1 1 0 011 1v2"/></svg> 还车</button>
</div>
</div>
@@ -719,16 +719,37 @@
<div class="return-overlay" onclick="closeReturnModal()"></div>
<div class="return-content">
<div class="return-icon"><svg viewBox="0 0 24 24" width="48" height="48" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M19 11H5m0 0l2-4h10l2 4m-14 0h14m0-4H5m14 4v4a2 2 0 01-2 2H7a2 2 0 01-2-2v-4m4-5h6l1 3H8l1-3m10 5a2 2 0 100 4 2 2 0 000-4z"/></svg></div>
<div class="return-title">你还车了吗?</div>
<div class="return-desc">您正在使用电动车</div>
<div class="return-title">结束提醒计时?</div>
<div class="return-desc">这是网页上的提醒计时(未绑定微信订单);车还在骑就别点确认</div>
<div class="return-bike" id="return-bike-code">#51287</div>
<div class="return-btns">
<button class="return-btn-yes" onclick="confirmReturn()">是,已还车</button>
<button class="return-btn-yes" onclick="confirmReturn()">结束提醒计时</button>
<button class="return-btn-no" onclick="closeReturnModal()">否,继续计时</button>
</div>
</div>
</div>
<!-- 拿不到定位时的三选一(UX-04):绝不替用户伪造一个坐标去还车/锁车 -->
<div class="auth-modal" id="geo-choice-modal">
<div class="auth-overlay" onclick="cancelGeoChoice()"></div>
<div class="auth-content">
<div class="auth-header">
<span>拿不到你的位置</span>
<button class="auth-close" onclick="cancelGeoChoice()" aria-label="关闭">✕</button>
</div>
<div class="share-desc">
还车和锁车都要把当前位置报给车辆服务。没有定位就直接提交,服务端多半判「不在停车区」,
所以这里不猜位置,交给你选:
</div>
<button class="auth-submit" onclick="chooseGeoRetry()">① 去开定位,再试一次</button>
<button class="auth-submit ghost" style="margin-top:10px;" onclick="chooseGeoMapCenter()">② 用地图中心点代替</button>
<button class="auth-submit ghost" style="margin-top:10px;" onclick="cancelGeoChoice()">③ 取消这次操作</button>
<div class="devices-tip" style="margin-top:12px;">
开启定位:手机「设置」→「隐私 / 位置信息」→ 找到浏览器或微信 → 允许定位,回来点①。
</div>
</div>
</div>
<!-- 车辆详情遮罩 -->
<div class="card-overlay" id="card-overlay" onclick="closeCard()"></div>
+50 -23
View File
@@ -171,9 +171,19 @@
<script>
const params = new URLSearchParams(window.location.search);
const taskId = params.get('task_id');
const taskId = params.get('task_id') || '';
const total = parseInt(params.get('total') || '0');
// ===== 登录态(BUG-20)=====
// 批次 C 之后 /api/ring_status | ring_cancel | ring_progress 都要求登录,
// 鉴权接受 Authorization: Bearer 或 ?token=。EventSource 不能自定义 header,
// 只能走查询参数;POST 取消请求两边都带上,任一通道生效即可。
function getAuthToken() {
try { return localStorage.getItem('auth_token') || ''; } catch (e) { return ''; }
}
const authToken = getAuthToken();
const tokenQuery = authToken ? `?token=${encodeURIComponent(authToken)}` : '';
document.getElementById('status-text').textContent = `共 ${total} 辆车`;
let cancelled = false;
@@ -217,13 +227,19 @@
function cancelTask() {
if (cancelled || completed) return;
if (!taskId) { addLog('缺少任务号,无法取消', 'failed'); return; }
cancelled = true;
document.getElementById('cancel-btn').disabled = true;
document.getElementById('cancel-btn').textContent = '取消中...';
fetch(`/api/ring_cancel/${taskId}`, { method: 'POST' })
const headers = {};
if (authToken) headers['Authorization'] = 'Bearer ' + authToken;
fetch(`/api/ring_cancel/${encodeURIComponent(taskId)}${tokenQuery}`, {
method: 'POST',
headers
})
.then(r => r.json())
.then(d => {
addLog(d.message || '取消请求已发送', '');
addLog(d.message || '取消请求已发送', d.rtn_code === 0 ? '' : 'failed');
})
.catch(() => addLog('取消请求失败', 'failed'));
}
@@ -235,29 +251,40 @@
uiCloseWindow();
}
// SSE 连接
const es = new EventSource(`/api/ring_progress/${taskId}`);
// SSE 连接(带 ?token=;没有任务号或未登录时不要连,否则 EventSource 会 401 反复重试)
let es = null;
if (!taskId) {
document.getElementById('status-text').textContent = '缺少任务号';
document.getElementById('cancel-btn').disabled = true;
addLog('缺少 task_id,请从主页面重新发起全车寻铃', 'failed');
} else if (!authToken) {
document.getElementById('status-text').textContent = '请先在主页面登录';
document.getElementById('cancel-btn').disabled = true;
addLog('未登录:请先在主页面登录后再查看寻车进度', 'failed');
} else {
es = new EventSource(`/api/ring_progress/${encodeURIComponent(taskId)}${tokenQuery}`);
es.onmessage = (e) => {
try {
const data = JSON.parse(e.data);
if (data.type === 'progress') {
updateUI(data);
} else if (data.type === 'done') {
es.close();
} else if (data.type === 'error') {
addLog(data.message, 'failed');
es.close();
}
} catch (err) {}
};
es.onmessage = (e) => {
try {
const data = JSON.parse(e.data);
if (data.type === 'progress') {
updateUI(data);
} else if (data.type === 'done') {
es.close();
} else if (data.type === 'error') {
addLog(data.message, 'failed');
es.close();
}
} catch (err) {}
};
es.onerror = () => {
addLog('连接断开', 'failed');
es.close();
};
es.onerror = () => {
addLog('连接断开', 'failed');
if (es) es.close();
};
addLog('开始监听进度...', '');
addLog('开始监听进度...', '');
}
</script>
</body>
</html>