diff --git a/CHANGELOG.md b/CHANGELOG.md index 76e2899..7b15b82 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # 更新日志 +## 2026-10-27 → 🔗 接入授权中心(安装统计 / 公告 / 版本更新) + +- ✨ 右上角常驻显示当前版本号;有新版本时高亮为 `v当前 → v最新`,点开可看更新说明与发布页 +- 🔔 新增公告铃铛:拉取授权中心公告(置顶优先),未读有红点,弹窗公告首次进入弹一次、看过不再打扰 +- 📊 安装登记 + 在线心跳:开机与每 30 分钟上报机器码、版本、平台(只这三项),后台可按天统计安装量与在线数 +- 🔧 告警设置页新增「授权与统计」:显示当前/最新版本、连接状态、安装编号、机器码、上次心跳,可一键关闭上报、立即检查更新 +- 🛡️ 全链路失败开放:授权中心不可达时面板照常工作,仅提示「不可达(不影响使用)」,绝不阻塞任何功能 +- 🐛 修复通用弹窗 `.modal-mask` 与主弹窗类名冲突导致遮罩盖住按钮、鼠标点不到「确定」的问题(改为 `ov-*` 前缀 + 主弹窗层级修正) +- ♻️ 版本号 1.0.2;`docker-compose.yml` 指向 `docker-center:1.0.2` + ## 2026-10-27 → 🛡️ 公网镜像仓库加限速与并发限制 - 🔧 VPS(43.163.242.147) 的 `gitea.88531.cn` 站点新增 `location ^~ /v2/`:`limit_conn perip 2` + `limit_rate 3m` + `limit_rate_after 10m`,防止公网拉镜像打满家庭上行带宽 diff --git a/README.md b/README.md index f7f04ea..f59194b 100644 --- a/README.md +++ b/README.md @@ -152,6 +152,23 @@ NAMESPACE=<命名空间> ./scripts/push-image.sh aliyun 1.0.0 # 或 tencent / > 安全提示:面板挂载了 `/var/run/docker.sock`(等同宿主 root),**不要直接暴露公网**,放在内网或前面套一层带鉴权的反代。 +## 版本与公告 + +面板右上角常驻版本号。有新版本时变成 `v1.0.2 → v1.0.3` 的高亮样式,点开能看到更新说明和发布页;公告走同一个铃铛入口,未读有红点,重要公告会弹一次窗(看过不再弹)。 + +数据来自授权中心(本项目的自建实例)。**上报内容只有三项**:随机生成的机器码、当前版本号、运行平台(linux/amd64 之类),不含容器名、镜像名、日志或任何业务数据。 + +不想上报可以关掉:`告警设置 → 授权与统计 → 上报安装 / 在线心跳`,关掉后不再上报,只保留公告拉取;授权中心挂掉时面板功能完全不受影响(失败开放)。 + +如果要指向自己的授权中心,改这三个环境变量即可: + +```yaml +environment: + - HUB_URL=https://auth.example.com + - HUB_API_KEY=ak_xxxxxxxx + - HUB_PROJECT_ID=7 +``` + ## 为什么按「应用」而不是「容器」管 61 个容器里其实只有 50 个应用(app + db + redis 属于同一个项目)。按容器管要逐个点,按应用管只需看: diff --git a/docker-compose.yml b/docker-compose.yml index abfaa88..209b100 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,7 +1,7 @@ services: docker-center: build: . - image: docker-center:1.0 + image: docker-center:1.0.2 container_name: ${CONTAINER_NAME:-docker-center} restart: always ports: diff --git a/package.json b/package.json index 8767822..a298e46 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "docker-center", - "version": "1.0.0", + "version": "1.0.2", "private": true, "description": "飞牛风格 Docker 容器管理面板(资源占用可排序 + 逐容器详情)", "main": "server/index.js", diff --git a/public/app.js b/public/app.js index dcbbe9a..7997a0f 100644 --- a/public/app.js +++ b/public/app.js @@ -1163,10 +1163,10 @@ async function renderImages() { nets = ns.filter(n => n.driver === 'bridge').map(n => ({ name: n.name, label: n.name })); } catch (e) {} const overlay = document.createElement('div'); - overlay.className = 'modal-mask'; - overlay.innerHTML = ` +
+

授权与统计

+
读取中…
+
+
仅上报机器码、版本号与运行平台,用于统计安装量和在线数;不含容器名、日志或任何业务数据。关闭后不再上报,面板功能不受影响。
+
+ + +
`; $('#saveBtn').onclick = async () => { try { @@ -1511,11 +1521,37 @@ async function renderSettings() { webhook: $('#th_webhook').value, links: { repo: $('#th_repo') ? $('#th_repo').value.trim() : '', nav: $('#th_nav') ? $('#th_nav').value.trim() : '' }, notify: $('#th_notify').checked, + telemetry: $('#th_telemetry') ? $('#th_telemetry').checked : true, }), }); toast('已保存'); + if ($('#th_telemetry')) fetchVersion(true).then(paintVerBox); } catch (e) { toast(e.message, true); } }; + const paintVerBox = () => { + const v = verInfo || {}; + const box = $('#verBox'); + if (!box) return; + box.innerHTML = `当前版本 v${esc(v.current || '—')} · 最新版本 ${v.latest ? 'v' + esc(v.latest) : '—'}` + + (v.update_available ? ' · 有新版本可升级' : '') + + `
授权中心:${v.online ? '已连接' : (v.enabled === false ? '上报已关闭' : '不可达(不影响使用)')}` + + ` · 安装编号 ${v.install_id ? '#' + esc(String(v.install_id)) : '未登记'}` + + `
机器码 ${esc(v.machine_id || '—')}` + + (v.last_heartbeat ? ` · 上次心跳 ${esc(timeStr(v.last_heartbeat))}` : '') + + (v.error ? `
最近一次上报失败:${esc(v.error)}` : ''); + }; + fetchVersion(false).then(paintVerBox); + if ($('#verCheckBtn')) $('#verCheckBtn').onclick = async () => { + $('#verCheckBtn').disabled = true; + await fetchVersion(true); + paintVerBox(); + $('#verCheckBtn').disabled = false; + toast(verInfo && verInfo.update_available ? `发现新版本 v${verInfo.latest}` : '已是最新版本'); + }; + if ($('#annRefreshBtn')) $('#annRefreshBtn').onclick = async () => { + await fetchVersion(true); + toast(`公告 ${(verInfo && verInfo.announcements || []).length} 条`); + }; $('#testBtn').onclick = async () => { try { await api('/api/settings/test', { method: 'POST' }); $('#setLog').textContent = '测试推送已发送'; toast('已发送'); } catch (e) { $('#setLog').textContent = '推送失败:' + e.message; toast(e.message, true); } @@ -1633,3 +1669,159 @@ document.addEventListener('keydown', e => { if (e.key === 'Escape') { $('#modal' paintIcons(); renderExtLinks(); go('apps'); + +/* ---------------- 版本 / 更新 / 公告(授权中心) ---------------- */ +let verInfo = null; +let verTimer = null; + +async function fetchVersion(force) { + try { + verInfo = force + ? await api('/api/version/check', { method: 'POST' }) + : await api('/api/version'); + } catch (e) { + verInfo = verInfo || { current: '', update_available: false, announcements: [], popup: [] }; + } + renderVerChip(); + renderAnnDot(); + return verInfo; +} + +function renderVerChip() { + const el = $('#verChip'); + if (!el || !verInfo) return; + const cur = verInfo.current || '—'; + const has = !!verInfo.update_available && !!verInfo.latest; + el.classList.toggle('has-update', has); + if (has) { + el.innerHTML = `v${esc(cur)} → v${esc(verInfo.latest)}`; + el.title = `有新版本 v${verInfo.latest},点此查看更新说明${verInfo.is_force ? '(重要更新)' : ''}`; + } else { + el.textContent = `v${cur}`; + el.title = verInfo.online === false + ? `当前版本 v${cur}(授权中心暂时不可达,不影响使用)` + : `当前版本 v${cur},已是最新${verInfo.checked_at ? '(检查于 ' + timeStr(Date.parse(verInfo.checked_at)) + ')' : ''}`; + } +} + +function renderAnnDot() { + const dot = $('#annDot'); + if (!dot || !verInfo) return; + const n = (verInfo.announcements || []).length; + const seenKey = 'dc.ann.seen'; + let seen = []; + try { seen = JSON.parse(localStorage.getItem(seenKey) || '[]'); } catch { seen = []; } + const unread = (verInfo.announcements || []).filter(a => !seen.includes(a.id)).length; + dot.classList.toggle('hidden', unread === 0); + $('#annBtn').title = n ? `公告 ${n} 条${unread ? `(${unread} 条未读)` : ''}` : '暂无公告'; +} + +function openVersionModal() { + const v = verInfo || {}; + const has = !!v.update_available && !!v.latest; + $('#modalTitle').textContent = has ? `发现新版本 v${v.latest}` : '关于与更新'; + $('#modalBody').innerHTML = ` +
+
当前版本v${esc(v.current || '—')}
+
最新版本${v.latest ? 'v' + esc(v.latest) : '未获取到'}
+
授权中心${v.online ? '已连接' : (v.enabled === false ? '上报已关闭' : '不可达(不影响使用)')}
+
安装编号${v.install_id ? '#' + esc(String(v.install_id)) : '未登记'}
+ ${has ? `
${esc(v.changelog || '(该版本未填写更新说明)')}
` : '
当前已是最新版本。
'} + ${has && v.is_force ? '
这是一个重要更新,建议尽快升级。
' : ''} +
升级方式:重新拉取镜像后重建容器(数据卷与设置会保留)。${v.download_url ? `
发布页:${esc(v.download_url)}` : ''}
+
`; + $('#modal').classList.remove('hidden'); + const ok = $('#modalOk'); + if (has && v.download_url) { + ok.textContent = '打开发布页'; + ok.onclick = () => { window.open(v.download_url, '_blank', 'noopener'); $('#modal').classList.add('hidden'); }; + } else { + ok.textContent = '检查更新'; + ok.onclick = async () => { + ok.disabled = true; ok.textContent = '检查中…'; + await fetchVersion(true); + ok.disabled = false; ok.textContent = '检查更新'; + openVersionModal(); + }; + } +} + +function annTag(t) { + const map = { update: ['更新', 'update'], promo: ['活动', 'promo'], system: ['系统', ''] }; + const [label, cls] = map[t] || ['公告', '']; + return `${label}`; +} + +function toggleAnnPanel(force) { + let p = $('#annPanel'); + if (p && !force) { p.remove(); return; } + if (p) p.remove(); + const list = (verInfo && verInfo.announcements) || []; + p = document.createElement('div'); + p.id = 'annPanel'; + p.className = 'ann-panel'; + p.innerHTML = `
公告${list.length} 条
` + (list.length + ? list.map(a => ` +
${a.is_top ? '📌' : ''}${annTag(a.type)}${esc(a.title || '')}
+
${esc((a.content || '').slice(0, 260))}
+
${a.created_at ? esc(String(a.created_at).slice(0, 16)) : ''}
+
`).join('') + : '
暂无公告
'); + document.body.appendChild(p); + p.addEventListener('click', e => { + const a = e.target.closest('.ann-item'); + if (a) markAnnSeen(Number(a.dataset.ann)); + }); + const close = (ev) => { + if (!p.contains(ev.target) && !ev.target.closest('#annBtn')) { + p.remove(); document.removeEventListener('pointerdown', close); + } + }; + setTimeout(() => document.addEventListener('pointerdown', close), 0); +} + +function markAnnSeen(id) { + if (!id) return; + const key = 'dc.ann.seen'; + let seen = []; + try { seen = JSON.parse(localStorage.getItem(key) || '[]'); } catch { seen = []; } + if (!seen.includes(id)) { + seen.push(id); + localStorage.setItem(key, JSON.stringify(seen.slice(-200))); + renderAnnDot(); + } +} + +function showPopupAnnouncements() { + const pops = (verInfo && verInfo.popup) || []; + if (!pops.length) return; + const key = 'dc.ann.popup'; + let done = []; + try { done = JSON.parse(localStorage.getItem(key) || '[]'); } catch { done = []; } + const next = pops.find(a => !done.includes(a.id)); + if (!next) return; + $('#modalTitle').textContent = next.title || '公告'; + $('#modalBody').innerHTML = `
${esc(next.content || '')}
+ ${next.link_url ? `
查看详情
` : ''}
`; + $('#modal').classList.remove('hidden'); + $('#modalOk').textContent = '我知道了'; + $('#modalOk').onclick = () => { + done.push(next.id); + localStorage.setItem(key, JSON.stringify(done.slice(-200))); + markAnnSeen(next.id); + $('#modal').classList.add('hidden'); + }; +} + +function initVersionUI() { + const chip = $('#verChip'); + const bell = $('#annBtn'); + if (chip) chip.addEventListener('click', () => { fetchVersion(true).then(openVersionModal); }); + if (bell) bell.addEventListener('click', e => { e.stopPropagation(); toggleAnnPanel(); }); + fetchVersion(false).then(() => showPopupAnnouncements()); + clearInterval(verTimer); + // 后端每 5 分钟刷新一次,前端 2 分钟取一次缓存 + verTimer = setInterval(() => { if (!document.hidden) fetchVersion(false); }, 120000); +} + +initVersionUI(); diff --git a/public/index.html b/public/index.html index bff8278..901f29c 100644 --- a/public/index.html +++ b/public/index.html @@ -64,6 +64,10 @@ + + diff --git a/public/style.css b/public/style.css index a436fd6..824a03f 100644 --- a/public/style.css +++ b/public/style.css @@ -135,8 +135,8 @@ table.tb th.num{text-align:right} /* 弹窗 */ .modal{position:fixed;inset:0;z-index:50;display:grid;place-items:center} .modal.hidden{display:none} -.modal-mask{position:absolute;inset:0;background:rgba(16,24,40,.32)} -.modal-box{position:relative;background:#fff;border-radius:12px;width:min(560px,94vw);max-height:88vh;overflow:auto;padding:18px 20px;box-shadow:0 20px 50px rgba(16,24,40,.2)} +.modal-mask{position:absolute;inset:0;background:rgba(16,24,40,.32);z-index:1} +.modal-box{position:relative;z-index:2;background:#fff;border-radius:12px;width:min(560px,94vw);max-height:88vh;overflow:auto;padding:18px 20px;box-shadow:0 20px 50px rgba(16,24,40,.2)} .modal-box h2{margin:0 0 14px;font-size:16px} .modal-box label{display:block;font-size:12px;color:var(--muted);margin:10px 0 4px} .modal-box input,.modal-box textarea{width:100%;padding:8px 10px;border:1px solid var(--line);border-radius:8px;font-size:13px;outline:none;font-family:inherit} @@ -391,17 +391,17 @@ table.tb th.num{text-align:right} .lim-chip{display:inline-block;margin-left:6px;padding:1px 6px;border-radius:999px;background:#fff1f0;border:1px solid #ffd6d2;color:#c0392b;font-size:10.5px;font-weight:600;vertical-align:middle} /* 通用弹窗 */ -.modal-mask{position:fixed;inset:0;background:rgba(18,24,34,.42);display:flex;align-items:center;justify-content:center;z-index:9998} -.modal-card{background:#fff;border-radius:14px;width:min(460px,92vw);box-shadow:0 18px 48px rgba(0,0,0,.22);overflow:hidden} -.modal-head{display:flex;align-items:center;justify-content:space-between;padding:12px 16px;border-bottom:1px solid #eef2f7;font-size:14px} -.modal-x{cursor:pointer;color:#93a0b4;font-size:13px} -.modal-x:hover{color:#26303f} -.modal-body{padding:14px 16px;display:flex;flex-direction:column;gap:10px} +.ov-mask{position:fixed;inset:0;background:rgba(18,24,34,.42);display:flex;align-items:center;justify-content:center;z-index:90} +.ov-card{background:#fff;border-radius:14px;width:min(460px,92vw);box-shadow:0 18px 48px rgba(0,0,0,.22);overflow:hidden} +.ov-head{display:flex;align-items:center;justify-content:space-between;padding:12px 16px;border-bottom:1px solid #eef2f7;font-size:14px} +.ov-x{cursor:pointer;color:#93a0b4;font-size:13px} +.ov-x:hover{color:#26303f} +.ov-body{padding:14px 16px;display:flex;flex-direction:column;gap:10px} .m-row{display:flex;align-items:center;gap:8px;font-size:12.5px;color:#5a6b82} .m-row.col{flex-direction:column;align-items:stretch;gap:6px} .m-row select,.m-row input{height:30px;padding:0 9px;border:1px solid #dfe6ef;border-radius:8px;font-size:12.5px;flex:1} .m-row textarea{min-height:74px;padding:8px;border:1px solid #dfe6ef;border-radius:8px;font-family:ui-monospace,Menlo,Consolas,monospace;font-size:12px;resize:vertical} -.modal-foot{display:flex;justify-content:flex-end;gap:8px;padding:12px 16px;border-top:1px solid #eef2f7;background:#fbfdff} +.ov-foot{display:flex;justify-content:flex-end;gap:8px;padding:12px 16px;border-top:1px solid #eef2f7;background:#fbfdff} /* 容器行:安装时间 */ .row .inst{flex-shrink:0;width:76px;text-align:right;line-height:1.3} @@ -433,3 +433,37 @@ table.tb th.num{text-align:right} .promo-card .pc-btn{display:inline-flex;align-items:center;height:36px;padding:0 18px;border-radius:999px;font-size:13px;font-weight:700;color:#fff;background:#1a73e8;box-shadow:0 3px 10px rgba(26,115,232,.26)} .promo-card .pc-btn:hover{text-decoration:none;color:#fff;transform:translateY(-1px)} .promo-card .pc-btn.green{background:#0f9d58;box-shadow:0 3px 10px rgba(15,157,88,.24)} + +/* 顶栏:公告铃铛 + 版本号 */ +.ver-bell{position:relative;display:inline-flex;align-items:center;justify-content:center;width:30px;height:28px;border:1px solid #dfe6ef;border-radius:8px;background:#fff;color:#5a6b82;cursor:pointer} +.ver-bell:hover{border-color:#c9d5e4;background:#f5f8fc;color:#1a5fbf} +.ver-bell svg{width:14px;height:14px} +.ver-bell .ann-dot{position:absolute;top:3px;right:4px;min-width:7px;height:7px;border-radius:999px;background:#e5484d;box-shadow:0 0 0 2px #fff} +.ver-chip{display:inline-flex;align-items:center;gap:4px;height:28px;padding:0 10px;border:1px solid #dfe6ef;border-radius:8px;background:#fff;color:#5a6b82;font-size:12px;font-weight:600;font-variant-numeric:tabular-nums;cursor:pointer;white-space:nowrap} +.ver-chip:hover{border-color:#c9d5e4;background:#f5f8fc;color:#1a5fbf} +.ver-chip.has-update{border-color:#f0b37e;background:linear-gradient(95deg,#fff7ec,#ffeccd);color:#a2560b;box-shadow:0 2px 8px rgba(242,153,74,.22)} +.ver-chip.has-update b{font-weight:800} +.ver-chip .up-dot{width:7px;height:7px;border-radius:999px;background:#f2994a;box-shadow:0 0 0 2px #fff} + +/* 公告面板 */ +.ann-panel{position:fixed;top:56px;right:16px;z-index:60;width:340px;max-height:64vh;overflow:auto;background:#fff;border:1px solid #dfe6ef;border-radius:12px;box-shadow:0 12px 34px rgba(18,38,63,.16);padding:6px} +.ann-panel.hidden{display:none} +.ann-panel .ap-head{display:flex;align-items:center;justify-content:space-between;padding:8px 10px 6px;font-size:12.5px;color:#8b98a9} +.ann-panel .ap-head b{color:#1f2a3a;font-size:13px} +.ann-item{display:block;padding:9px 10px;border-radius:8px;color:#2b3a4d} +.ann-item:hover{background:#f3f7fd;text-decoration:none} +.ann-item .ai-t{font-size:13px;font-weight:700;color:#1f2a3a;display:flex;align-items:center;gap:6px} +.ann-item .ai-t .tag{font-size:10.5px;font-weight:700;padding:1px 6px;border-radius:999px;background:#eaf1fb;color:#1a5fbf} +.ann-item .ai-t .tag.update{background:#e8f5ec;color:#0f7f47} +.ann-item .ai-t .tag.promo{background:#fff2e3;color:#a2560b} +.ann-item .ai-c{font-size:12px;color:#5a6b82;line-height:1.6;margin-top:3px;white-space:pre-wrap} +.ann-item .ai-d{font-size:11px;color:#9aa4b5;margin-top:4px} +.ann-empty{padding:22px 10px;text-align:center;color:#9aa4b5;font-size:12.5px} + +/* 版本 / 更新弹窗内容 */ +.ver-modal .vm-row{display:flex;justify-content:space-between;gap:12px;padding:5px 0;border-bottom:1px dashed #eef2f7;font-size:12.5px;color:#2b3a4d} +.ver-modal .vm-row:last-child{border-bottom:0} +.ver-modal .vm-row .k{color:#8b98a9} +.ver-modal .vm-log{margin-top:10px;padding:10px 12px;border-radius:10px;background:#f7f9fc;border:1px solid #e8eef6;font-size:12.5px;color:#3d4859;line-height:1.75;white-space:pre-wrap;max-height:220px;overflow:auto} +.ver-modal .vm-tip{margin-top:10px;font-size:12px;color:#8b98a9;line-height:1.7} +.ver-modal .vm-tip.warn{color:#a2560b} diff --git a/screenshots/08a-announcement-popup.png b/screenshots/08a-announcement-popup.png new file mode 100644 index 0000000..015db80 Binary files /dev/null and b/screenshots/08a-announcement-popup.png differ diff --git a/screenshots/08b-update-modal.png b/screenshots/08b-update-modal.png new file mode 100644 index 0000000..3071bba Binary files /dev/null and b/screenshots/08b-update-modal.png differ diff --git a/screenshots/08c-announcement-panel.png b/screenshots/08c-announcement-panel.png new file mode 100644 index 0000000..1fa36ee Binary files /dev/null and b/screenshots/08c-announcement-panel.png differ diff --git a/screenshots/08d-settings-license.png b/screenshots/08d-settings-license.png new file mode 100644 index 0000000..5f6b6b2 Binary files /dev/null and b/screenshots/08d-settings-license.png differ diff --git a/server/cloud.js b/server/cloud.js new file mode 100644 index 0000000..d3b4119 --- /dev/null +++ b/server/cloud.js @@ -0,0 +1,214 @@ +'use strict'; +/** + * 授权中心接入(auth.88531.cn / CardAuth) + * 作用:安装登记、在线心跳、版本更新检测、公告拉取。 + * 原则:全部失败开放——授权中心不可达时面板一切功能照常,只是不显示更新与公告。 + */ +const fs = require('fs'); +const path = require('path'); +const crypto = require('crypto'); + +const HUB_URL = (process.env.HUB_URL || 'https://auth.88531.cn').replace(/\/+$/, ''); +const HUB_API_KEY = process.env.HUB_API_KEY || 'ak_eefdbfda4cd96954ff3b9e2fa882d0f1'; +const HUB_PROJECT_ID = Number(process.env.HUB_PROJECT_ID || 7); +const STATE_PATH = process.env.INSTALL_PATH || '/data/install.json'; +const HEARTBEAT_MS = Number(process.env.HUB_HEARTBEAT_MS || 30 * 60 * 1000); +const CHECK_MS = Number(process.env.HUB_CHECK_MS || 6 * 60 * 60 * 1000); +const ANN_MS = Number(process.env.HUB_ANN_MS || 10 * 60 * 1000); +const TIMEOUT_MS = Number(process.env.HUB_TIMEOUT_MS || 8000); + +const state = { + machine_id: '', + install_id: null, + installed_at: '', + last_heartbeat: 0, + last_check: 0, + last_ann: 0, + version: '', // 上次上报的版本 +}; + +const snapshot = { + enabled: true, // 由 settings.telemetry 控制 + online: false, // 授权中心是否可达 + current: '', + latest: '', + update_available: false, + update_required: false, + changelog: '', + download_url: '', + is_force: false, + announcements: [], + popup: [], + checked_at: '', + error: '', +}; + +let getSettings = () => ({}); +let appVersion = '0.0.0'; +let timer = null; + +/* ---------------- 本机标识 ---------------- */ + +function genMachineId() { + // CardAuth 约定:13 位纯数字机器码 + let s = String(1 + Math.floor(Math.random() * 9)); + while (s.length < 13) s += String(Math.floor(Math.random() * 10)); + return s; +} + +function loadState() { + try { + if (fs.existsSync(STATE_PATH)) { + const saved = JSON.parse(fs.readFileSync(STATE_PATH, 'utf8')); + Object.assign(state, saved); + } + } catch (e) { console.error('[hub] 读取安装信息失败', e.message); } + if (!/^\d{10,16}$/.test(state.machine_id || '')) { + state.machine_id = genMachineId(); + state.installed_at = new Date().toISOString(); + } + saveState(); +} + +function saveState() { + try { + fs.mkdirSync(path.dirname(STATE_PATH), { recursive: true }); + fs.writeFileSync(STATE_PATH, JSON.stringify(state, null, 2)); + } catch (e) { console.error('[hub] 写入安装信息失败', e.message); } +} + +/* ---------------- HTTP ---------------- */ + +async function hubFetch(pathname, { method = 'GET', body, withKey = true } = {}) { + const headers = { 'Content-Type': 'application/json', 'User-Agent': `docker-center/${appVersion}` }; + if (withKey) { + headers['X-Api-Key'] = HUB_API_KEY; + headers['X-Project-Id'] = String(HUB_PROJECT_ID); + } + const res = await fetch(HUB_URL + pathname, { + method, + headers, + body: body ? JSON.stringify(body) : undefined, + signal: AbortSignal.timeout(TIMEOUT_MS), + }); + const text = await res.text(); + let json; + try { json = JSON.parse(text); } catch { throw new Error('授权中心返回非 JSON'); } + // CardAuth 的成败在 JSON code 里,HTTP 状态恒为 200 + if (json.code !== 200) throw new Error(json.message || `code=${json.code}`); + return json.data || {}; +} + +function deviceInfo() { + let host = 'unknown'; + try { host = require('os').hostname(); } catch { /* ignore */ } + return JSON.stringify({ platform: process.platform, arch: process.arch, host }); +} + +/* ---------------- 上报 ---------------- */ + +async function checkUpdate(force = false) { + const now = Date.now(); + if (!force && now - state.last_check < CHECK_MS) return; + const data = await hubFetch('/api/public/installations/check-update', { + method: 'POST', + body: { + machine_id: state.machine_id, + client_version: appVersion, + device_info: deviceInfo(), + }, + }); + state.last_check = now; + state.install_id = data.install_id ?? state.install_id; + state.version = appVersion; + Object.assign(snapshot, { + online: true, + error: '', + latest: data.latest_version || data.version || '', + update_available: !!data.update_available, + update_required: !!data.update_required, + changelog: data.changelog || '', + download_url: data.download_url || '', + is_force: !!data.is_force, + checked_at: new Date().toISOString(), + }); + saveState(); +} + +async function heartbeat(force = false) { + const now = Date.now(); + if (!force && now - state.last_heartbeat < HEARTBEAT_MS) return; + const res = await hubFetch('/api/public/installations/heartbeat', { + method: 'POST', + body: { + machine_id: state.machine_id, + client_version: appVersion, + device_info: deviceInfo(), + }, + }); + state.last_heartbeat = now; + if (res.install_id) state.install_id = res.install_id; + saveState(); +} + +async function loadAnnouncements(force = false) { + const now = Date.now(); + if (!force && now - state.last_ann < ANN_MS) return; + const data = await hubFetch( + `/api/public/announcements?target=client&project_id=${HUB_PROJECT_ID}&limit=20`, + { withKey: false }, + ); + state.last_ann = now; + snapshot.announcements = Array.isArray(data.list) ? data.list : []; + snapshot.popup = Array.isArray(data.popup) ? data.popup : []; +} + +async function refresh(force = false) { + const s = getSettings() || {}; + snapshot.enabled = s.telemetry !== false; + snapshot.current = appVersion; + try { + await loadAnnouncements(force); // 公告只读,不受统计开关影响 + } catch (e) { + snapshot.error = e.message; + } + if (!snapshot.enabled) { + snapshot.online = false; + return; + } + try { + await checkUpdate(force); + await heartbeat(force); + snapshot.online = true; + snapshot.error = ''; + } catch (e) { + snapshot.online = false; + snapshot.error = e.message; + console.error('[hub] 上报失败(不影响面板):', e.message); + } +} + +function start(version, settingsGetter) { + appVersion = version; + getSettings = settingsGetter; + loadState(); + snapshot.current = version; + refresh(true).catch(() => {}); + timer = setInterval(() => refresh(false).catch(() => {}), 5 * 60 * 1000); + if (timer.unref) timer.unref(); +} + +function stop() { if (timer) clearInterval(timer); } + +function getSnapshot() { + snapshot.current = appVersion; + return { + ...snapshot, + machine_id: state.machine_id, + install_id: state.install_id, + installed_at: state.installed_at, + last_heartbeat: state.last_heartbeat || null, + }; +} + +module.exports = { start, stop, refresh, getSnapshot, checkUpdate, loadAnnouncements, state }; diff --git a/server/index.js b/server/index.js index e066a3b..f6cf570 100644 --- a/server/index.js +++ b/server/index.js @@ -40,6 +40,7 @@ const DEFAULT_SETTINGS = { notify: true, debounceMinutes: 10, links: { repo: '', nav: '' }, + telemetry: true, // 安装/在线统计上报(关闭后不再上报,公告仍可拉取) }; let settings = JSON.parse(JSON.stringify(DEFAULT_SETTINGS)); try { @@ -937,8 +938,11 @@ app.post('/api/settings', (req, res) => { notify: b.notify !== undefined ? !!b.notify : settings.notify, debounceMinutes: b.debounceMinutes !== undefined ? (Number(b.debounceMinutes) || 10) : settings.debounceMinutes, links: { ...(settings.links || {}), ...(b.links || {}) }, + telemetry: b.telemetry !== undefined ? !!b.telemetry : settings.telemetry, }; saveSettings(); + // 开关变化后立即按新设置上报/停止上报 + hub.refresh(true).catch(() => {}); res.json(settings); }); app.post('/api/settings/test', async (req, res) => { @@ -1681,6 +1685,20 @@ app.delete('/api/backup/:name', async (req, res) => { }); /* ---------------- 启动 ---------------- */ +const hub = require('./cloud'); +const APP_VERSION = require('../package.json').version; + +/* ---------------- 授权中心 / 版本 / 公告 ---------------- */ +app.get('/api/version', (req, res) => res.json(hub.getSnapshot())); +app.post('/api/version/check', async (req, res) => { + try { + await hub.refresh(true); + res.json(hub.getSnapshot()); + } catch (e) { + res.status(200).json({ ...hub.getSnapshot(), error: e.message }); + } +}); + setInterval(sampleOnce, SAMPLE_MS); setInterval(tickApps, SAMPLE_MS); setInterval(inspectAll, INSPECT_MS); @@ -1689,4 +1707,8 @@ process.on('SIGTERM', () => { flushTraffic().finally(() => process.exit(0)); }); setInterval(tickUptime, UPTIME_MS); setTimeout(() => { sampleOnce(); inspectAll(); tickApps(); }, 300); -app.listen(PORT, '0.0.0.0', () => console.log(`[docker-center] http://0.0.0.0:${PORT} sample=${SAMPLE_MS}ms inspect=${INSPECT_MS}ms`)); +app.listen(PORT, '0.0.0.0', () => { + console.log(`[docker-center] http://0.0.0.0:${PORT} sample=${SAMPLE_MS}ms inspect=${INSPECT_MS}ms v${APP_VERSION}`); + // 授权中心上报(安装/在线/更新检测)+ 公告拉取,失败不影响面板 + try { hub.start(APP_VERSION, () => settings); } catch (e) { console.error('[hub] 启动失败', e.message); } +});