v-fixed35:授权/公告/版本推送系统(CardAuth project11) + 右上角版本角标 + 每IP限流429 + TVBOX统计 + 公告弹窗DOM化修白屏
This commit is contained in:
1 parent
e90d022ae4
commit
ce7a7dd84c
7 files changed
+377
No files matched your search
@@ -2,6 +2,15 @@
|
||||
|
||||
格式参考本机发版惯例:按日期分条,`🐛修复` / `✨新功能`。
|
||||
|
||||
## 2026-10-30 → v-fixed35
|
||||
|
||||
- ✨ **授权 / 公告 / 版本推送系统(对接 CardAuth 授权中心 `auth.88531.cn`)**:站点启动自动登记安装(**安装人数**统计,机器码只存授权中心 Redis、绝不下发浏览器)、30 分钟心跳(**在线人数**统计,含最后在线时间)、60 秒公告轮询(**公告推送**:网页弹窗 + TVBOX 配置 `notice` 字段)、6 小时版本自检(**版本推送**:中心发布新版后客户端显示「发现新版本」,TVBOX 配置带出 `version` / `update_url`);授权中心故障时失败开放,绝不影响站点功能
|
||||
- ✨ **右上角版本角标**:桌面导航右侧常驻紫色 `vfixed35` 小标
|
||||
- ✨ **每 IP 限流(防恶意刷流量)**:普通接口 240 次/分、直播拉流 30 次/分,超出返回 `429` + `Retry-After`;压测实测 250 发拦 10、40 发拦 10、正常用户不受影响
|
||||
- ✨ **TVBOX 使用统计**:`usage-stats.sh` 新增 TVBOX 段(配置/接口请求次数、独立 IP、看直播 IP、Top UA)
|
||||
- ✨ 新增免登录路由 **`/api/license-config`**(版本 / 公告 / 更新状态标准接口);`license-hub.js` 客户端 + 补丁 `patches/patch_license.js` 入仓(幂等可重放)
|
||||
- 🐛 **修复公告弹窗引发的首页白屏**(React #418/#422 水合错误):弹窗改为延迟 1.2s **纯 DOM 注入**、不走 React 状态,实测弹窗出现 / 关闭 / localStorage 去重全部通过;公告测试数据已清理
|
||||
|
||||
## 2026-10-29 → v-fixed34
|
||||
|
||||
- ✨ **访问日志与使用统计**:向 Next `start-server.js` 注入 `[ACCESS]` 请求日志(时间/IP/方法/路径/UA/Referer,跳过静态资源),nps 隧道透传 `X-Forwarded-For` 可拿到外网真实 IP;新增 `usage-stats.sh` + `usage-stats.py` 一键统计:总请求数、独立 IP 数、按天分布、Top IP、直播观看人数
|
||||
|
||||
@@ -79,6 +79,7 @@ docker restart katelyatv
|
||||
|
||||
## 📝 更新日志(最近)
|
||||
|
||||
- **2026-10-30 v-fixed35**:授权/公告/版本推送系统 —— 授权中心统计安装与在线人数、公告弹窗 + TVBOX notice 推送、新版提示;右上角显示当前版本号 `vfixed35`;新增每 IP 限流防恶意刷流量(接口 240/分、直播 30/分)
|
||||
- **2026-10-29 v-fixed34**:新增访问日志与使用统计 —— 外网访问者真实 IP/UA 全记录,`./usage-stats.sh [24h|all]` 一键查看独立 IP 数、按天分布、直播观看人数
|
||||
- **2026-10-29 v-fixed33**:桌面导航与直播页右上角新增「⭐ 开源地址」入口;镜像发布至 `gitea.88531.cn/jinghui/katelyatv` 公共仓库(免登录 `docker pull`)
|
||||
- **2026-10-26 v-fixed32**:站点更名为「米视TV」(界面 / 标题 / TVBOX 内置名称 / manifest 全量替换,支持 `SITE_NAME` 环境变量自定义)
|
||||
|
||||
@@ -72,6 +72,19 @@ DOCKER_CONFIG=/tmp/emptydockercfg docker pull jpccr.ccs.tencentyun.com/jinghui/k
|
||||
- 个人版仓库默认私有挡匿名 pull;**改公开用云 API 秒批**(本机 20 仓已全量公开):TC3 签名调 `ModifyRepositoryAccessPersonal`(`RepoName=jinghui/<名>`, `Public=1`, Region `ap-tokyo`,密钥 `/root/.tencent_api_creds`);核验 = 匿名取 token 后 `GET /v2/jinghui/<名>/tags/list` 200;注意 `DescribeRepositoryFilterPersonal` 列表会漏个别仓库(用 `ValidateRepositoryExistPersonal` 兜底)
|
||||
- 仓库私有不挡 push,只挡匿名 pull
|
||||
|
||||
## 发版后:授权中心登记版本行(触发「发现新版本」推送)
|
||||
|
||||
镜像双渠道推完后,在 CardAuth(`auth.88531.cn`,project **11**)登记本次版本:
|
||||
|
||||
```bash
|
||||
# SQL 走 /tmp/run_ann.sh(远端脚本,参数=SQL 文件);脚本与 SQL 见 /root/ 或会话 scratch
|
||||
# INSERT INTO ca_project_versions (project_id, version, changelog, download_url, released_at) ...
|
||||
# 注意:发版前插入会让现网 fixed35 站点自报客户端版本=fixed35,不弹;旧版实例会弹
|
||||
```
|
||||
|
||||
- 心跳里客户端上报 `SITE_VERSION`(compose env),中心据此判定 `update_available`
|
||||
- 公告在 `ca_announcements` 插 `project_id=11` 行即 60s 内全网推送
|
||||
|
||||
## 硬规则
|
||||
|
||||
- `.env`、镜像 tar、token 永不入库(`.gitignore` 已覆盖)
|
||||
|
||||
@@ -29,6 +29,14 @@ services:
|
||||
# 豆瓣海报图片代理(走站内 /api/image-proxy,绕过 doubanio 防盗链)
|
||||
NEXT_PUBLIC_IMAGE_PROXY: "http://192.168.68.19:3030/api/image-proxy?url="
|
||||
NEXT_PUBLIC_DOUBAN_PROXY: "http://192.168.68.19:3030/api/image-proxy?url="
|
||||
|
||||
# 授权中心(CardAuth 遥测:安装/在线统计、公告推送、版本推送)
|
||||
HUB_URL: ${HUB_URL:-https://auth.88531.cn}
|
||||
HUB_API_KEY: ${HUB_API_KEY:-}
|
||||
HUB_PROJECT_ID: ${HUB_PROJECT_ID:-11}
|
||||
HUB_DISABLED: ${HUB_DISABLED:-0}
|
||||
# 当前版本号(右上角角标 + 授权中心自检上报)
|
||||
SITE_VERSION: ${SITE_VERSION:-fixed35}
|
||||
depends_on:
|
||||
- katelyatv-redis
|
||||
volumes:
|
||||
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
"use strict";
|
||||
/* LICENSE-HUB-V1 — CardAuth 授权中心客户端(米视TV project 11)
|
||||
* 功能:安装登记(check-update)、在线心跳(heartbeat)、公告(announcements)、版本推送
|
||||
* 配置:HUB_URL / HUB_API_KEY / HUB_PROJECT_ID / SITE_VERSION / HUB_DISABLED
|
||||
* 原则:失败开放 —— 授权中心不可达绝不影响站点任何功能;
|
||||
* 机器码只存服务端(Redis),绝不下发浏览器。
|
||||
*/
|
||||
const NET = require("net");
|
||||
const FS = require("fs");
|
||||
const CRYPTO = require("crypto");
|
||||
|
||||
const HUB_URL = (process.env.HUB_URL || "https://auth.88531.cn").replace(/\/+$/, "");
|
||||
const API_KEY = process.env.HUB_API_KEY || "";
|
||||
const PROJECT_ID = String(process.env.HUB_PROJECT_ID || "11");
|
||||
const VERSION = process.env.SITE_VERSION || "dev";
|
||||
const DISABLED = process.env.HUB_DISABLED === "1";
|
||||
const REDIS_HOST = (process.env.REDIS_URL || "redis://katelyatv-redis:6379").replace(/^redis:\/\//, "").split("/")[0].split(":");
|
||||
const HB_MS = 30 * 60 * 1000, CK_MS = 6 * 60 * 60 * 1000, AN_MS = 60 * 1000, TIMEOUT = 8000;
|
||||
|
||||
const state = {
|
||||
machine_id: null, install_id: null, latest: "", update_available: false,
|
||||
changelog: "", download_url: "", version: VERSION,
|
||||
announcements: [], popup: null, hub_ok: false, last_msg: ""
|
||||
};
|
||||
|
||||
// ---- 极简 RESP 客户端(GET/SET/AUTH,够用即可) ----
|
||||
function parseResp(t) {
|
||||
if (!t.length) return { done: false };
|
||||
const c = t[0];
|
||||
if (c === "+" || c === ":") { const i = t.indexOf("\r\n"); return i < 0 ? { done: false } : { done: true, value: t.slice(1, i) }; }
|
||||
if (c === "-") { const i = t.indexOf("\r\n"); return i < 0 ? { done: false } : { done: true, value: null, err: t.slice(1, i) }; }
|
||||
if (c === "$") {
|
||||
const i = t.indexOf("\r\n"); if (i < 0) return { done: false };
|
||||
const n = Number(t.slice(1, i)); if (n < 0) return { done: true, value: null };
|
||||
return t.length >= i + 2 + n + 2 ? { done: true, value: t.slice(i + 2, i + 2 + n) } : { done: false };
|
||||
}
|
||||
return { done: true, value: null };
|
||||
}
|
||||
function redisCmd(args) {
|
||||
return new Promise((resolve, reject) => {
|
||||
try {
|
||||
const s = NET.connect(Number(REDIS_HOST[1] || 6379), REDIS_HOST[0]);
|
||||
let buf = "", done = false, authed = !process.env.REDIS_PASSWORD;
|
||||
const enc = (a) => { let p = "*" + a.length + "\r\n"; for (const x of a) p += "$" + Buffer.byteLength(String(x)) + "\r\n" + x + "\r\n"; return p; };
|
||||
const finish = (v) => { if (!done) { done = true; try { s.destroy(); } catch (e) {} resolve(v); } };
|
||||
const fail = (e) => { if (!done) { done = true; try { s.destroy(); } catch (e2) {} reject(e); } };
|
||||
s.setTimeout(TIMEOUT, () => fail(new Error("redis-timeout")));
|
||||
s.on("error", fail);
|
||||
s.on("connect", () => { if (!authed) s.write(enc(["AUTH", process.env.REDIS_PASSWORD])); s.write(enc(args)); });
|
||||
s.on("data", (d) => {
|
||||
buf += d.toString();
|
||||
if (!authed) {
|
||||
if (buf.startsWith("+")) { authed = true; buf = ""; s.write(enc(args)); return; }
|
||||
if (buf.startsWith("-")) return fail(new Error("redis-auth"));
|
||||
return;
|
||||
}
|
||||
const r = parseResp(buf);
|
||||
if (r.done) finish(r.value);
|
||||
});
|
||||
} catch (e) { reject(e); }
|
||||
});
|
||||
}
|
||||
|
||||
const FILE_ID = "/app/data/hub-install.json";
|
||||
async function ensureMachine() {
|
||||
if (state.machine_id) return state.machine_id;
|
||||
let mid = null;
|
||||
try { mid = await redisCmd(["GET", "license:machine_id"]); } catch (e) {}
|
||||
if (!mid) { try { mid = JSON.parse(FS.readFileSync(FILE_ID, "utf8")).machine_id; } catch (e) {} }
|
||||
if (!mid || !/^\d{10,16}$/.test(String(mid))) {
|
||||
mid = String(CRYPTO.randomInt(1e12, 9e12)); // 13位数字
|
||||
try { await redisCmd(["SET", "license:machine_id", String(mid)]); } catch (e) {}
|
||||
try { FS.mkdirSync("/app/data", { recursive: true }); FS.writeFileSync(FILE_ID, JSON.stringify({ machine_id: mid })); } catch (e) {}
|
||||
}
|
||||
state.machine_id = String(mid);
|
||||
return state.machine_id;
|
||||
}
|
||||
|
||||
async function hubPost(path, extra) {
|
||||
const mid = await ensureMachine();
|
||||
const ctl = new AbortController();
|
||||
const tm = setTimeout(() => ctl.abort(), TIMEOUT);
|
||||
try {
|
||||
const r = await fetch(HUB_URL + path, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", "X-Api-Key": API_KEY, "X-Project-Id": PROJECT_ID },
|
||||
body: JSON.stringify(Object.assign({ machine_id: mid, client_version: VERSION, device_info: "docker/katelyatv " + VERSION }, extra || {})),
|
||||
signal: ctl.signal
|
||||
});
|
||||
return await r.json();
|
||||
} finally { clearTimeout(tm); }
|
||||
}
|
||||
|
||||
async function checkUpdate(silent) {
|
||||
if (!API_KEY) return;
|
||||
try {
|
||||
const j = await hubPost("/api/public/installations/check-update", {});
|
||||
if (j && j.code === 200 && j.data) {
|
||||
state.install_id = j.data.install_id;
|
||||
state.latest = j.data.latest_version || "";
|
||||
state.update_available = !!j.data.update_available;
|
||||
state.changelog = j.data.changelog || "";
|
||||
state.download_url = j.data.download_url || "";
|
||||
state.hub_ok = true; state.last_msg = "ok";
|
||||
if (!silent) console.log("[LICENSE] update-check install_id=" + state.install_id + " latest=" + (state.latest || "-") + " available=" + state.update_available);
|
||||
} else {
|
||||
state.hub_ok = false; state.last_msg = JSON.stringify(j || {}).slice(0, 120);
|
||||
if (!silent) console.log("[LICENSE] update-check code-err " + state.last_msg);
|
||||
}
|
||||
} catch (e) { state.hub_ok = false; state.last_msg = String(e && e.message || e); if (!silent) console.log("[LICENSE] update-check err " + state.last_msg); }
|
||||
}
|
||||
|
||||
async function heartbeat() {
|
||||
if (!API_KEY) return;
|
||||
try {
|
||||
const j = await hubPost("/api/public/installations/heartbeat", {});
|
||||
if (j && j.code === 200) { state.hub_ok = true; console.log("[LICENSE] heartbeat ok install_id=" + ((j.data && j.data.install_id) || state.install_id)); }
|
||||
else { state.hub_ok = false; console.log("[LICENSE] heartbeat code-err " + JSON.stringify(j || {}).slice(0, 120)); }
|
||||
} catch (e) { state.hub_ok = false; console.log("[LICENSE] heartbeat err " + String(e && e.message || e)); }
|
||||
}
|
||||
|
||||
async function fetchAnnouncements() {
|
||||
const ctl = new AbortController();
|
||||
const tm = setTimeout(() => ctl.abort(), TIMEOUT);
|
||||
try {
|
||||
const r = await fetch(HUB_URL + "/api/public/announcements?target=client&project_id=" + PROJECT_ID + "&limit=10",
|
||||
{ headers: { "X-Api-Key": API_KEY, "X-Project-Id": PROJECT_ID }, signal: ctl.signal });
|
||||
const j = await r.json();
|
||||
if (j && j.code === 200 && j.data) {
|
||||
const ok = (arr) => (Array.isArray(arr) ? arr.filter(x => x && (x.project_id == null || String(x.project_id) === PROJECT_ID)) : []);
|
||||
state.announcements = ok(j.data.list);
|
||||
state.popup = ok(j.data.popup)[0] || state.announcements[0] || null; // 授权中心返回空列表即覆盖为空
|
||||
state.hub_ok = true;
|
||||
console.log("[LICENSE] announcements n=" + state.announcements.length + " popup=" + (state.popup ? String(state.popup.title || "").slice(0, 30) : "-"));
|
||||
}
|
||||
} catch (e) { /* 拉取失败保留上一次成功结果 */ }
|
||||
finally { clearTimeout(tm); }
|
||||
}
|
||||
|
||||
let started = false;
|
||||
function start() {
|
||||
if (started) return; started = true;
|
||||
if (DISABLED) { console.log("[LICENSE] telemetry disabled (HUB_DISABLED=1)"); return; }
|
||||
if (!API_KEY) { console.log("[LICENSE] no HUB_API_KEY, telemetry off"); return; }
|
||||
console.log("[LICENSE] hub=" + HUB_URL + " project=" + PROJECT_ID + " version=" + VERSION);
|
||||
(async () => { await ensureMachine(); await checkUpdate(); await heartbeat(); await fetchAnnouncements(); })();
|
||||
setInterval(() => heartbeat().catch(() => {}), HB_MS);
|
||||
setInterval(() => checkUpdate(true).catch(() => {}), CK_MS);
|
||||
setInterval(() => fetchAnnouncements().catch(() => {}), AN_MS);
|
||||
}
|
||||
|
||||
function getStatus() {
|
||||
return {
|
||||
version: VERSION, latest: state.latest || null, update_available: state.update_available,
|
||||
changelog: state.changelog || null, download_url: state.download_url || null,
|
||||
announcement: state.popup, announcements: state.announcements.slice(0, 5),
|
||||
hub_ok: state.hub_ok, updated_at: new Date().toISOString()
|
||||
};
|
||||
}
|
||||
function getNotice() {
|
||||
const p = state.popup;
|
||||
if (!p) return "";
|
||||
return String(p.title || "公告") + "\n" + String(p.content || "").slice(0, 500);
|
||||
}
|
||||
function getVersion() { return VERSION; }
|
||||
function getUpdateUrl() { return state.download_url || ""; }
|
||||
|
||||
module.exports = { start, getStatus, getNotice, getVersion, getUpdateUrl };
|
||||
@@ -0,0 +1,163 @@
|
||||
"use strict";
|
||||
/* PATCH-LICENSE-V1 — 在 katelyatv 容器内注入授权系统(容器内 node 运行,幂等)
|
||||
* 1) start-server.js 启动 license-hub
|
||||
* 2) 新增 /api/license-config 路由(以容器内 tvbox route 为模板做模块手术)
|
||||
* 3) app-path-routes-manifest 注册路由
|
||||
* 4) 导航 chunk 注入「版本号角标 + 公告/更新弹窗组件 HubNotice」
|
||||
* 5) tvbox 配置注入 notice/version/update_url
|
||||
* 所有修改均先 node --check,失败即抛错不写盘。
|
||||
*/
|
||||
const FS = require("fs");
|
||||
const CP = require("child_process");
|
||||
const VERSION = process.env.PATCH_VERSION || "fixed35";
|
||||
const log = (...a) => console.log("[PATCH-LICENSE]", ...a);
|
||||
let failures = [];
|
||||
function checkFile(p) {
|
||||
const r = CP.spawnSync(process.execPath, ["--check", p], { encoding: "utf8" });
|
||||
if (r.status !== 0) { console.error("[PATCH-LICENSE] CHECK-FAIL", p, "\n" + (r.stderr || "")); failures.push(p + ": " + (r.stderr || "").split("\n")[0]); return false; }
|
||||
return true;
|
||||
}
|
||||
function writeChecked(p, s) {
|
||||
const tmp = p.replace(/\.js$/, "") + ".licensetmp.js";
|
||||
FS.writeFileSync(tmp, s);
|
||||
if (!checkFile(tmp)) { console.error("[PATCH-LICENSE] tmp kept for inspection:", tmp); throw new Error("syntax check failed: " + p); }
|
||||
FS.renameSync(tmp, p);
|
||||
log("patched", p);
|
||||
}
|
||||
|
||||
// ---------- 1) start-server.js ----------
|
||||
(function () {
|
||||
const p = "/app/node_modules/next/dist/server/lib/start-server.js";
|
||||
let s = FS.readFileSync(p, "utf8");
|
||||
if (s.includes("LICENSE-HUB-V1")) { log("start-server: skip (already)"); return; }
|
||||
const a = "// <<< ACCESS-LOG-V1";
|
||||
if (!s.includes(a)) { failures.push("start-server anchor missing"); return; }
|
||||
const ins = a + '\n // >>> LICENSE-HUB-V1\n try { require("/app/license-hub.js").start(); } catch (e) { console.log("[LICENSE] boot-err", e && e.message); }\n // <<< LICENSE-HUB-V1';
|
||||
writeChecked(p, s.replace(a, ins));
|
||||
})();
|
||||
|
||||
// ---------- 1b) start-server.js 每IP限流(429,防恶意刷接口/直播) ----------
|
||||
(function () {
|
||||
const p = "/app/node_modules/next/dist/server/lib/start-server.js";
|
||||
let s = FS.readFileSync(p, "utf8");
|
||||
if (s.includes("RATE-LIMIT-V1")) { log("ratelimit: skip (already)"); return; }
|
||||
const a = "// <<< LICENSE-HUB-V1";
|
||||
if (!s.includes(a)) { failures.push("ratelimit anchor missing"); return; }
|
||||
const ins = a + [
|
||||
"\n // >>> RATE-LIMIT-V1",
|
||||
" try {",
|
||||
" const __rlMap = new Map();",
|
||||
' const __origReq = server.listeners("request");',
|
||||
' server.removeAllListeners("request");',
|
||||
' server.on("request", (req, res) => {',
|
||||
" try {",
|
||||
' const xff = req.headers["x-forwarded-for"];',
|
||||
' const ip = (xff ? String(xff).split(",")[0].trim() : "") || (req.socket && req.socket.remoteAddress) || "-";',
|
||||
' const u = String(req.url || "");',
|
||||
" const now = Date.now();",
|
||||
" let e = __rlMap.get(ip);",
|
||||
' if (!e || now - e.w0 > 60000) { e = { w0: now, n: 0, live: 0 }; if (__rlMap.size > 20000) __rlMap.clear(); __rlMap.set(ip, e); }',
|
||||
" e.n++;",
|
||||
' const isLive = u.indexOf("/api/tvbox") === 0 && /live=(ts|m3u8|lines|ch)/.test(u);',
|
||||
" if (isLive) e.live++;",
|
||||
" if (e.n > 240 || (isLive && e.live > 30)) {",
|
||||
' console.log("[RATE] 429 ip=" + ip + " n=" + e.n + " live=" + e.live + " " + u.slice(0, 60));',
|
||||
' res.writeHead(429, { "Content-Type": "text/plain; charset=utf-8", "Retry-After": "60" });',
|
||||
' res.end("Too Many Requests");',
|
||||
" return;",
|
||||
" }",
|
||||
" } catch (err) {}",
|
||||
" for (let i = 0; i < __origReq.length; i++) __origReq[i](req, res);",
|
||||
" });",
|
||||
' console.log("[RATE] per-ip limiter on (api=240/min, live=30/min)");',
|
||||
' } catch (e) { console.log("[RATE] init-err", e && e.message); }',
|
||||
" // <<< RATE-LIMIT-V1"
|
||||
].join("\n");
|
||||
writeChecked(p, s.replace(a, ins));
|
||||
})();
|
||||
|
||||
// ---------- 2) /api/license-config route ----------
|
||||
(function () {
|
||||
const dir = "/app/.next/server/app/api/license-config";
|
||||
const dst = dir + "/route.js";
|
||||
if (FS.existsSync(dst) && FS.readFileSync(dst, "utf8").includes("96282:(")) { log("route: skip (already)"); return; } // 旧版36282入口与tvbox撞号→强制重生
|
||||
const tplPath = "/app/.next/server/app/api/tvbox/route.js";
|
||||
const src = FS.readFileSync(tplPath, "utf8");
|
||||
const start = src.indexOf("36282:(e,o,t)=>{");
|
||||
const mark = src.indexOf(",13303:(", start);
|
||||
if (start < 0 || mark < 0) { failures.push("route template anchors missing"); return; }
|
||||
const newMod = '96282:(e,o,t)=>{t.r(o),t.d(o,{originalPathname:()=>C,patchFetch:()=>y,requestAsyncStorage:()=>g,routeModule:()=>f,serverHooks:()=>h,staticGenerationAsyncStorage:()=>d});var n={};t.r(n),t.d(n,{GET:()=>u,OPTIONS:()=>p,runtime:()=>l});var a=t(4762),i=t(20515),r=t(4894),s=t(40379);let l="nodejs";async function u(e){try{let hub=eval("require")("/app/license-hub.js"),st=hub.getStatus();return s.NextResponse.json({code:200,message:"ok",data:st},{headers:{"Content-Type":"application/json; charset=utf-8","Access-Control-Allow-Origin":"*","Cache-Control":"public, max-age=60"}})}catch(x){console.log("[LICENSE-CFG] ERR",x&&x.message);return s.NextResponse.json({code:500,message:String(x&&x.message||x),data:null},{headers:{"Access-Control-Allow-Origin":"*"}})}}async function p(){return new s.NextResponse(null,{status:200,headers:{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, OPTIONS","Access-Control-Allow-Headers":"Content-Type"}})}let m="standalone",f=new a.AppRouteRouteModule({definition:{kind:i.x.APP_ROUTE,page:"/api/license-config/route",pathname:"/api/license-config",filename:"route",bundlePath:"app/api/license-config/route"},resolvedPagePath:"/app/src/app/api/license-config/route.ts",nextConfigOutput:m,userland:n}),{requestAsyncStorage:g,staticGenerationAsyncStorage:d,serverHooks:h}=f,C="/api/license-config/route";function y(){return(0,r.patchFetch)({serverHooks:h,staticGenerationAsyncStorage:d})}}';
|
||||
let out = src.slice(0, start) + newMod + "," + src.slice(mark + 1);
|
||||
out = out.replace("()=>__webpack_exec__(36282)", "()=>__webpack_exec__(96282)"); // 入口改独有号,避开共享runtime上tvbox的36282执行缓存
|
||||
FS.mkdirSync(dir, { recursive: true });
|
||||
writeChecked(dst, out);
|
||||
// nft.json 照抄 login 路由
|
||||
try { FS.copyFileSync("/app/.next/server/app/api/login/route.js.nft.json", dir + "/route.js.nft.json"); log("route: nft copied"); }
|
||||
catch (e) { log("route: nft copy failed (non-fatal):", e.message); }
|
||||
// manifest 注册
|
||||
const mp = "/app/.next/app-path-routes-manifest.json";
|
||||
const man = JSON.parse(FS.readFileSync(mp, "utf8"));
|
||||
if (man["/api/license-config/route"]) { log("manifest: skip"); return; }
|
||||
man["/api/license-config/route"] = "/api/license-config";
|
||||
FS.writeFileSync(mp, JSON.stringify(man, null, 2));
|
||||
log("manifest: registered /api/license-config");
|
||||
})();
|
||||
|
||||
// ---------- 3) 导航 chunk:版本角标 + HubNotice ----------
|
||||
(function () {
|
||||
const dir = "/app/.next/static/chunks";
|
||||
let target = null;
|
||||
for (const f of FS.readdirSync(dir)) {
|
||||
if (!f.endsWith(".js")) continue;
|
||||
const p = dir + "/" + f;
|
||||
if (FS.readFileSync(p, "utf8").includes('href:"https://github.com/katelya77/KatelyaTV"')) { target = p; break; }
|
||||
}
|
||||
if (!target) { failures.push("chunk with 开源地址 anchor not found"); return; }
|
||||
let s = FS.readFileSync(target, "utf8");
|
||||
|
||||
const comp = [
|
||||
'function HubNotice(){',
|
||||
'let ov=null,dead=!1;',
|
||||
'(0,u.useEffect)(()=>{const T=setTimeout(()=>{fetch("/api/license-config",{cache:"no-store"}).then(r=>r.json()).then(j=>{if(dead||!j||200!==j.code||!j.data)return;const d=j.data;let ann=null;try{const seen=JSON.parse(localStorage.getItem("hub_seen")||"{}");if(d.announcement&&!seen["a"+d.announcement.id])ann=d.announcement}catch(e){}let upd=null;try{upd=(d.update_available&&localStorage.getItem("hub_ver_dismiss")!==String(d.latest||""))?d:null}catch(e){}if(!ann&&!upd)return;ov=document.createElement("div");ov.className="fixed inset-0 z-[9999] flex items-center justify-center bg-black/50 p-4";ov.style.backdropFilter="blur(4px)";const card=document.createElement("div");card.className="bg-white dark:bg-gray-800 rounded-2xl shadow-2xl max-w-md w-full max-h-[80vh] flex flex-col overflow-hidden";const head=document.createElement("div");head.className="flex items-center justify-between px-6 pt-5 pb-3";const h3=document.createElement("h3");h3.className="text-base font-bold text-gray-900 dark:text-gray-100 truncate mr-2";h3.textContent=ann?String(ann.title||"📢 公告"):"发现新版本 v"+String(upd&&upd.latest||"");const xb=document.createElement("button");xb.className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-200 text-lg leading-none flex-shrink-0";xb.textContent="✕";head.appendChild(h3);head.appendChild(xb);const bd=document.createElement("div");bd.className="px-6 pb-2 overflow-y-auto text-sm text-gray-700 dark:text-gray-300 whitespace-pre-wrap";bd.textContent=ann?String(ann.content||""):String(upd&&upd.changelog||"").slice(0,600);const ver=document.createElement("div");ver.className="mt-3 text-xs text-gray-400 dark:text-gray-500";ver.textContent="当前版本 v"+String(upd&&upd.version||"");bd.appendChild(ver);card.appendChild(head);card.appendChild(bd);const closeAnn=()=>{try{if(ann){const s=JSON.parse(localStorage.getItem("hub_seen")||"{}");s["a"+ann.id]=1;localStorage.setItem("hub_seen",JSON.stringify(s))}}catch(e){}if(ov&&ov.parentNode)ov.parentNode.removeChild(ov)};xb.onclick=closeAnn;if(upd||ann&&ann.link_url){const foot=document.createElement("div");foot.className="px-6 py-4 bg-gray-50 dark:bg-gray-700/50 flex items-center justify-end gap-2";if(ann&&ann.link_url){const la=document.createElement("a");la.href=ann.link_url;la.target="_blank";la.rel="noopener";la.className="px-3 py-1.5 rounded-lg text-xs font-medium text-purple-600 dark:text-purple-400 hover:bg-purple-500/10";la.textContent="查看详情 →";foot.appendChild(la)}if(upd){const ok=document.createElement("button");ok.className="px-4 py-1.5 rounded-lg text-xs font-medium text-white bg-purple-600 hover:bg-purple-700";ok.textContent="我知道了";ok.onclick=()=>{try{localStorage.setItem("hub_ver_dismiss",String(upd.latest||""))}catch(e){}if(ov&&ov.parentNode)ov.parentNode.removeChild(ov)};foot.appendChild(ok)}else{const cb=document.createElement("button");cb.className="px-3 py-1.5 rounded-lg text-xs font-medium text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-600";cb.textContent="关闭";cb.onclick=closeAnn;foot.appendChild(cb)}card.appendChild(foot)}ov.appendChild(card);ov.onclick=(e)=>{if(e.target===ov)closeAnn()};document.body.appendChild(ov)}).catch(()=>{})},1200);return()=>{dead=!0;if(ov&&ov.parentNode)ov.parentNode.removeChild(ov)}},[]);',
|
||||
'return null}',
|
||||
''
|
||||
].join("\n");
|
||||
|
||||
// 3a) 先剥离旧注入(修 bug 后可整块重打,幂等)
|
||||
const anchorI = "let I=()=>{let e=(0,x.useRouter)()";
|
||||
const anchorOpen = '(0,a.jsx)("a",{href:"https://github.com/katelya77/KatelyaTV"';
|
||||
const hi = s.indexOf("function HubNotice(){");
|
||||
if (hi >= 0) {
|
||||
const ai = s.indexOf(anchorI, hi);
|
||||
if (ai < 0) { failures.push("reinject: anchorI missing after HubNotice"); return; }
|
||||
s = s.slice(0, hi) + s.slice(ai);
|
||||
log("chunk: stripped old HubNotice");
|
||||
}
|
||||
const bs = s.indexOf('(0,a.jsx)("span",{className:"hidden lg:inline-flex');
|
||||
if (bs >= 0) {
|
||||
const ao = s.indexOf(anchorOpen, bs);
|
||||
if (ao < 0) { failures.push("reinject: anchorOpen missing after badge"); return; }
|
||||
s = s.slice(0, bs) + s.slice(ao);
|
||||
log("chunk: stripped old badge");
|
||||
}
|
||||
// 3b) 组件定义放在 let I=()=>{ 前(模块作用域,u/a 绑定可用),角标+弹窗渲染在开源地址按钮前
|
||||
if (!s.includes(anchorI)) { failures.push("chunk anchor I missing"); return; }
|
||||
s = s.replace(anchorI, comp + "\n" + anchorI);
|
||||
const badge = '(0,a.jsx)("span",{className:"hidden lg:inline-flex items-center select-none rounded-lg px-2 py-1.5 text-xs font-bold tracking-wide text-purple-600 dark:text-purple-400 bg-purple-500/10 border border-purple-500/20",title:"米视TV 当前版本",children:"v' + VERSION + '"}),(0,a.jsx)(HubNotice,{}),';
|
||||
s = s.replace(anchorOpen, badge + anchorOpen);
|
||||
writeChecked(target, s);
|
||||
})();
|
||||
|
||||
// ---------- 4) tvbox 配置:notice/version/update_url ----------
|
||||
(function () {
|
||||
const p = "/app/.next/server/app/api/tvbox/route.js";
|
||||
let s = FS.readFileSync(p, "utf8");
|
||||
if (s.includes("_hubNST")) { log("tvbox: skip (already)"); return; } // 实际插入标记是 _hubNST/_NST_V1
|
||||
const a = 'let l={spider:"",wallpaper:';
|
||||
if (!s.includes(a)) { failures.push("tvbox anchor missing"); return; }
|
||||
const ins = 'let _hubNST=null;try{_hubNST=eval("require")("/app/license-hub.js")}catch(e){}let l={notice:_hubNST&&_hubNST.getNotice?_hubNST.getNotice():"",version:_hubNST&&_hubNST.getVersion?_hubNST.getVersion():"",update_url:_hubNST&&_hubNST.getUpdateUrl?_hubNST.getUpdateUrl():"",_NST_V1:1,spider:"",wallpaper:';
|
||||
writeChecked(p, s.replace(a, ins));
|
||||
})();
|
||||
|
||||
if (failures.length) { console.error("[PATCH-LICENSE] FAILURES:", JSON.stringify(failures)); process.exit(1); }
|
||||
log("all patches applied");
|
||||
@@ -41,3 +41,18 @@ if pages:
|
||||
for p, c in pages.most_common(8):
|
||||
print(f" {p:24s} {c}")
|
||||
print("\n提示: NAT/共享出口 IP 会把多人算一个;同一人换网络会算多个 —— 数字为近似值。")
|
||||
|
||||
# ---------- TVBOX 客户端统计 ----------
|
||||
tb_req, tb_ips, tb_live_ips, ua_tb = 0, set(), set(), collections.Counter()
|
||||
for ts, ip, m, p, ua in rows:
|
||||
if p.startswith("/api/tvbox"):
|
||||
tb_req += 1
|
||||
tb_ips.add(ip)
|
||||
ua_tb[ua or "(none)"] += 1
|
||||
if is_live(p):
|
||||
tb_live_ips.add(ip)
|
||||
print(f"\n===== TVBOX =====")
|
||||
print(f"配置/接口请求 {tb_req} 次,独立 IP {len(tb_ips)};其中看直播 IP {len(tb_live_ips)}")
|
||||
print("Top UA:")
|
||||
for ua, c in ua_tb.most_common(6):
|
||||
print(f" {ua[:56]:56s} {c}")
|
||||
Reference in new issue
Block a user