212 lines
6.6 KiB
JavaScript
212 lines
6.6 KiB
JavaScript
'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 || 60 * 1000);
|
||
const TIMEOUT_MS = Number(process.env.HUB_TIMEOUT_MS || 8000);
|
||
const HUB_DISABLED = /^(1|true|yes)$/i.test(process.env.HUB_DISABLED || '');
|
||
|
||
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 = !HUB_DISABLED && 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(() => {}), 60 * 1000);
|
||
if (timer.unref) timer.unref();
|
||
}
|
||
|
||
function stop() { if (timer) clearInterval(timer); }
|
||
|
||
function getSnapshot() {
|
||
snapshot.current = appVersion;
|
||
// 注意:机器码 / 安装编号只留在服务端与授权中心,不下发到浏览器
|
||
return { ...snapshot };
|
||
}
|
||
|
||
module.exports = { start, stop, refresh, getSnapshot, checkUpdate, loadAnnouncements, state };
|