164 lines
13 KiB
JavaScript
164 lines
13 KiB
JavaScript
"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");
|