Document VIP ops vs Nomadro admin hosts and ship LIVE/tag assets.

Hard-separate admin.hackrobot.cn (VIP ops) from admin.nomadro.cn forever; add live_ops bus, overlay tags, and deploy helpers.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Eric 2026-11-15 02:38:03 +08:00
parent e1ff83e96c
commit 29b8bdc55e
16 changed files with 2695 additions and 11 deletions

View File

@ -0,0 +1,25 @@
# 管理后台域名:永远禁止混淆
## 铁律
**`https://admin.hackrobot.cn/` 与 `https://admin.nomadro.cn/` 永远不允许混淆。**
改后台、部署、反代、注入脚本、鉴权、文档时必须先认域名;禁止把 A 的包/API/文案套到 B。
| 域名 | 产品 | 后端 | 源码 / 产物 | 鉴权 |
|------|------|------|-------------|------|
| **admin.hackrobot.cn** | **VIP 运营台**(`vip.hackrobot.cn`) | `/api/ops` → nomadvip `:4007`;`/api/admin/live/*` → nomadmini `:8010` | 独立 VIP SPA(勿用 Nomadro 微信壳覆盖) | `vip_ops_token`(HMAC) |
| **admin.nomadro.cn** | Nomadro 中国站后台(微信 / 抖音) | Nomadro API / PocketBase | `apps/admin` → admin.nomadro.cn | ebook/admin JWT |
| admin.nomadro.com | Nomadro 国际站后台(仅 Web) | `.com` API | `apps/com/admin` | `.com` admin 会话 |
## 禁止
- 把 `apps/admin`(微信/抖音壳)部署成 `admin.hackrobot.cn`
- 把 VIP 运营台 `/api` 整站指到 `:8010` 导致 `/api/ops` 失效
- 用 UI locale /「都叫 admin」假定两边同一套用户、拉黑、LIVE、支付
- 在文档或脚本里用「管理后台」不写全称域名
## 正确习惯
- VIP LIVE / 拉黑存档 / 线索 → 只谈 **admin.hackrobot.cn** + **vip.hackrobot.cn**
- 微信小程序运营 / 抖音模块 → 只谈 **admin.nomadro.cn** + `apps/admin`
- 国际 Web 运营 → **admin.nomadro.com** + `apps/com/admin`

View File

@ -2,6 +2,8 @@
Follow `.cursor/rules/*.mdc`。
**管理后台域名永远禁止混淆**:dmin.hackrobot.cn = VIP 运营台(vip.hackrobot.cn);dmin.nomadro.cn = Nomadro 中国站微信/抖音后台(pps/admin);dmin.nomadro.com = 国际站(pps/com/admin)。禁止互盖包/互指 API。见 .cursor/rules/admin-hosts-never-confuse.mdc。
**发版核心:`nomadro.com`(美国机)**。`.com` 分中文/国际受众;中文轨测稳后再**独立同步** `.cn`(中国机)。未点名域名时默认部署 `.com`,见 `com-first-deploy.mdc`。链路:`.com` → `.cn`(Next) → Taro H5 → 微信/抖音/小红书(微信为中国核心)。
**未经允许,不能上线前端**(写死):见 `.cursor/skills/no-frontend-deploy-without-ok` + `.cursor/rules/no-frontend-deploy-without-ok.mdc`。无本轮明确许可勿上传 `.next` / admin dist / 小程序包。

View File

@ -1,5 +1,19 @@
# Nomadro
> **管理后台域名铁律(永远禁止混淆)**
>
> | 域名 | 是什么 | 不是什么 |
> |------|--------|----------|
> | [admin.hackrobot.cn](https://admin.hackrobot.cn/) | **VIP 运营台**(服务 [vip.hackrobot.cn](https://vip.hackrobot.cn/):线索 / 拉黑存档 / LIVE 在线与弹窗通知) | 不是 Nomadro 微信/抖音后台 |
> | [admin.nomadro.cn](https://admin.nomadro.cn/) | Nomadro **中国站**管理 SPA(pps/admin:微信 / 抖音) | 不是 VIP 运营台;禁止用它的包覆盖 hackrobot |
> | [admin.nomadro.com](https://admin.nomadro.com/) | Nomadro **国际站**管理 SPA(pps/com/admin,美国 VPS,无小程序) | 与上两者均独立 |
>
> 反代、发版、鉴权、LIVE 注入、文档里写「管理后台」时必须带全称域名。规则见 \.cursor/rules/admin-hosts-never-confuse.mdc\。
2026-11-15:VIP 运营台实时能力 — dmin.hackrobot.cn LIVE 在线/弹窗通知(ops token ↔ /api/admin/live)、用户拉黑/曾拉黑 tag 与身份提示;**写死** dmin.hackrobot.cn 与 dmin.nomadro.cn 永远禁止混淆。资产 pps/admin/deploy/_vip_live_assets/ · API live_ops/ops_live。
2026-11-10:`test14` 收尾(`8935269` / tag `2026-11-10`)后切换 `test15` 开发。基线含社区主题 1–4、后台体验主题切换、反馈图片灯箱、招聘首页底部化、本地皮肤调试小球。见 [test14 收尾](docs/test14-closeout.md) · [test15 开发](docs/test15-development.md)。
2026-11-09:`test14` 门户、后端及 `.com` 管理后台已获许可并部署美国机。门户构建 `T9G517UdX-JND3zgNO3SD`;修复生产通知/预约代理自循环,公网接口恢复 200。门户/后台静态资源哈希、服务健康与后台鉴权验证通过,`.cn` 未同步。备份与验收见 [test14 上线记录](docs/test14-release.md)。
@ -53,6 +67,7 @@ scripts/ 本地开发 / 清理(dev-api · clean-artifacts)
| **咖啡聊预约** | `/social/coffeechat` | `src/modules/coffee` · FastAPI `coffee_svc` `/api/coffee/v1`(Cal.com 域:日程/时段/预约) |
| VIP | `/vip` | `src/modules/vip`(微信小程序原生页,见下) |
| 后台 .cn | admin.nomadro.cn | `apps/admin`(`/wechat` · `/douyin`) |
| **VIP 运营台** | **admin.hackrobot.cn** | 独立 VIP SPA(vip.hackrobot.cn);**禁止**与 admin.nomadro.cn 混淆;LIVE/拉黑见 _vip_live_assets |
| 后台 .com | admin.nomadro.com | `apps/com/admin`(**仅 Web**;美国 VPS) |
| API | api.nomadro.cn | `apps/api` |

View File

@ -0,0 +1,149 @@
/*! admin-leads-online.js — animate 在线 column on /leads without touching SPA bundle */
(function () {
"use strict";
if (window.__adminLeadsOnlineBooted) return;
window.__adminLeadsOnlineBooted = true;
if (!/admin\.hackrobot\.cn$/i.test(location.hostname)) return;
var TTL_MS = 120000;
var STYLE_ID = "admin-leads-online-style";
function ensureStyle() {
if (document.getElementById(STYLE_ID)) return;
var s = document.createElement("style");
s.id = STYLE_ID;
s.textContent =
"@keyframes comOnlinePulse{0%{box-shadow:0 0 0 0 rgba(52,211,153,.55)}70%{box-shadow:0 0 0 8px rgba(52,211,153,0)}100%{box-shadow:0 0 0 0 rgba(52,211,153,0)}}" +
"@keyframes comOnlineGlow{0%,100%{filter:none}50%{filter:drop-shadow(0 0 6px rgba(52,211,153,.4))}}" +
".alo-cell{display:inline-flex;flex-direction:column;align-items:flex-start;gap:4px;min-width:64px}" +
".alo-badge{display:inline-flex;align-items:center;gap:6px;padding:3px 8px;border-radius:999px;font-size:10px;font-weight:800;letter-spacing:.1em}" +
".alo-badge.on{color:#6ee7b7;border:1px solid rgba(52,211,153,.4);background:rgba(52,211,153,.08);animation:comOnlineGlow 2s ease-in-out infinite}" +
".alo-badge.on i{width:7px;height:7px;border-radius:50%;background:#34d399;animation:comOnlinePulse 1.6s ease-out infinite}" +
".alo-badge.off{color:#a8a29e;border:1px solid rgba(168,162,158,.25);background:rgba(255,255,255,.03)}" +
".alo-time{font-size:12px;color:#a8a29e}" +
".alo-badge.on + .alo-time,.alo-cell.is-live .alo-time{color:#6ee7b7;font-weight:600}" +
"th.alo-th-live{color:#6ee7b7}" +
"tr.alo-row-live td:first-child{animation:comOnlineGlow 2.4s ease-in-out infinite}";
document.head.appendChild(s);
}
function parseTs(text, title) {
// title often full locale string; text is relative like 刚刚 / 3分钟前
if (title && title !== "—") {
var d = Date.parse(title.replace(/年|月/g, "/").replace(/日/g, " "));
if (!Number.isNaN(d)) return d;
d = Date.parse(title);
if (!Number.isNaN(d)) return d;
}
var t = (text || "").trim();
if (!t || t === "—") return 0;
if (t === "刚刚") return Date.now();
var m = t.match(/^(\d+)\s*秒/);
if (m) return Date.now() - Number(m[1]) * 1000;
m = t.match(/^(\d+)\s*分钟/);
if (m) return Date.now() - Number(m[1]) * 60000;
m = t.match(/^(\d+)\s*小时/);
if (m) return Date.now() - Number(m[1]) * 3600000;
return 0;
}
function paintCell(td, live) {
if (!td) return;
if (td.getAttribute("data-alo") === "1") {
var badge = td.querySelector(".alo-badge");
var time = td.querySelector(".alo-time");
if (badge) {
badge.className = "alo-badge " + (live ? "on" : "off");
badge.innerHTML = live ? "<i></i>在线" : "离线";
}
td.classList.toggle("is-live", !!live);
var tr = td.closest("tr");
if (tr) tr.classList.toggle("alo-row-live", !!live);
return;
}
var rawText = (td.textContent || "").trim();
var title = td.getAttribute("title") || "";
td.setAttribute("data-alo", "1");
td.innerHTML = "";
var wrap = document.createElement("div");
wrap.className = "alo-cell" + (live ? " is-live" : "");
var badge = document.createElement("span");
badge.className = "alo-badge " + (live ? "on" : "off");
badge.innerHTML = live ? "<i></i>在线" : "离线";
var time = document.createElement("span");
time.className = "alo-time";
time.textContent = rawText || "—";
if (title) time.title = title;
wrap.appendChild(badge);
wrap.appendChild(time);
td.appendChild(wrap);
var tr = td.closest("tr");
if (tr) tr.classList.toggle("alo-row-live", !!live);
}
function findOnlineColIndex(table) {
var ths = table.querySelectorAll("thead th");
for (var i = 0; i < ths.length; i++) {
var label = (ths[i].textContent || "").trim();
if (label === "最近活跃" || label === "在线" || label.indexOf("活跃") >= 0) {
ths[i].classList.add("alo-th-live");
if (label === "最近活跃") ths[i].textContent = "在线";
return i;
}
}
return 0; // leads list first col
}
function enhance() {
if (!location.pathname.replace(/\/$/, "").endsWith("/leads") && location.pathname !== "/leads") {
// also allow /leads with query
if (location.pathname.replace(/\/+$/, "") !== "/leads") return;
}
ensureStyle();
var tables = document.querySelectorAll("table.com-table");
tables.forEach(function (table) {
var idx = findOnlineColIndex(table);
var rows = table.querySelectorAll("tbody tr");
rows.forEach(function (tr) {
var tds = tr.querySelectorAll("td");
if (!tds.length || idx >= tds.length) return;
var td = tds[idx];
var title = td.getAttribute("title") || "";
var text = td.getAttribute("data-alo") === "1"
? (td.querySelector(".alo-time") || {}).textContent || ""
: (td.textContent || "").trim();
// Prefer title absolute time; if missing, relative text
var ts = parseTs(text, title);
var live = ts > 0 && Date.now() - ts < TTL_MS;
// relative "刚刚" / N分钟
if (!ts) {
var rel = text;
if (td.getAttribute("data-alo") === "1") {
rel = (td.querySelector(".alo-time") || {}).textContent || "";
}
if (rel === "刚刚" || /^\d+\s*秒/.test(rel) || /^[1-2]\s*分钟/.test(rel)) live = true;
}
paintCell(td, live);
});
});
}
function boot() {
ensureStyle();
enhance();
setInterval(enhance, 5000);
var obs = new MutationObserver(function () {
enhance();
});
obs.observe(document.documentElement, { childList: true, subtree: true });
window.addEventListener("popstate", function () {
setTimeout(enhance, 50);
});
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", boot);
} else {
boot();
}
})();

View File

@ -0,0 +1,275 @@
/*! admin-live.js — LIVE online + broadcast dock for admin.hackrobot.cn VIP 运营台 */
(function () {
"use strict";
if (window.__adminLiveBooted) return;
window.__adminLiveBooted = true;
if (!/admin\.hackrobot\.cn$/i.test(location.hostname)) return;
var TOKEN_KEY = "vip_ops_token";
var API_ONLINE = "/api/admin/live/online";
var API_BC = "/api/admin/live/broadcast";
var API_STREAM = "/api/admin/live/stream";
var POLL_MS = 5000;
function token() {
try {
return localStorage.getItem(TOKEN_KEY) || "";
} catch (e) {
return "";
}
}
function authHeaders() {
var t = token();
return t
? { Authorization: "Bearer " + t, "Content-Type": "application/json" }
: { "Content-Type": "application/json" };
}
function el(tag, attrs, kids) {
var n = document.createElement(tag);
if (attrs) {
Object.keys(attrs).forEach(function (k) {
if (k === "style" && typeof attrs[k] === "object") {
Object.assign(n.style, attrs[k]);
} else if (k === "text") {
n.textContent = attrs[k];
} else if (k.slice(0, 2) === "on") {
n.addEventListener(k.slice(2).toLowerCase(), attrs[k]);
} else {
n.setAttribute(k, attrs[k]);
}
});
}
(kids || []).forEach(function (c) {
if (c == null) return;
n.appendChild(typeof c === "string" ? document.createTextNode(c) : c);
});
return n;
}
function ensureStyle() {
if (document.getElementById("admin-live-style")) return;
var s = document.createElement("style");
s.id = "admin-live-style";
s.textContent =
"@keyframes alPulse{0%,100%{opacity:1}50%{opacity:.45}}" +
"@keyframes alIn{from{opacity:0;transform:translateY(12px) scale(.98)}to{opacity:1;transform:none}}" +
"#admin-live-fab{position:fixed;right:18px;bottom:18px;z-index:2147482500;display:flex;align-items:center;gap:8px;padding:12px 16px;min-height:44px;border-radius:999px;border:1px solid rgba(245,158,11,.45);background:linear-gradient(135deg,#1a1408,#0c0c0f 55%,#121016);color:#fbbf24;font:600 13px/1.2 'DM Sans',Syne,system-ui,sans-serif;cursor:pointer;box-shadow:0 12px 40px rgba(0,0,0,.45),0 0 0 1px rgba(245,158,11,.12);backdrop-filter:blur(10px)}" +
"#admin-live-fab .dot{width:8px;height:8px;border-radius:50%;background:#22c55e;box-shadow:0 0 10px #22c55e;animation:alPulse 1.6s ease-in-out infinite}" +
"#admin-live-fab[data-off=1] .dot{background:#78716c;box-shadow:none;animation:none}" +
"#admin-live-panel{position:fixed;right:14px;bottom:72px;z-index:2147482501;width:min(380px,calc(100vw - 28px));max-height:min(72vh,560px);overflow:auto;border-radius:16px;border:1px solid rgba(245,158,11,.28);background:linear-gradient(165deg,#141418 0%,#0c0c0f 60%,#1a1408 100%);color:#e7e5e4;box-shadow:0 24px 60px rgba(0,0,0,.55);animation:alIn .28s ease;font-family:'DM Sans',system-ui,sans-serif;padding:14px}" +
"#admin-live-panel h3{margin:0 0 8px;font:700 15px/1.2 Syne,'DM Sans',sans-serif;color:#fbbf24;letter-spacing:.02em}" +
"#admin-live-panel .meta{font-size:12px;color:#a8a29e;margin-bottom:10px}" +
"#admin-live-panel .list{display:flex;flex-direction:column;gap:6px;margin:0 0 12px;max-height:180px;overflow:auto}" +
"#admin-live-panel .row{display:flex;flex-direction:column;gap:2px;padding:8px 10px;border-radius:10px;background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.06);font-size:12px}" +
"#admin-live-panel .row b{color:#fafaf9;font-weight:600}" +
"#admin-live-panel .row span{color:#a8a29e}" +
"#admin-live-panel label{display:block;font-size:11px;color:#a8a29e;margin:8px 0 4px}" +
"#admin-live-panel input,#admin-live-panel textarea,#admin-live-panel select{width:100%;box-sizing:border-box;border-radius:10px;border:1px solid rgba(255,255,255,.1);background:#0a0a0c;color:#f5f5f4;padding:10px 12px;font:400 13px/1.35 inherit;min-height:44px}" +
"#admin-live-panel textarea{min-height:72px;resize:vertical}" +
"#admin-live-panel .actions{display:flex;gap:8px;margin-top:12px}" +
"#admin-live-panel button{flex:1;min-height:44px;border-radius:12px;border:0;font:600 13px/1 inherit;cursor:pointer}" +
"#admin-live-panel .send{background:linear-gradient(135deg,#f59e0b,#d97706);color:#111}" +
"#admin-live-panel .ghost{background:rgba(255,255,255,.06);color:#e7e5e4}" +
"#admin-live-panel .msg{margin-top:8px;font-size:12px;color:#86efac}" +
"#admin-live-panel .err{color:#fda4af}" +
"#admin-live-panel .empty{font-size:12px;color:#78716c;padding:8px 0}";
document.head.appendChild(s);
}
var state = { open: false, online: [], ok: false, err: "", busy: false };
var fab, panel;
function renderList() {
if (!panel) return;
var list = panel.querySelector(".list");
list.innerHTML = "";
if (!state.online.length) {
list.appendChild(
el("div", { class: "empty", text: state.ok ? "当前无人在线" : "等待连接…" })
);
return;
}
state.online.slice(0, 40).forEach(function (u) {
var title = u.nick || u.email || u.id || "访客";
var sub = [u.page || "/", u.role || "", u.email && u.nick ? u.email : ""]
.filter(Boolean)
.join(" · ");
list.appendChild(
el("div", { class: "row" }, [el("b", { text: title }), el("span", { text: sub })])
);
});
}
function syncFab() {
if (!fab) return;
fab.setAttribute("data-off", state.ok ? "0" : "1");
fab.querySelector(".lab").textContent = "LIVE · " + state.online.length;
}
async function refresh() {
var t = token();
if (!t) {
state.ok = false;
state.online = [];
syncFab();
if (state.open) renderList();
return;
}
try {
var res = await fetch(API_ONLINE, { headers: authHeaders(), credentials: "omit" });
if (!res.ok) throw new Error("HTTP " + res.status);
var data = await res.json();
state.online = Array.isArray(data.webOnline) ? data.webOnline : [];
state.ok = true;
} catch (e) {
state.ok = false;
}
syncFab();
if (state.open) renderList();
}
async function sendBroadcast() {
if (state.busy || !panel) return;
var title = panel.querySelector("[name=title]").value.trim();
var body = panel.querySelector("[name=body]").value.trim();
var cta = panel.querySelector("[name=cta]").value.trim() || "知道了";
var href = panel.querySelector("[name=href]").value.trim();
var tone = panel.querySelector("[name=tone]").value || "amber";
var msgEl = panel.querySelector(".msg");
if (!title) {
msgEl.className = "msg err";
msgEl.textContent = "请填写标题";
return;
}
state.busy = true;
msgEl.className = "msg";
msgEl.textContent = "发送中…";
try {
var res = await fetch(API_BC, {
method: "POST",
headers: authHeaders(),
credentials: "omit",
body: JSON.stringify({
title: title,
body: body,
cta: cta,
href: href,
tone: tone,
ttlSec: 90,
}),
});
var data = await res.json().catch(function () {
return {};
});
if (!res.ok) throw new Error(data.detail || "HTTP " + res.status);
msgEl.className = "msg";
msgEl.textContent = "已推送到 vip.hackrobot.cn 在线用户";
panel.querySelector("[name=title]").value = "";
panel.querySelector("[name=body]").value = "";
} catch (e) {
msgEl.className = "msg err";
msgEl.textContent = (e && e.message) || "发送失败";
} finally {
state.busy = false;
}
}
function openPanel() {
if (panel) {
state.open = !state.open;
panel.style.display = state.open ? "block" : "none";
if (state.open) {
renderList();
refresh();
}
return;
}
panel = el("div", { id: "admin-live-panel" }, [
el("h3", { text: "实时在线 · 通知" }),
el("div", { class: "meta", text: "vip.hackrobot.cn 访客心跳 · 一键弹窗推送" }),
el("div", { class: "list" }),
el("label", { text: "标题" }),
el("input", { name: "title", placeholder: "例如:限时优惠", maxlength: "80" }),
el("label", { text: "正文" }),
el("textarea", { name: "body", placeholder: "弹窗内容(可选)", maxlength: "400" }),
el("label", { text: "按钮文案" }),
el("input", { name: "cta", value: "知道了", maxlength: "32" }),
el("label", { text: "跳转链接" }),
el("input", { name: "href", value: "https://vip.hackrobot.cn/", maxlength: "300" }),
el("label", { text: "色调" }),
el("select", { name: "tone" }, [
el("option", { value: "amber", text: "琥珀" }),
el("option", { value: "mint", text: "薄荷绿" }),
el("option", { value: "rose", text: "玫红" }),
]),
el("div", { class: "actions" }, [
el("button", {
class: "ghost",
type: "button",
text: "刷新",
onClick: function () {
refresh();
},
}),
el("button", {
class: "send",
type: "button",
text: "推送弹窗",
onClick: sendBroadcast,
}),
]),
el("div", { class: "msg" }),
]);
document.body.appendChild(panel);
state.open = true;
renderList();
}
function boot() {
ensureStyle();
fab = el(
"button",
{
id: "admin-live-fab",
type: "button",
title: "实时在线 / 通知",
onClick: openPanel,
},
[el("span", { class: "dot" }), el("span", { class: "lab", text: "LIVE · 0" })]
);
document.body.appendChild(fab);
refresh();
setInterval(refresh, POLL_MS);
try {
var t = token();
if (t && window.EventSource) {
var es = new EventSource(API_STREAM + "?token=" + encodeURIComponent(t));
es.addEventListener("tick", function (ev) {
try {
var data = JSON.parse(ev.data || "{}");
if (Array.isArray(data.webOnline)) {
state.online = data.webOnline;
state.ok = true;
syncFab();
if (state.open) renderList();
}
} catch (e) {}
});
es.onerror = function () {
try {
es.close();
} catch (e) {}
};
}
} catch (e) {}
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", boot);
} else {
boot();
}
})();

View File

@ -0,0 +1,272 @@
/*! admin-user-tags.js — blacklist/archive tags + identity across VIP ops */
(function () {
"use strict";
if (window.__adminUserTagsBooted) return;
window.__adminUserTagsBooted = true;
if (!/admin\.hackrobot\.cn$/i.test(location.hostname)) return;
var TOKEN_KEY = "vip_ops_token";
var STYLE_ID = "admin-user-tags-style";
var CACHE_MS = 20000;
var state = { blocks: [], archives: [], leads: [], byId: {}, fetchedAt: 0, busy: false };
function token() {
try { return localStorage.getItem(TOKEN_KEY) || ""; } catch (e) { return ""; }
}
function ensureStyle() {
if (document.getElementById(STYLE_ID)) return;
var s = document.createElement("style");
s.id = STYLE_ID;
s.textContent =
".aut-chip{display:inline-flex;align-items:center;gap:4px;margin-left:6px;padding:2px 8px;border-radius:999px;font-size:10px;font-weight:800;letter-spacing:.04em;vertical-align:middle;white-space:nowrap;cursor:help;line-height:1.4}" +
".aut-chip-block{color:#fecaca;border:1px solid rgba(248,113,113,.45);background:rgba(239,68,68,.14)}" +
".aut-chip-was{color:#fcd34d;border:1px solid rgba(245,158,11,.4);background:rgba(245,158,11,.12)}" +
".aut-hint{display:block;font-size:11px;color:#a8a29e;margin-top:2px;line-height:1.35}" +
"#admin-live-panel .row .aut-chip{margin-left:0;margin-top:2px}" +
"code.aut-marked{outline:1px dashed rgba(245,158,11,.25);outline-offset:2px;border-radius:4px}";
document.head.appendChild(s);
}
function norm(s) { return String(s || "").trim().toLowerCase(); }
function addKeys(map, key, info) {
var k = norm(key);
if (!k || k === "-" || k === "—") return;
var cur = map[k];
if (!cur) { map[k] = info; return; }
if (info.status === "blocked" || (info.status === "was" && cur.status !== "blocked")) {
map[k] = Object.assign({}, cur, info);
}
}
function rebuildIndex() {
var map = {};
(state.blocks || []).forEach(function (b) {
var info = {
status: "blocked",
reason: b.reason || "",
note: b.note || "",
kind: b.kind || "user",
at: b.createdAt || "",
by: b.createdBy || ""
};
addKeys(map, b.userId, info);
(b.aliases || []).forEach(function (a) { addKeys(map, a, info); });
});
(state.archives || []).forEach(function (a) {
var info = {
status: "was",
reason: a.reason || "",
note: a.note || "",
kind: a.kind || "user",
at: a.createdAt || "",
by: a.createdBy || "",
unblockedAt: a.unblockedAt || "",
unblockedBy: a.unblockedBy || ""
};
addKeys(map, a.userId, info);
(a.aliases || []).forEach(function (x) { addKeys(map, x, info); });
});
(state.leads || []).forEach(function (u) {
var ids = [u.key, u.display, u.email, u.openid, u.userId, u.ip].concat(u.aliases || []);
var hit = null;
for (var i = 0; i < ids.length; i++) {
hit = map[norm(ids[i])];
if (hit) break;
}
if (!hit && u.blocked) hit = { status: "blocked", reason: "线索标记", at: "", by: "" };
if (hit) ids.forEach(function (id) { addKeys(map, id, hit); });
});
state.byId = map;
}
function lookup() {
for (var i = 0; i < arguments.length; i++) {
var hit = state.byId[norm(arguments[i])];
if (hit) return hit;
}
return null;
}
function findLead() {
var ids = [];
for (var i = 0; i < arguments.length; i++) {
var n = norm(arguments[i]);
if (n) ids.push(n);
}
var leads = state.leads || [];
for (var li = 0; li < leads.length; li++) {
var u = leads[li];
var bag = [u.key, u.display, u.email, u.openid, u.userId, u.ip]
.concat(u.aliases || [])
.map(norm);
for (var j = 0; j < ids.length; j++) {
if (ids[j] && bag.indexOf(ids[j]) >= 0) return u;
}
}
return null;
}
function tipFor(info) {
if (!info) return "";
var parts = [];
if (info.status === "blocked") parts.push("当前拉黑");
if (info.status === "was") parts.push("历史拉黑(已解除,须重新付款开通)");
if (info.reason) parts.push("原因: " + info.reason);
if (info.note) parts.push("备注: " + info.note);
if (info.at) parts.push("拉黑: " + info.at);
if (info.unblockedAt) parts.push("解除: " + info.unblockedAt);
if (info.by) parts.push("操作: " + info.by);
return parts.join("\n");
}
function chipEl(info) {
var span = document.createElement("span");
if (info.status === "blocked") {
span.className = "aut-chip aut-chip-block";
span.textContent = "已拉黑";
} else {
span.className = "aut-chip aut-chip-was";
span.textContent = "曾拉黑";
}
span.title = tipFor(info);
return span;
}
function identityHint(lead) {
if (!lead) return null;
var bits = [];
var nick = null;
(lead.aliases || []).forEach(function (a) {
if (!a) return;
if (/^user\d+$/i.test(a)) return;
if (/^\d+\.\d+\.\d+\.\d+$/.test(a)) return;
if (/^smw/i.test(a)) return;
if (a.length >= 2 && a.length <= 32) nick = nick || a;
});
if (nick) bits.push("昵称 " + nick);
if (lead.email && lead.email !== lead.display) bits.push(lead.email);
if (lead.ip) bits.push("IP " + lead.ip);
if (!bits.length) return null;
var d = document.createElement("span");
d.className = "aut-hint";
d.textContent = bits.slice(0, 3).join(" · ");
d.title = bits.join("\n");
return d;
}
function paintNear(node, ids) {
if (!node || node.nodeType !== 1) return;
var info = lookup.apply(null, ids);
var lead = findLead.apply(null, ids);
var next = node.nextSibling;
while (next && next.nodeType === 1 && next.classList && next.classList.contains("aut-chip")) {
var rm = next;
next = next.nextSibling;
rm.remove();
}
if (info) {
node.classList.add("aut-marked");
node.insertAdjacentElement("afterend", chipEl(info));
}
var host = node.parentElement;
if (lead && host && node.tagName === "CODE" && !host.querySelector(":scope > .aut-hint")) {
var hint = identityHint(lead);
if (hint) host.appendChild(hint);
}
}
function enhanceCodes() {
document.querySelectorAll("code").forEach(function (code) {
if (code.closest("#admin-live-panel")) return;
paintNear(code, [(code.textContent || "").trim()]);
});
}
function enhanceLivePanel() {
var panel = document.getElementById("admin-live-panel");
if (!panel) return;
panel.querySelectorAll(".row").forEach(function (row) {
var b = row.querySelector("b");
var span = row.querySelector("span");
var ids = [];
if (b) ids.push(b.textContent || "");
if (span) {
String(span.textContent || "").split("·").forEach(function (p) {
ids.push(p.trim());
});
}
row.querySelectorAll(".aut-chip, .aut-hint").forEach(function (c) {
if (c.parentElement === row) c.remove();
});
var info = lookup.apply(null, ids);
if (info) row.appendChild(chipEl(info));
var hint = identityHint(findLead.apply(null, ids));
if (hint) row.appendChild(hint);
});
}
async function refreshData(force) {
var t = token();
if (!t) return;
if (!force && Date.now() - state.fetchedAt < CACHE_MS) return;
if (state.busy) return;
state.busy = true;
try {
var headers = { Authorization: "Bearer " + t };
var ctrl = await fetch("/api/ops/control", {
headers: headers,
credentials: "omit"
}).then(function (r) { return r.ok ? r.json() : {}; });
state.blocks = ctrl.blocks || [];
state.archives = ctrl.archives || [];
try {
var leads = await fetch("/api/ops/leads?limit=400", {
headers: headers,
credentials: "omit"
}).then(function (r) { return r.ok ? r.json() : {}; });
state.leads = leads.users || [];
} catch (e) {}
rebuildIndex();
state.fetchedAt = Date.now();
} catch (e) {
} finally {
state.busy = false;
}
}
var paintTimer = null;
function schedulePaint() {
if (paintTimer) return;
paintTimer = setTimeout(function () {
paintTimer = null;
try {
ensureStyle();
enhanceCodes();
enhanceLivePanel();
} catch (e) {}
}, 120);
}
async function tick() {
await refreshData(false);
schedulePaint();
}
function boot() {
ensureStyle();
tick();
setInterval(tick, 8000);
new MutationObserver(function () { schedulePaint(); }).observe(
document.documentElement,
{ childList: true, subtree: true }
);
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", boot);
} else {
boot();
}
})();

View File

@ -0,0 +1,191 @@
/*! vip-live.js — presence heartbeat + admin broadcast popup for vip.hackrobot.cn */
(function () {
"use strict";
if (window.__vipLiveBooted) return;
window.__vipLiveBooted = true;
var API_PRESENCE = "/api/vip/live/presence";
var API_STREAM = "/api/vip/live/stream";
var HEARTBEAT_MS = 20000;
var SEEN_KEY = "vip_live_seen_bc";
function lsGet(k) {
try {
return localStorage.getItem(k) || "";
} catch (e) {
return "";
}
}
function lsSet(k, v) {
try {
localStorage.setItem(k, v);
} catch (e) {}
}
function cookie(name) {
var m = document.cookie.match(new RegExp("(?:^|; )" + name + "=([^;]*)"));
return m ? decodeURIComponent(m[1]) : "";
}
function visitorId() {
var anon = cookie("nomadvip_anon_uid") || lsGet("userid") || lsGet("wechatUserId") || "";
if (anon) return String(anon).slice(0, 80);
var vid = lsGet("vip_live_vid");
if (!vid) {
vid = "web_" + Math.random().toString(36).slice(2, 10) + Date.now().toString(36).slice(-4);
lsSet("vip_live_vid", vid);
}
return vid;
}
function identity() {
var email = (lsGet("email") || lsGet("vipEmail") || "").trim().toLowerCase();
var name = (lsGet("name") || lsGet("nickname") || "").trim();
var role = (lsGet("role") || "").trim() || (lsGet("isVip") === "1" ? "vip" : "guest");
var openid = (lsGet("wechatUserId") || lsGet("userid") || "").trim();
return { email: email, nick: name, role: role, openid: openid };
}
function ping() {
var id = identity();
var body = {
visitorId: visitorId(),
openid: id.openid,
nick: id.nick,
email: id.email,
page: (location.pathname || "/") + (location.search || ""),
role: id.role,
};
try {
fetch(API_PRESENCE, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
credentials: "omit",
keepalive: true,
}).catch(function () {});
} catch (e) {}
}
function ensureStyles() {
if (document.getElementById("vip-live-style")) return;
var s = document.createElement("style");
s.id = "vip-live-style";
s.textContent =
"@keyframes vipLiveIn{from{opacity:0;transform:translateY(18px) scale(.96);filter:blur(6px)}to{opacity:1;transform:none;filter:none}}" +
"@keyframes vipLiveGlow{0%,100%{box-shadow:0 0 0 1px rgba(245,158,11,.35),0 24px 60px rgba(0,0,0,.45)}50%{box-shadow:0 0 0 1px rgba(245,158,11,.7),0 28px 70px rgba(245,158,11,.18)}}" +
"#vip-live-mask{position:fixed;inset:0;z-index:2147483000;display:flex;align-items:flex-end;justify-content:center;padding:20px;background:rgba(8,8,10,.55);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px)}" +
"@media(min-width:720px){#vip-live-mask{align-items:center}}" +
"#vip-live-card{width:min(420px,100%);border-radius:18px;padding:22px 22px 18px;background:linear-gradient(165deg,#141418 0%,#0c0c0f 55%,#1a1408 100%);color:#f5f5f4;border:1px solid rgba(245,158,11,.35);animation:vipLiveIn .45s cubic-bezier(.2,.8,.2,1),vipLiveGlow 3.2s ease-in-out infinite;font-family:ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,PingFang SC,Microsoft YaHei,sans-serif}" +
"#vip-live-card[data-tone=mint]{border-color:rgba(94,196,120,.45);background:linear-gradient(165deg,#121816,#0c0f0d 60%,#0f1a14)}" +
"#vip-live-card[data-tone=rose]{border-color:rgba(244,114,182,.4);background:linear-gradient(165deg,#181218,#0f0c0e 60%,#1a1014)}" +
"#vip-live-kicker{font-size:11px;letter-spacing:.14em;text-transform:uppercase;color:rgba(245,158,11,.9);margin:0 0 8px;font-weight:700}" +
"#vip-live-title{margin:0;font-size:22px;line-height:1.25;letter-spacing:-.02em;font-weight:750}" +
"#vip-live-body{margin:10px 0 0;font-size:14px;line-height:1.65;color:rgba(245,245,244,.78)}" +
"#vip-live-actions{display:flex;gap:10px;flex-wrap:wrap;margin-top:18px}" +
"#vip-live-actions button{min-height:44px;padding:0 16px;border-radius:12px;border:1px solid rgba(255,255,255,.12);background:#f59e0b;color:#111;font-weight:700;font-size:14px;cursor:pointer}" +
"#vip-live-actions button.ghost{background:transparent;color:#f5f5f4}";
document.head.appendChild(s);
}
function seenIds() {
try {
return JSON.parse(lsGet(SEEN_KEY) || "[]");
} catch (e) {
return [];
}
}
function markSeen(id) {
var arr = seenIds().filter(Boolean);
if (arr.indexOf(id) >= 0) return;
arr.unshift(id);
lsSet(SEEN_KEY, JSON.stringify(arr.slice(0, 30)));
}
function closePopup() {
var m = document.getElementById("vip-live-mask");
if (m) m.remove();
}
function showBroadcast(msg) {
if (!msg || !msg.id || !msg.title) return;
if (seenIds().indexOf(msg.id) >= 0) return;
ensureStyles();
closePopup();
markSeen(msg.id);
var mask = document.createElement("div");
mask.id = "vip-live-mask";
mask.setAttribute("role", "dialog");
mask.setAttribute("aria-modal", "true");
var card = document.createElement("div");
card.id = "vip-live-card";
card.setAttribute("data-tone", msg.tone || "amber");
card.innerHTML =
'<p id="vip-live-kicker">运营通知</p>' +
"<h2 id=\"vip-live-title\"></h2>" +
'<p id="vip-live-body"></p>' +
'<div id="vip-live-actions"></div>';
card.querySelector("#vip-live-title").textContent = String(msg.title || "");
var body = card.querySelector("#vip-live-body");
if (msg.body) body.textContent = String(msg.body);
else body.remove();
var actions = card.querySelector("#vip-live-actions");
var primary = document.createElement("button");
primary.type = "button";
primary.textContent = String(msg.cta || "知道了");
primary.onclick = function () {
if (msg.href) {
try {
window.open(String(msg.href), "_blank", "noopener");
} catch (e) {
location.href = String(msg.href);
}
}
closePopup();
};
actions.appendChild(primary);
if (msg.href) {
var ghost = document.createElement("button");
ghost.type = "button";
ghost.className = "ghost";
ghost.textContent = "稍后";
ghost.onclick = closePopup;
actions.appendChild(ghost);
}
mask.appendChild(card);
mask.addEventListener("click", function (e) {
if (e.target === mask) closePopup();
});
document.body.appendChild(mask);
var ttl = Math.max(8, Number(msg.ttlSec) || 60) * 1000;
window.setTimeout(closePopup, ttl);
}
function connectStream() {
if (!window.EventSource) return;
var es;
try {
es = new EventSource(API_STREAM);
} catch (e) {
return;
}
es.addEventListener("broadcast", function (ev) {
try {
showBroadcast(JSON.parse(ev.data));
} catch (e) {}
});
es.onerror = function () {
/* browser auto-reconnects */
};
}
ping();
window.setInterval(ping, HEARTBEAT_MS);
document.addEventListener("visibilitychange", function () {
if (document.visibilityState === "visible") ping();
});
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", connectStream);
} else {
connectStream();
}
})();

View File

@ -1,6 +1,6 @@
import { useCallback, useEffect, useMemo, useState } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { api } from '../api'
import { api, API_BASE, getToken } from '../api'
import {
WxBadge,
WxEmpty,
@ -30,10 +30,35 @@ type UserRow = {
unlocks: UnlockRow[]
}
const POLL_MS = 12_000
type WebVisitor = {
id: string
nick?: string
email?: string
page?: string
role?: string
ageSec?: number
online?: boolean
}
type Tab = 'vip' | 'nonvip' | 'all' | 'blocked'
type BroadcastForm = {
title: string
body: string
cta: string
href: string
tone: string
}
const POLL_MS = 30_000 // SSE 为主;轮询仅兜底解锁态
type Tab = 'vip' | 'nonvip' | 'all' | 'blocked' | 'online'
const VIP_BOOK_ID = '__vip__'
const EMPTY_BC: BroadcastForm = {
title: '',
body: '',
cta: '知道了',
href: 'https://vip.hackrobot.cn/',
tone: 'amber',
}
export default function VipUsers() {
const [searchParams, setSearchParams] = useSearchParams()
@ -48,6 +73,10 @@ export default function VipUsers() {
const [busy, setBusy] = useState('')
const [loading, setLoading] = useState(true)
const [openId, setOpenId] = useState<string | null>(deepOpenid || null)
const [webOnline, setWebOnline] = useState<WebVisitor[]>([])
const [liveOk, setLiveOk] = useState(false)
const [liveFlash, setLiveFlash] = useState(0)
const [bc, setBc] = useState<BroadcastForm>(EMPTY_BC)
const refresh = useCallback(
async (search = q, quiet = false) => {
@ -80,7 +109,88 @@ export default function VipUsers() {
// eslint-disable-next-line react-hooks/exhaustive-deps -- mount / deep-link only
}, [deepOpenid])
// 轮询在线态(小程序心跳 → last_seen)
// SSE 实时在线(Bearer 流);失败则降级轮询
useEffect(() => {
const token = getToken()
if (!token) return
const url = `${API_BASE}/api/admin/live/stream`
const ac = new AbortController()
let cancelled = false
async function pump() {
try {
const res = await fetch(url, {
headers: { Authorization: `Bearer ${token}`, Accept: 'text/event-stream' },
signal: ac.signal,
cache: 'no-store',
})
if (!res.ok || !res.body) throw new Error(`live ${res.status}`)
setLiveOk(true)
const reader = res.body.getReader()
const dec = new TextDecoder()
let buf = ''
while (!cancelled) {
const { done, value } = await reader.read()
if (done) break
buf += dec.decode(value, { stream: true })
const parts = buf.split('\n\n')
buf = parts.pop() || ''
for (const chunk of parts) {
const lines = chunk.split('\n')
let event = 'message'
let data = ''
for (const line of lines) {
if (line.startsWith('event:')) event = line.slice(6).trim()
if (line.startsWith('data:')) data += line.slice(5).trim()
}
if (!data) continue
try {
const payload = JSON.parse(data) as {
type?: string
webOnline?: WebVisitor[]
users?: Array<{ openid?: string; last_seen_at?: number }>
}
if (event === 'tick' || payload.type === 'tick') {
if (Array.isArray(payload.webOnline)) {
setWebOnline((prev) => {
const next = payload.webOnline || []
if (next.length !== prev.length) setLiveFlash((n) => n + 1)
return next
})
}
// Merge app online last_seen into local users quietly
if (Array.isArray(payload.users) && payload.users.length) {
const map = new Map(
payload.users
.filter((u) => u.openid)
.map((u) => [String(u.openid), u.last_seen_at || Date.now() / 1000]),
)
setUsers((prev) =>
prev.map((u) => {
const ts = map.get(u.openid)
if (!ts) return { ...u, online: false }
return { ...u, online: true, last_seen_at: ts }
}),
)
}
}
} catch {
/* ignore parse */
}
}
}
} catch {
if (!cancelled) setLiveOk(false)
}
}
void pump()
return () => {
cancelled = true
ac.abort()
}
}, [])
// 兜底轮询(解锁/备注等非在线字段)
useEffect(() => {
const id = window.setInterval(() => void refresh(q, true), POLL_MS)
return () => window.clearInterval(id)
@ -97,8 +207,16 @@ export default function VipUsers() {
if (u.unlocked_vip) vip += 1
else nonvip += 1
}
return { total: users.length, vip, nonvip, blocked, online }
}, [users])
return {
total: users.length,
vip,
nonvip,
blocked,
online,
web: webOnline.length,
live: online + webOnline.length,
}
}, [users, webOnline])
const filtered = useMemo(() => {
const rows = users.filter((u) => {
@ -106,6 +224,7 @@ export default function VipUsers() {
if (tab === 'vip' && !u.unlocked_vip) return false
if (tab === 'nonvip' && u.unlocked_vip) return false
if (tab === 'blocked' && !blocked) return false
if (tab === 'online' && !u.online) return false
return true
})
// 在线置顶
@ -117,6 +236,35 @@ export default function VipUsers() {
})
}, [users, tab])
async function sendBroadcast() {
if (!bc.title.trim()) {
setErr('请填写弹窗标题')
return
}
setBusy('broadcast')
setErr('')
setMsg('')
try {
await api('/api/admin/live/broadcast', {
method: 'POST',
body: JSON.stringify({
title: bc.title.trim(),
body: bc.body.trim(),
cta: bc.cta.trim() || '知道了',
href: bc.href.trim(),
tone: bc.tone || 'amber',
ttlSec: 60,
}),
})
setMsg('已推送到 vip.hackrobot.cn 在线访客')
setBc((f) => ({ ...f, title: '', body: '' }))
} catch (e: any) {
setErr(e.message || '推送失败')
} finally {
setBusy('')
}
}
async function run(key: string, fn: () => Promise<void>, okMsg?: string) {
setBusy(key)
setMsg('')
@ -143,7 +291,7 @@ export default function VipUsers() {
<WxHead
eyebrow="VIP 会员"
title="VIP用户"
desc={`会员身份(unlocks.__vip__)。小程序在线心跳约 90s 窗口;在线用户光效置顶。共 ${counts.total} 人 · VIP ${counts.vip} · 在线 ${counts.online}。`}
desc={`实时通道 ${liveOk ? '已连接' : '降级轮询'} · 小程序 + VIP 网页在线。读者 ${counts.total} · VIP ${counts.vip} · 在线 ${counts.live}(App ${counts.online} · Web ${counts.web})。`}
>
<Link className="wx-btn wx-btn-ghost" to="/wechat/orders?kind=vip">
VIP 订单
@ -173,14 +321,18 @@ export default function VipUsers() {
</WxToast>
) : null}
<div className="wx-stats" style={{ gridTemplateColumns: 'repeat(5, minmax(0, 1fr))' }}>
<div className="wx-stats" style={{ gridTemplateColumns: 'repeat(6, minmax(0, 1fr))' }}>
<div className="wx-stat">
<div className="wx-stat-label">读者池</div>
<div className="wx-stat-val">{counts.total}</div>
</div>
<div className="wx-stat wx-stat--online">
<div className="wx-stat-label">在线</div>
<div className="wx-stat-val">{counts.online}</div>
<div className={`wx-stat wx-stat--online${liveFlash ? ' is-live-flash' : ''}`}>
<div className="wx-stat-label">实时在线</div>
<div className="wx-stat-val">{counts.live}</div>
</div>
<div className="wx-stat">
<div className="wx-stat-label">网页访客</div>
<div className="wx-stat-val">{counts.web}</div>
</div>
<div className="wx-stat">
<div className="wx-stat-label">VIP</div>
@ -196,6 +348,89 @@ export default function VipUsers() {
</div>
</div>
<section className="wx-panel vip-live-panel">
<div className="vip-live-panel-head">
<div>
<h2 className="wx-panel-title">推送到 VIP 网页弹窗</h2>
<p className="wx-hint" style={{ display: 'block', marginTop: 6 }}>
向正在浏览 <code>vip.hackrobot.cn</code> 的访客实时弹窗(SSE)。标题必填。
</p>
</div>
<span className={`wx-live-pill${liveOk ? ' is-on' : ''}`}>
{liveOk ? 'LIVE' : 'OFFLINE'}
</span>
</div>
<div className="vip-bc-grid">
<label className="wx-field">
<span>标题</span>
<input
value={bc.title}
placeholder="例如:今晚 9 点直播答疑"
onChange={(e) => setBc({ ...bc, title: e.target.value })}
/>
</label>
<label className="wx-field">
<span>正文</span>
<input
value={bc.body}
placeholder="一句话说明(可选)"
onChange={(e) => setBc({ ...bc, body: e.target.value })}
/>
</label>
<label className="wx-field">
<span>按钮文案</span>
<input
value={bc.cta}
onChange={(e) => setBc({ ...bc, cta: e.target.value })}
/>
</label>
<label className="wx-field">
<span>链接(可选)</span>
<input
value={bc.href}
onChange={(e) => setBc({ ...bc, href: e.target.value })}
/>
</label>
<label className="wx-field">
<span>风格</span>
<select value={bc.tone} onChange={(e) => setBc({ ...bc, tone: e.target.value })}>
<option value="amber">琥珀</option>
<option value="mint">薄荷绿</option>
<option value="rose">玫红</option>
</select>
</label>
</div>
<div className="wx-toolbar" style={{ marginTop: 12 }}>
<button
type="button"
className="wx-btn"
disabled={busy === 'broadcast' || !bc.title.trim()}
onClick={() => void sendBroadcast()}
>
{busy === 'broadcast' ? '推送中…' : '推送弹窗'}
</button>
</div>
</section>
{webOnline.length ? (
<section className="wx-panel vip-web-online" aria-label="网页在线访客">
<h2 className="wx-panel-title">网页在线 · {webOnline.length}</h2>
<div className="vip-web-chips">
{webOnline.map((v) => (
<article key={v.id} className="vip-web-chip is-enter">
<span className="wx-online-dot" aria-hidden />
<div>
<strong>{v.nick || v.id.slice(-8)}</strong>
<div className="wx-hint">
{(v.role || 'guest') + (v.page ? ` · ${v.page}` : '')}
</div>
</div>
</article>
))}
</div>
</section>
) : null}
<section className="wx-panel">
<div className="wx-toolbar" style={{ marginBottom: 0 }}>
<input
@ -254,6 +489,7 @@ export default function VipUsers() {
value={tab}
onChange={setTab}
items={[
{ key: 'online', label: '在线', count: counts.online },
{ key: 'vip', label: 'VIP', count: counts.vip },
{ key: 'nonvip', label: '非会员', count: counts.nonvip },
{ key: 'all', label: '全部', count: counts.total },

View File

@ -0,0 +1,298 @@
# -*- coding: utf-8 -*-
"""Realtime ops: VIP presence + admin broadcast (SSE)."""
from __future__ import annotations
import asyncio
import base64
import hashlib
import hmac
import json
import os
import time
from typing import Annotated, Any
import jwt
from fastapi import APIRouter, Depends, Header, HTTPException, Query, Request
from fastapi.responses import JSONResponse, StreamingResponse
from pydantic import BaseModel, Field
from ebook_svc.core.rate_limit import rate_limit
from ebook_svc.services import ops_live
from ebook_svc.services.store import store
try:
from ebook_svc.config import settings # type: ignore
except Exception: # pragma: no cover
from ebook_svc.core.config import settings # type: ignore
router = APIRouter(tags=["live-ops"])
_SSE_HEADERS = {
"Cache-Control": "no-cache, no-transform",
"Connection": "keep-alive",
"X-Accel-Buffering": "no",
"Access-Control-Allow-Origin": "*",
}
def _b64url_decode(raw: str) -> bytes:
pad = "=" * (-len(raw) % 4)
return base64.urlsafe_b64decode(raw + pad)
def _b64url_encode(raw: bytes) -> str:
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
def _ops_secrets() -> list[str]:
"""Match nomadvip ops-auth.ts: VIP_OPS_SECRET || POCKETBASE_PASSWORD || default."""
out: list[str] = []
for key in ("VIP_OPS_SECRET", "POCKETBASE_PASSWORD"):
val = (os.environ.get(key) or "").strip()
if val and val not in out:
out.append(val)
for attr in ("vip_ops_secret", "pocketbase_password"):
val = str(getattr(settings, attr, "") or "").strip()
if val and val not in out:
out.append(val)
if "vip-ops-change-me" not in out:
out.append("vip-ops-change-me")
return out
def verify_ops_token(token: str) -> str | None:
"""Verify VIP 运营台 HMAC token (payload.sig, exp in ms)."""
parts = str(token or "").split(".")
if len(parts) != 2:
return None
payload, sig = parts
if not payload or not sig:
return None
for secret in _ops_secrets():
expect = _b64url_encode(
hmac.new(secret.encode("utf-8"), payload.encode("utf-8"), hashlib.sha256).digest()
)
try:
if len(sig) != len(expect) or not hmac.compare_digest(sig, expect):
continue
except Exception:
continue
try:
data = json.loads(_b64url_decode(payload).decode("utf-8"))
except Exception:
return None
user = str(data.get("u") or "").strip()
exp = data.get("exp")
if not user or not exp:
return None
try:
if time.time() * 1000 > float(exp):
return None
except Exception:
return None
return user
return None
async def require_admin_or_ops(
authorization: Annotated[str | None, Header()] = None,
token: str | None = Query(default=None),
) -> str:
"""Accept ebook admin JWT or VIP ops HMAC token (admin.hackrobot.cn 运营台)."""
auth = authorization
if (not auth or not auth.startswith("Bearer ")) and token:
auth = f"Bearer {token.strip()}"
if not auth or not auth.startswith("Bearer "):
raise HTTPException(401, "未登录管理后台")
raw = auth.removeprefix("Bearer ").strip()
try:
data = jwt.decode(raw, settings.jwt_secret, algorithms=["HS256"])
if data.get("role") == "admin":
return str(data.get("sub") or "admin")
except Exception:
pass
ops_user = verify_ops_token(raw)
if ops_user:
return ops_user
raise HTTPException(401, "登录已失效")
class PresenceIn(BaseModel):
visitorId: str = Field(default="", max_length=80)
openid: str = Field(default="", max_length=80)
nick: str = Field(default="", max_length=48)
email: str = Field(default="", max_length=160)
page: str = Field(default="/", max_length=160)
role: str = Field(default="guest", max_length=24)
class BroadcastIn(BaseModel):
title: str = Field(min_length=1, max_length=80)
body: str = Field(default="", max_length=400)
cta: str = Field(default="知道了", max_length=32)
href: str = Field(default="", max_length=300)
tone: str = Field(default="amber", max_length=24)
ttlSec: int = Field(default=60, ge=8, le=600)
def _sse(event: str, data: dict[str, Any]) -> str:
return f"event: {event}\ndata: {json.dumps(data, ensure_ascii=False)}\n\n"
def _admin_users_online() -> list[dict[str, Any]]:
rows = store.list_users(limit=200, q="")
out = []
for u in rows:
if not u.get("online"):
continue
out.append(
{
"openid": u.get("openid"),
"nickname": u.get("nickname"),
"notes": u.get("notes"),
"unlocked_vip": bool(u.get("unlocked_vip")),
"last_seen_at": u.get("last_seen_at"),
"status": u.get("status") or "active",
"source": "miniprogram",
}
)
return out
@router.post("/api/vip/live/presence")
@router.post("/api/ebook/vip/live/presence")
async def vip_presence(body: PresenceIn, request: Request):
rate_limit(request, bucket="vip.live.presence", limit=60, window_sec=60.0)
ua = (request.headers.get("user-agent") or "")[:180]
try:
row = ops_live.touch_presence(
visitor_id=body.visitorId or body.openid,
openid=body.openid,
nick=body.nick,
email=body.email,
page=body.page,
role=body.role,
ua=ua,
)
except ValueError as e:
raise HTTPException(400, str(e)) from e
# If looks like wechat openid, also refresh sqlite last_seen for VipUsers
oid = (body.openid or body.visitorId or "").strip()
if oid and not oid.startswith("user") and len(oid) >= 16:
try:
store.touch_last_seen(oid)
except Exception:
pass
return {"ok": True, "id": row["id"], "ttlSec": int(ops_live.PRESENCE_TTL_SEC)}
@router.get("/api/vip/live/stream")
@router.get("/api/ebook/vip/live/stream")
async def vip_live_stream():
"""Public SSE for vip.hackrobot.cn — receives admin broadcasts."""
try:
ops_live.bind_loop()
except Exception:
pass
queue = ops_live.register_listener()
async def gen():
try:
hello = {"type": "hello", "at": ops_live._now(), "channel": "vip"}
yield _sse("hello", hello)
for bc in ops_live.recent_broadcasts(1):
# only push if fresh (< ttl)
age = ops_live._now() - float(bc.get("at") or 0)
if age <= float(bc.get("ttlSec") or 60):
yield _sse("broadcast", bc)
while True:
try:
payload = await asyncio.wait_for(queue.get(), timeout=18.0)
except asyncio.TimeoutError:
yield ": ping\n\n"
continue
if not isinstance(payload, dict):
continue
if payload.get("type") == "broadcast":
yield _sse("broadcast", payload)
# presence ticks ignored on VIP client
finally:
ops_live.unregister_listener(queue)
return StreamingResponse(gen(), media_type="text/event-stream", headers=_SSE_HEADERS)
@router.get("/api/admin/live/online")
async def admin_live_online(_: str = Depends(require_admin_or_ops)):
return {
"ok": True,
"webOnline": ops_live.list_online(),
"appOnline": _admin_users_online(),
"recentBroadcasts": ops_live.recent_broadcasts(10),
}
@router.post("/api/admin/live/broadcast")
async def admin_live_broadcast(
body: BroadcastIn,
admin: str = Depends(require_admin_or_ops),
):
try:
msg = ops_live.publish_broadcast(
title=body.title,
body=body.body,
cta=body.cta,
href=body.href,
tone=body.tone,
ttl_sec=body.ttlSec,
admin=admin,
)
except ValueError as e:
raise HTTPException(400, str(e)) from e
return {"ok": True, "item": msg}
@router.get("/api/admin/live/stream")
async def admin_live_stream(
admin: str = Depends(require_admin_or_ops),
):
"""Admin SSE. Prefer Authorization; EventSource may pass ?token=."""
try:
ops_live.bind_loop()
except Exception:
pass
queue = ops_live.register_listener()
async def gen():
try:
snap = ops_live.snapshot(include_users=_admin_users_online())
snap["admin"] = admin
yield _sse("tick", snap)
while True:
try:
payload = await asyncio.wait_for(queue.get(), timeout=ops_live.ADMIN_TICK_SEC)
if isinstance(payload, dict) and payload.get("type") == "broadcast":
yield _sse("broadcast", payload)
# always refresh online snapshot on any event
tick = ops_live.snapshot(include_users=_admin_users_online())
yield _sse("tick", tick)
except asyncio.TimeoutError:
tick = ops_live.snapshot(include_users=_admin_users_online())
yield _sse("tick", tick)
finally:
ops_live.unregister_listener(queue)
return StreamingResponse(gen(), media_type="text/event-stream", headers=_SSE_HEADERS)
@router.options("/api/vip/live/{path:path}")
@router.options("/api/admin/live/{path:path}")
async def live_cors_options():
return JSONResponse(
content={"ok": True},
headers={
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET,POST,OPTIONS",
"Access-Control-Allow-Headers": "Authorization,Content-Type",
},
)

View File

@ -0,0 +1,175 @@
# -*- coding: utf-8 -*-
"""VIP / admin live ops bus — presence TTL + admin→VIP broadcast.
Process-local (single uvicorn worker). Admin SSE polls snapshot; VIP SSE gets push.
"""
from __future__ import annotations
import asyncio
import threading
import time
import uuid
from collections import deque
from typing import Any
_lock = threading.RLock()
_PRESENCE: dict[str, dict[str, Any]] = {}
_BROADCASTS: deque[dict[str, Any]] = deque(maxlen=40)
_LISTENERS: set[asyncio.Queue] = set()
_LOOP: asyncio.AbstractEventLoop | None = None
PRESENCE_TTL_SEC = 75.0
ADMIN_TICK_SEC = 3.0
def bind_loop(loop: asyncio.AbstractEventLoop | None = None) -> None:
global _LOOP
_LOOP = loop or asyncio.get_running_loop()
def _now() -> float:
return time.time()
def _prune(now: float | None = None) -> None:
t = now or _now()
dead = [k for k, v in _PRESENCE.items() if (t - float(v.get("ts") or 0)) > PRESENCE_TTL_SEC]
for k in dead:
_PRESENCE.pop(k, None)
def touch_presence(
*,
visitor_id: str,
nick: str = "",
email: str = "",
page: str = "",
role: str = "",
ua: str = "",
openid: str = "",
) -> dict[str, Any]:
vid = (visitor_id or openid or "").strip()[:80]
if not vid:
raise ValueError("missing visitor")
now = _now()
with _lock:
_prune(now)
row = {
"id": vid,
"nick": (nick or "")[:48] or (email.split("@")[0] if email else "")[:48] or vid[-8:],
"email": (email or "").strip().lower()[:160],
"page": (page or "/")[:160],
"role": (role or "guest")[:24],
"ua": (ua or "")[:180],
"openid": (openid or "")[:80],
"ts": now,
}
_PRESENCE[vid] = row
payload = {"type": "presence", "at": now, "online": list_online_unlocked()}
_fanout(payload)
return row
def list_online_unlocked() -> list[dict[str, Any]]:
now = _now()
_prune(now)
rows = sorted(_PRESENCE.values(), key=lambda r: float(r.get("ts") or 0), reverse=True)
out = []
for r in rows:
age = max(0.0, now - float(r.get("ts") or 0))
out.append({**r, "ageSec": round(age, 1), "online": True})
return out
def list_online() -> list[dict[str, Any]]:
with _lock:
return list_online_unlocked()
def publish_broadcast(
*,
title: str,
body: str = "",
cta: str = "",
href: str = "",
tone: str = "amber",
ttl_sec: int = 60,
admin: str = "",
) -> dict[str, Any]:
title_n = (title or "").strip()[:80]
if not title_n:
raise ValueError("title required")
msg = {
"type": "broadcast",
"id": f"bc_{uuid.uuid4().hex[:12]}",
"title": title_n,
"body": (body or "").strip()[:400],
"cta": (cta or "知道了").strip()[:32] or "知道了",
"href": (href or "").strip()[:300],
"tone": (tone or "amber")[:24],
"ttlSec": max(8, min(int(ttl_sec or 60), 600)),
"at": _now(),
"admin": (admin or "")[:64],
}
with _lock:
_BROADCASTS.appendleft(msg)
_fanout(msg)
return msg
def recent_broadcasts(limit: int = 10) -> list[dict[str, Any]]:
with _lock:
return list(_BROADCASTS)[: max(1, min(limit, 40))]
def snapshot(*, include_users: list[dict[str, Any]] | None = None) -> dict[str, Any]:
with _lock:
online = list_online_unlocked()
return {
"type": "tick",
"at": _now(),
"webOnline": online,
"webOnlineCount": len(online),
"users": include_users or [],
"recentBroadcasts": recent_broadcasts(5),
}
def register_listener() -> asyncio.Queue:
q: asyncio.Queue = asyncio.Queue(maxsize=64)
with _lock:
_LISTENERS.add(q)
return q
def unregister_listener(q: asyncio.Queue) -> None:
with _lock:
_LISTENERS.discard(q)
def _fanout(payload: dict[str, Any]) -> None:
with _lock:
listeners = list(_LISTENERS)
loop = _LOOP
if not listeners:
return
def _put(q: asyncio.Queue) -> None:
try:
q.put_nowait(payload)
except asyncio.QueueFull:
try:
_ = q.get_nowait()
except Exception:
pass
try:
q.put_nowait(payload)
except Exception:
pass
if loop and loop.is_running():
for q in listeners:
loop.call_soon_threadsafe(_put, q)
else:
for q in listeners:
_put(q)

View File

@ -391,6 +391,13 @@ class Store:
"UPDATE users SET last_seen_at=? WHERE openid=?",
(time.time(), openid),
)
# Notify admin live SSE (best-effort; ignore if bus unavailable)
try:
from ebook_svc.services import ops_live
ops_live._fanout({"type": "presence", "openid": openid, "source": "app"})
except Exception:
pass
def get_user_by_token(self, token: str) -> dict[str, Any] | None:
with self.conn() as c:

View File

@ -0,0 +1,281 @@
# -*- coding: utf-8 -*-
from pathlib import Path
JS = r"""/*! admin-user-tags.js — blacklist/archive tags + identity across VIP ops */
(function () {
"use strict";
if (window.__adminUserTagsBooted) return;
window.__adminUserTagsBooted = true;
if (!/admin\.hackrobot\.cn$/i.test(location.hostname)) return;
var TOKEN_KEY = "vip_ops_token";
var STYLE_ID = "admin-user-tags-style";
var CACHE_MS = 20000;
var state = { blocks: [], archives: [], leads: [], byId: {}, fetchedAt: 0, busy: false };
function token() {
try { return localStorage.getItem(TOKEN_KEY) || ""; } catch (e) { return ""; }
}
function ensureStyle() {
if (document.getElementById(STYLE_ID)) return;
var s = document.createElement("style");
s.id = STYLE_ID;
s.textContent =
".aut-chip{display:inline-flex;align-items:center;gap:4px;margin-left:6px;padding:2px 8px;border-radius:999px;font-size:10px;font-weight:800;letter-spacing:.04em;vertical-align:middle;white-space:nowrap;cursor:help;line-height:1.4}" +
".aut-chip-block{color:#fecaca;border:1px solid rgba(248,113,113,.45);background:rgba(239,68,68,.14)}" +
".aut-chip-was{color:#fcd34d;border:1px solid rgba(245,158,11,.4);background:rgba(245,158,11,.12)}" +
".aut-hint{display:block;font-size:11px;color:#a8a29e;margin-top:2px;line-height:1.35}" +
"#admin-live-panel .row .aut-chip{margin-left:0;margin-top:2px}" +
"code.aut-marked{outline:1px dashed rgba(245,158,11,.25);outline-offset:2px;border-radius:4px}";
document.head.appendChild(s);
}
function norm(s) { return String(s || "").trim().toLowerCase(); }
function addKeys(map, key, info) {
var k = norm(key);
if (!k || k === "-" || k === "—") return;
var cur = map[k];
if (!cur) { map[k] = info; return; }
if (info.status === "blocked" || (info.status === "was" && cur.status !== "blocked")) {
map[k] = Object.assign({}, cur, info);
}
}
function rebuildIndex() {
var map = {};
(state.blocks || []).forEach(function (b) {
var info = {
status: "blocked",
reason: b.reason || "",
note: b.note || "",
kind: b.kind || "user",
at: b.createdAt || "",
by: b.createdBy || ""
};
addKeys(map, b.userId, info);
(b.aliases || []).forEach(function (a) { addKeys(map, a, info); });
});
(state.archives || []).forEach(function (a) {
var info = {
status: "was",
reason: a.reason || "",
note: a.note || "",
kind: a.kind || "user",
at: a.createdAt || "",
by: a.createdBy || "",
unblockedAt: a.unblockedAt || "",
unblockedBy: a.unblockedBy || ""
};
addKeys(map, a.userId, info);
(a.aliases || []).forEach(function (x) { addKeys(map, x, info); });
});
(state.leads || []).forEach(function (u) {
var ids = [u.key, u.display, u.email, u.openid, u.userId, u.ip].concat(u.aliases || []);
var hit = null;
for (var i = 0; i < ids.length; i++) {
hit = map[norm(ids[i])];
if (hit) break;
}
if (!hit && u.blocked) hit = { status: "blocked", reason: "线索标记", at: "", by: "" };
if (hit) ids.forEach(function (id) { addKeys(map, id, hit); });
});
state.byId = map;
}
function lookup() {
for (var i = 0; i < arguments.length; i++) {
var hit = state.byId[norm(arguments[i])];
if (hit) return hit;
}
return null;
}
function findLead() {
var ids = [];
for (var i = 0; i < arguments.length; i++) {
var n = norm(arguments[i]);
if (n) ids.push(n);
}
var leads = state.leads || [];
for (var li = 0; li < leads.length; li++) {
var u = leads[li];
var bag = [u.key, u.display, u.email, u.openid, u.userId, u.ip]
.concat(u.aliases || [])
.map(norm);
for (var j = 0; j < ids.length; j++) {
if (ids[j] && bag.indexOf(ids[j]) >= 0) return u;
}
}
return null;
}
function tipFor(info) {
if (!info) return "";
var parts = [];
if (info.status === "blocked") parts.push("当前拉黑");
if (info.status === "was") parts.push("历史拉黑(已解除,须重新付款开通)");
if (info.reason) parts.push("原因: " + info.reason);
if (info.note) parts.push("备注: " + info.note);
if (info.at) parts.push("拉黑: " + info.at);
if (info.unblockedAt) parts.push("解除: " + info.unblockedAt);
if (info.by) parts.push("操作: " + info.by);
return parts.join("\n");
}
function chipEl(info) {
var span = document.createElement("span");
if (info.status === "blocked") {
span.className = "aut-chip aut-chip-block";
span.textContent = "已拉黑";
} else {
span.className = "aut-chip aut-chip-was";
span.textContent = "曾拉黑";
}
span.title = tipFor(info);
return span;
}
function identityHint(lead) {
if (!lead) return null;
var bits = [];
var nick = null;
(lead.aliases || []).forEach(function (a) {
if (!a) return;
if (/^user\d+$/i.test(a)) return;
if (/^\d+\.\d+\.\d+\.\d+$/.test(a)) return;
if (/^smw/i.test(a)) return;
if (a.length >= 2 && a.length <= 32) nick = nick || a;
});
if (nick) bits.push("昵称 " + nick);
if (lead.email && lead.email !== lead.display) bits.push(lead.email);
if (lead.ip) bits.push("IP " + lead.ip);
if (!bits.length) return null;
var d = document.createElement("span");
d.className = "aut-hint";
d.textContent = bits.slice(0, 3).join(" · ");
d.title = bits.join("\n");
return d;
}
function paintNear(node, ids) {
if (!node || node.nodeType !== 1) return;
var info = lookup.apply(null, ids);
var lead = findLead.apply(null, ids);
var next = node.nextSibling;
while (next && next.nodeType === 1 && next.classList && next.classList.contains("aut-chip")) {
var rm = next;
next = next.nextSibling;
rm.remove();
}
if (info) {
node.classList.add("aut-marked");
node.insertAdjacentElement("afterend", chipEl(info));
}
var host = node.parentElement;
if (lead && host && node.tagName === "CODE" && !host.querySelector(":scope > .aut-hint")) {
var hint = identityHint(lead);
if (hint) host.appendChild(hint);
}
}
function enhanceCodes() {
document.querySelectorAll("code").forEach(function (code) {
if (code.closest("#admin-live-panel")) return;
paintNear(code, [(code.textContent || "").trim()]);
});
}
function enhanceLivePanel() {
var panel = document.getElementById("admin-live-panel");
if (!panel) return;
panel.querySelectorAll(".row").forEach(function (row) {
var b = row.querySelector("b");
var span = row.querySelector("span");
var ids = [];
if (b) ids.push(b.textContent || "");
if (span) {
String(span.textContent || "").split("·").forEach(function (p) {
ids.push(p.trim());
});
}
row.querySelectorAll(".aut-chip, .aut-hint").forEach(function (c) {
if (c.parentElement === row) c.remove();
});
var info = lookup.apply(null, ids);
if (info) row.appendChild(chipEl(info));
var hint = identityHint(findLead.apply(null, ids));
if (hint) row.appendChild(hint);
});
}
async function refreshData(force) {
var t = token();
if (!t) return;
if (!force && Date.now() - state.fetchedAt < CACHE_MS) return;
if (state.busy) return;
state.busy = true;
try {
var headers = { Authorization: "Bearer " + t };
var ctrl = await fetch("/api/ops/control", {
headers: headers,
credentials: "omit"
}).then(function (r) { return r.ok ? r.json() : {}; });
state.blocks = ctrl.blocks || [];
state.archives = ctrl.archives || [];
try {
var leads = await fetch("/api/ops/leads?limit=400", {
headers: headers,
credentials: "omit"
}).then(function (r) { return r.ok ? r.json() : {}; });
state.leads = leads.users || [];
} catch (e) {}
rebuildIndex();
state.fetchedAt = Date.now();
} catch (e) {
} finally {
state.busy = false;
}
}
var paintTimer = null;
function schedulePaint() {
if (paintTimer) return;
paintTimer = setTimeout(function () {
paintTimer = null;
try {
ensureStyle();
enhanceCodes();
enhanceLivePanel();
} catch (e) {}
}, 120);
}
async function tick() {
await refreshData(false);
schedulePaint();
}
function boot() {
ensureStyle();
tick();
setInterval(tick, 8000);
new MutationObserver(function () { schedulePaint(); }).observe(
document.documentElement,
{ childList: true, subtree: true }
);
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", boot);
} else {
boot();
}
})();
"""
out = Path(__file__).resolve().parents[1] / "apps" / "admin" / "deploy" / "_vip_live_assets" / "admin-user-tags.js"
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(JS, encoding="utf-8", newline="\n")
print("wrote", out, out.stat().st_size)

View File

@ -0,0 +1,84 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
import sys
from pathlib import Path
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True)
ROOT = Path(__file__).resolve().parents[1]
SRC = ROOT / "apps" / "admin" / "deploy" / "_vip_live_assets" / "admin-user-tags.js"
HOST, USER, PASSWORD = "129.204.21.129", "ubuntu", "Xiao4669805"
REMOTE = r'''#!/bin/bash
set -euo pipefail
R=/www/wwwroot/admin.hackrobot.cn
sudo cp /tmp/admin-user-tags.js "$R/admin-user-tags.js"
sudo chmod 644 "$R/admin-user-tags.js"
# syntax check
node --check "$R/admin-user-tags.js"
python3 <<'PY'
from pathlib import Path
import time
p=Path('/www/wwwroot/admin.hackrobot.cn/index.html')
t=p.read_text(encoding='utf-8')
if 'admin-user-tags.js' not in t:
needle='<script src="/admin-live.js" defer></script>'
inject=needle + '\n <script src="/admin-user-tags.js" defer></script>'
if needle in t:
t=t.replace(needle, inject, 1)
else:
t=t.replace('</body>', ' <script src="/admin-user-tags.js" defer></script>\n </body>', 1)
# bust spa cache lightly
v=str(int(time.time()))
import re
t=re.sub(r'index-OYkETFeq\.js\?v=\d+', f'index-OYkETFeq.js?v={v}', t)
t=re.sub(r'index-DJrK42yQ\.css\?v=\d+', f'index-DJrK42yQ.css?v={v}', t)
p.write_text(t, encoding='utf-8')
print(p.read_text(encoding='utf-8'))
PY
curl -sk -o /dev/null -w 'tags:%{http_code}\n' https://admin.hackrobot.cn/admin-user-tags.js
curl -sk -o /dev/null -w 'admin:%{http_code}\n' https://admin.hackrobot.cn/
# ensure SPA still no liveTick / 拉黑存档 broken
python3 <<'PY'
from pathlib import Path
t=Path('/www/wwwroot/admin.hackrobot.cn/assets/index-OYkETFeq.js').read_text(encoding='utf-8')
assert 'liveTick' not in t
assert '拉黑存档' not in t
print('spa still clean')
PY
echo DONE
'''
def main() -> int:
# generate asset first
import runpy
runpy.run_path(str(ROOT / "scripts" / "_gen_admin_user_tags.py"))
if not SRC.is_file() or SRC.stat().st_size < 1000:
print("missing admin-user-tags.js")
return 1
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, 22, USER, PASSWORD, timeout=40, allow_agent=False, look_for_keys=False)
try:
sftp = c.open_sftp()
with sftp.file("/tmp/admin-user-tags.js", "wb") as f:
f.write(SRC.read_bytes())
with sftp.file("/tmp/deploy_admin_user_tags_129.sh", "wb") as f:
f.write(REMOTE.replace("\r\n", "\n").encode("utf-8"))
sftp.close()
_, o, e = c.exec_command("bash /tmp/deploy_admin_user_tags_129.sh", timeout=60)
print(o.read().decode("utf-8", "replace"), flush=True)
err = e.read().decode("utf-8", "replace")
if err.strip():
print(err[-1500:], file=sys.stderr, flush=True)
return o.channel.recv_exit_status()
finally:
c.close()
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,351 @@
# -*- coding: utf-8 -*-
"""Local-build then deploy VIP live ops to 129 (admin.hackrobot.cn + vip.hackrobot.cn)."""
from __future__ import annotations
import io
import subprocess
import sys
import tarfile
from pathlib import Path
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True)
ROOT = Path(__file__).resolve().parents[1]
HOST, USER, PASSWORD = "129.204.21.129", "ubuntu", "Xiao4669805"
ADMIN_DIST = ROOT / "apps" / "admin" / "dist"
ASSETS = ROOT / "apps" / "admin" / "deploy" / "_vip_live_assets"
API_ROOT = ROOT / "apps" / "api" / "services" / "ebook_svc"
API_FILES = [
(API_ROOT / "services" / "ops_live.py", "ops_live.py"),
(API_ROOT / "routers" / "live_ops.py", "live_ops.py"),
(API_ROOT / "services" / "store.py", "store.py"),
]
REMOTE_SH = r'''#!/bin/bash
set -euo pipefail
echo '=== free ==='
free -h | head -3
B=/opt/nomadmini/backend
if [ -d "$B/app" ]; then APP="$B/app"; else APP="$B"; fi
echo "APP=$APP"
sudo mkdir -p "$APP/services" "$APP/routers"
sudo cp /tmp/ops_live.py "$APP/services/ops_live.py"
sudo cp /tmp/live_ops.py "$APP/routers/live_ops.py"
sudo cp /tmp/store.py "$APP/services/store.py"
python3 /tmp/patch_main_live_ops.py
sudo systemctl restart nomadmini-api
sleep 2
systemctl is-active nomadmini-api
curl -sS -o /dev/null -w 'api_health:%{http_code}\n' --max-time 8 http://127.0.0.1:8010/health || true
curl -sS -o /dev/null -w 'vip_stream:%{http_code}\n' --max-time 8 http://127.0.0.1:8010/api/vip/live/stream || true
R=/www/wwwroot/admin.hackrobot.cn
sudo rm -rf "$R.new"
sudo mkdir -p "$R.new"
sudo tar -xzf /tmp/admin-hackrobot.tgz -C "$R.new"
sudo rm -rf "$R.old"
sudo mv "$R" "$R.old" 2>/dev/null || true
sudo mv "$R.new" "$R"
sudo rm -rf "$R.old"
sudo mkdir -p /www/wwwroot/nomadvip/public
sudo cp /tmp/vip-live.js /www/wwwroot/nomadvip/public/vip-live.js
sudo chmod 644 /www/wwwroot/nomadvip/public/vip-live.js
EXT=/www/server/panel/vhost/nginx/extension/vip.hackrobot.cn
sudo mkdir -p "$EXT"
sudo cp /tmp/vip-live-api.conf "$EXT/vip-live-api.conf"
sudo sed -i 's/\r$//' "$EXT/vip-live-api.conf"
AEXT=/www/server/panel/vhost/nginx/extension/admin.hackrobot.cn
sudo mkdir -p "$AEXT"
sudo cp /tmp/admin-live-sse.conf "$AEXT/admin-live-sse.conf"
sudo sed -i 's/\r$//' "$AEXT/admin-live-sse.conf"
# admin site did not include extension/*.conf — wire it before catch-all /api/
sudo python3 /tmp/patch_admin_nginx_include.py
# admin.hackrobot.cn /api/ops lives on VIP Next :4007 — do NOT point catch-all /api to 8010.
# Only /api/admin/live/* stays on 8010 via extension conf.
# sudo python3 /tmp/patch_admin_api_8010.py # DISABLED — breaks VIP 运营台
PROXY=$(sudo ls /www/server/panel/vhost/nginx/proxy/vip.hackrobot.cn/*.conf 2>/dev/null | head -1 || true)
if [ -n "$PROXY" ]; then
sudo python3 /tmp/patch_vip_proxy_inject.py "$PROXY"
else
echo 'WARN: vip proxy conf missing'
fi
sudo nginx -t
sudo nginx -s reload
sleep 1
echo '=== smoke ==='
curl -sk -o /dev/null -w 'admin:%{http_code}\n' --max-time 15 https://admin.hackrobot.cn/
curl -sk -o /dev/null -w 'admin_online:%{http_code}\n' --max-time 10 https://admin.hackrobot.cn/api/admin/live/online
curl -sk -o /dev/null -w 'vip:%{http_code}\n' --max-time 15 https://vip.hackrobot.cn/
curl -sk -o /dev/null -w 'vip-live.js:%{http_code}\n' --max-time 10 https://vip.hackrobot.cn/vip-live.js
curl -sk -o /dev/null -w 'presence:%{http_code}\n' -X POST https://vip.hackrobot.cn/api/vip/live/presence \
-H 'content-type: application/json' \
-d '{"visitorId":"deploy_smoke","nick":"smoke","page":"/","role":"guest"}'
curl -sk https://vip.hackrobot.cn/ | tr '\n' ' ' | grep -o 'vip-live.js' | head -1 || echo 'WARN: html inject missing'
free -h | head -3
echo DONE
'''
PATCH_MAIN = r'''# -*- coding: utf-8 -*-
from pathlib import Path
cands = [
Path("/opt/nomadmini/backend/app/main.py"),
Path("/opt/nomadmini/backend/main.py"),
]
insert = "\nfrom app.routers import live_ops\napp.include_router(live_ops.router)\n"
for p in cands:
if not p.is_file():
continue
t = p.read_text(encoding="utf-8")
if "live_ops" in t:
print("main already has live_ops", p)
break
if "include_router(audience_admin.router)" in t:
t = t.replace(
"app.include_router(audience_admin.router)",
"app.include_router(audience_admin.router)" + insert,
1,
)
p.write_text(t, encoding="utf-8")
print("patched", p)
break
t = t + insert
p.write_text(t, encoding="utf-8")
print("appended", p)
break
else:
print("WARN: main.py not found")
'''
PATCH_PROXY = r'''# -*- coding: utf-8 -*-
import re
import sys
from pathlib import Path
p = Path(sys.argv[1])
raw = p.read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n")
t = raw.decode("utf-8")
if "vip-live.js" in t:
print("inject already present")
raise SystemExit(0)
old = '<script src="/vip-track.js" defer></script></body>'
new = '<script src="/vip-track.js" defer></script><script src="/vip-live.js" defer></script></body>'
if old in t:
t = t.replace(old, new, 1)
p.write_bytes(t.encode("utf-8"))
print("inject beside vip-track")
raise SystemExit(0)
if "sub_filter" not in t:
m = re.search(r"location \^~ /\s*\{", t)
if m:
insert = (
'\n proxy_set_header Accept-Encoding "";'
"\n sub_filter_types text/html;"
"\n sub_filter '</body>' '<script src=\"/vip-live.js\" defer></script></body>';"
"\n sub_filter_once on;\n"
)
t = t[: m.end()] + insert + t[m.end() :]
p.write_bytes(t.encode("utf-8"))
print("inject sub_filter added")
raise SystemExit(0)
print("WARN: could not inject")
'''
PATCH_ADMIN_INCLUDE = r'''# -*- coding: utf-8 -*-
from pathlib import Path
p = Path("/www/server/panel/vhost/nginx/admin.hackrobot.cn.conf")
raw = p.read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n")
t = raw.decode("utf-8")
inc = "include /www/server/panel/vhost/nginx/extension/admin.hackrobot.cn/*.conf;"
if inc in t:
print("admin include already present")
else:
for needle in (
" # Ops API -> VIP next (4007)",
" # Ops API -> nomadmini (8010).",
):
if needle in t:
t = t.replace(
needle,
" # Live ops SSE/API (more specific than /api/)\n " + inc + "\n\n" + needle,
1,
)
print("admin include inserted")
break
else:
raise SystemExit("admin nginx include needle missing")
p.write_bytes(t.encode("utf-8"))
'''
PATCH_ADMIN_API_8010 = r'''# -*- coding: utf-8 -*-
from pathlib import Path
p = Path("/www/server/panel/vhost/nginx/admin.hackrobot.cn.conf")
raw = p.read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n")
t = raw.decode("utf-8")
if "proxy_pass http://127.0.0.1:8010;" in t and "location ^~ /api/" in t:
# still replace any leftover 4007 under /api/
if "proxy_pass http://127.0.0.1:4007;" in t:
t = t.replace("proxy_pass http://127.0.0.1:4007;", "proxy_pass http://127.0.0.1:8010;", 1)
print("replaced leftover 4007")
else:
print("admin api already 8010")
else:
if "proxy_pass http://127.0.0.1:4007;" not in t:
raise SystemExit("admin /api proxy_pass not found")
t = t.replace("proxy_pass http://127.0.0.1:4007;", "proxy_pass http://127.0.0.1:8010;", 1)
t = t.replace(
"proxy_set_header Host 127.0.0.1;",
"proxy_set_header Host $host;\n proxy_set_header Authorization $http_authorization;",
1,
)
t = t.replace("# Ops API -> VIP next (4007)", "# Ops API -> nomadmini (8010)", 1)
print("admin api patched to 8010")
p.write_bytes(t.encode("utf-8"))
'''
VIP_LIVE_API_CONF = """location ^~ /api/vip/live/ {
proxy_pass http://127.0.0.1:8010;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Connection '';
proxy_buffering off;
proxy_cache off;
proxy_read_timeout 3600s;
chunked_transfer_encoding off;
}
location = /vip-live.js {
root /www/wwwroot/nomadvip/public;
add_header Cache-Control "public, max-age=60";
}
"""
ADMIN_LIVE_SSE_CONF = """location ^~ /api/admin/live/ {
proxy_pass http://127.0.0.1:8010;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header Authorization $http_authorization;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Connection '';
proxy_buffering off;
proxy_cache off;
proxy_read_timeout 3600s;
chunked_transfer_encoding off;
}
"""
def to_app(text: str) -> str:
return text.replace("ebook_svc.", "app.")
def sh_local(cmd: list[str]) -> None:
print("$", " ".join(cmd), flush=True)
# Windows: pnpm is a .ps1 shim — run via shell so PATH resolves.
subprocess.check_call(" ".join(cmd) if sys.platform == "win32" else cmd, cwd=str(ROOT), shell=sys.platform == "win32")
def connect() -> paramiko.SSHClient:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
HOST,
22,
USER,
PASSWORD,
timeout=40,
allow_agent=False,
look_for_keys=False,
banner_timeout=60,
)
t = c.get_transport()
if t:
t.set_keepalive(20)
return c
def remote(c: paramiko.SSHClient, cmd: str, timeout: int = 240) -> str:
print(f"$ {cmd[:180].replace(chr(10), ' ')}", flush=True)
_, o, e = c.exec_command(cmd, timeout=timeout)
out = o.read().decode("utf-8", "replace")
err = e.read().decode("utf-8", "replace")
code = o.channel.recv_exit_status()
if out.strip():
print(out[-7000:], flush=True)
if err.strip():
print(err[-2000:], file=sys.stderr, flush=True)
if code:
raise RuntimeError(f"remote failed {code}")
return out
def put_text(sftp: paramiko.SFTPClient, remote_path: str, text: str) -> None:
# Always LF — CRLF breaks bash heredocs and nginx include files on Linux.
data = text.replace("\r\n", "\n").replace("\r", "\n").encode("utf-8")
with sftp.file(remote_path, "wb") as rf:
rf.write(data)
def main() -> int:
if not (ASSETS / "vip-live.js").is_file():
print("missing vip-live.js")
return 1
print("=== local build admin ===", flush=True)
sh_local(["pnpm", "build:admin"])
if not (ADMIN_DIST / "index.html").is_file():
print("admin dist missing")
return 1
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
for p in ADMIN_DIST.rglob("*"):
if p.is_file():
tar.add(p, arcname=p.relative_to(ADMIN_DIST).as_posix())
admin_blob = buf.getvalue()
print("admin pack", len(admin_blob), flush=True)
c = connect()
try:
sftp = c.open_sftp()
with sftp.file("/tmp/admin-hackrobot.tgz", "wb") as f:
f.write(admin_blob)
sftp.put(str(ASSETS / "vip-live.js"), "/tmp/vip-live.js")
for src, name in API_FILES:
text = to_app(src.read_text(encoding="utf-8"))
if "ebook_svc." in text:
raise SystemExit(f"rewrite failed: {name}")
put_text(sftp, f"/tmp/{name}", text)
print("up api", name, flush=True)
put_text(sftp, "/tmp/remote_vip_live.sh", REMOTE_SH)
put_text(sftp, "/tmp/patch_main_live_ops.py", PATCH_MAIN)
put_text(sftp, "/tmp/patch_vip_proxy_inject.py", PATCH_PROXY)
put_text(sftp, "/tmp/patch_admin_nginx_include.py", PATCH_ADMIN_INCLUDE)
put_text(sftp, "/tmp/patch_admin_api_8010.py", PATCH_ADMIN_API_8010)
put_text(sftp, "/tmp/vip-live-api.conf", VIP_LIVE_API_CONF)
put_text(sftp, "/tmp/admin-live-sse.conf", ADMIN_LIVE_SSE_CONF)
sftp.close()
remote(c, "bash /tmp/remote_vip_live.sh", timeout=240)
finally:
c.close()
print("OK deploy_vip_live_129", flush=True)
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,166 @@
# -*- coding: utf-8 -*-
"""Point admin.hackrobot.cn /api → nomadvip :4007 (/api/ops). Keep /api/admin/live → :8010."""
from __future__ import annotations
import sys
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True)
REMOTE = r"""#!/bin/bash
set -euo pipefail
echo '=== local ops on 4007 ==='
curl -sS -o /tmp/ops4007.json -w 'ops4007:%{http_code}\n' --max-time 8 \
-H 'Content-Type: application/json' \
-d '{"username":"hackrobot","password":"Xiao4669805@"}' \
http://127.0.0.1:4007/api/ops/login || true
head -c 220 /tmp/ops4007.json; echo
CONF=/www/server/panel/vhost/nginx/admin.hackrobot.cn.conf
sudo cp -a "$CONF" "/tmp/admin.conf.before-4007-$(date -u +%Y%m%dT%H%M%SZ)"
sudo python3 - <<'PY'
from pathlib import Path
p = Path("/www/server/panel/vhost/nginx/admin.hackrobot.cn.conf")
raw = p.read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n")
t = raw.decode("utf-8")
# Ensure extension include for live SSE (8010) remains before catch-all /api/
inc = "include /www/server/panel/vhost/nginx/extension/admin.hackrobot.cn/*.conf;"
if inc not in t:
# insert before location ^~ /api/
needle = " location ^~ /api/ {"
if needle not in t:
raise SystemExit("no /api/ location")
t = t.replace(
needle,
" # Live ops SSE (8010) — more specific than /api/\n " + inc + "\n\n" + needle,
1,
)
print("inserted extension include")
# Force catch-all /api/ → VIP Next 4007 (hosts /api/ops for VIP 运营台)
import re
pat = re.compile(
r"(location \^~ /api/ \{.*?proxy_pass http://127\.0\.0\.1:)(\d+)(;)",
re.S,
)
m = pat.search(t)
if not m:
raise SystemExit("cannot find /api/ proxy_pass")
old_port = m.group(2)
t = pat.sub(r"\g<1>4007\g<3>", t, count=1)
# Host header for Next should be localhost-ish as before
t = t.replace(
"proxy_set_header Host $host;\n proxy_set_header Authorization $http_authorization;",
"proxy_set_header Host 127.0.0.1;",
1,
)
# comment
t = t.replace("# Ops API -> nomadmini (8010)", "# Ops API -> VIP next (4007) /api/ops", 1)
t = t.replace("# Ops API -> VIP next (4007)", "# Ops API -> VIP next (4007) /api/ops", 1)
p.write_bytes(t.encode("utf-8"))
print(f"api proxy_pass {old_port} -> 4007")
PY
# live SSE conf must exist and stay on 8010
sudo mkdir -p /www/server/panel/vhost/nginx/extension/admin.hackrobot.cn
sudo tee /www/server/panel/vhost/nginx/extension/admin.hackrobot.cn/admin-live-sse.conf >/dev/null <<'NGX'
location ^~ /api/admin/live/ {
proxy_pass http://127.0.0.1:8010;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header Authorization $http_authorization;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Connection '';
proxy_buffering off;
proxy_cache off;
proxy_read_timeout 3600s;
chunked_transfer_encoding off;
}
NGX
sudo sed -i 's/\r$//' /www/server/panel/vhost/nginx/extension/admin.hackrobot.cn/admin-live-sse.conf
# SPA must be VIP ops (not wechat shell)
R=/www/wwwroot/admin.hackrobot.cn
if ! grep -q 'index-OYkETFeq.js\|/api/ops/' "$R"/assets/index-*.js 2>/dev/null; then
echo 'SPA not VIP ops — restoring from /tmp backup'
if [ -d /tmp/admin-restore-20261111T061920Z ]; then
sudo rsync -a --delete /tmp/admin-restore-20261111T061920Z/ "$R"/
elif [ -f /var/backups/nomadro-upgrade/20261111T060203Z/admin-hackrobot.tgz ]; then
sudo rm -rf /tmp/admin-vip-unpack && mkdir -p /tmp/admin-vip-unpack
sudo tar -xzf /var/backups/nomadro-upgrade/20261111T060203Z/admin-hackrobot.tgz -C /tmp/admin-vip-unpack
# tarball may be flat or nested
if [ -f /tmp/admin-vip-unpack/index.html ]; then
sudo rsync -a --delete /tmp/admin-vip-unpack/ "$R"/
else
INNER=$(find /tmp/admin-vip-unpack -name index.html | head -1 | xargs dirname)
sudo rsync -a --delete "$INNER"/ "$R"/
fi
else
echo 'WARN: no VIP SPA backup'
fi
fi
sudo nginx -t
sudo nginx -s reload
sleep 1
echo '=== smoke ==='
curl -sk -o /tmp/ops_pub.json -w 'ops_login:%{http_code}\n' --max-time 12 \
-H 'Content-Type: application/json' \
-d '{"username":"hackrobot","password":"Xiao4669805@"}' \
https://admin.hackrobot.cn/api/ops/login
head -c 220 /tmp/ops_pub.json; echo
curl -sk -o /dev/null -w 'admin:%{http_code}\n' --max-time 12 https://admin.hackrobot.cn/
curl -sk -o /dev/null -w 'vip:%{http_code}\n' --max-time 12 https://vip.hackrobot.cn/
# confirm no wechat shell
JS=$(ls "$R"/assets/index-*.js | head -1)
echo "JS=$JS"
python3 - <<PY
from pathlib import Path
t=Path("$JS").read_text(encoding="utf-8", errors="replace")
print("api/ops", t.count("/api/ops"))
print("wechat", t.count("wechat"))
print("微信后台", t.count("微信后台"))
print("vip.hackrobot", t.count("vip.hackrobot"))
PY
grep -n 'proxy_pass' /www/server/panel/vhost/nginx/admin.hackrobot.cn.conf | head -10
echo DONE
"""
def main() -> int:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
"129.204.21.129",
22,
"ubuntu",
"Xiao4669805",
timeout=40,
allow_agent=False,
look_for_keys=False,
)
try:
sftp = c.open_sftp()
with sftp.file("/tmp/fix_admin_hk_api_to_vip4007.sh", "wb") as f:
f.write(REMOTE.replace("\r\n", "\n").encode("utf-8"))
sftp.close()
_, o, e = c.exec_command("bash /tmp/fix_admin_hk_api_to_vip4007.sh", timeout=90)
print(o.read().decode("utf-8", "replace"), flush=True)
err = e.read().decode("utf-8", "replace")
if err.strip():
print(err[-2000:], file=sys.stderr, flush=True)
return o.channel.recv_exit_status()
finally:
c.close()
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,157 @@
# -*- coding: utf-8 -*-
"""Wire LIVE online/broadcast into VIP ops SPA on admin.hackrobot.cn.
- Accept VIP ops HMAC token on /api/admin/live/*
- Sync VIP_OPS_SECRET into nomadmini .env
- Inject admin-live.js dock into VIP 运营台
"""
from __future__ import annotations
import sys
from pathlib import Path
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True)
ROOT = Path(__file__).resolve().parents[1]
LIVE_OPS = ROOT / "apps" / "api" / "services" / "ebook_svc" / "routers" / "live_ops.py"
ADMIN_LIVE_JS = ROOT / "apps" / "admin" / "deploy" / "_vip_live_assets" / "admin-live.js"
HOST, USER, PASSWORD = "129.204.21.129", "ubuntu", "Xiao4669805"
REMOTE_SH = r'''#!/bin/bash
set -euo pipefail
APP=/opt/nomadmini/backend/app
ENVF=/opt/nomadmini/backend/.env
echo '=== sync VIP_OPS_SECRET ==='
SECRET=$(sudo python3 - <<'PY'
from pathlib import Path
p=Path('/www/wwwroot/nomadvip/.env.local')
for line in p.read_text(encoding='utf-8').splitlines():
if line.startswith('VIP_OPS_SECRET='):
print(line.split('=',1)[1].strip().strip('"').strip("'"))
break
PY
)
if [ -z "$SECRET" ]; then echo 'missing VIP_OPS_SECRET'; exit 1; fi
printf '%s' "$SECRET" | sudo tee /tmp/vip_ops_secret.txt >/dev/null
sudo python3 - <<'PY'
from pathlib import Path
secret = Path('/tmp/vip_ops_secret.txt').read_text(encoding='utf-8').strip()
p = Path('/opt/nomadmini/backend/.env')
t = p.read_text(encoding='utf-8')
lines = [ln for ln in t.splitlines() if not ln.startswith('VIP_OPS_SECRET=')]
lines.append(f'VIP_OPS_SECRET={secret}')
p.write_text('\n'.join(lines) + '\n', encoding='utf-8')
print('VIP_OPS_SECRET synced len', len(secret))
PY
sudo rm -f /tmp/vip_ops_secret.txt
echo '=== install live_ops ==='
sudo cp /tmp/live_ops.py "$APP/routers/live_ops.py"
sudo chown ubuntu:ubuntu "$APP/routers/live_ops.py"
echo '=== install admin-live.js ==='
R=/www/wwwroot/admin.hackrobot.cn
sudo cp /tmp/admin-live.js "$R/admin-live.js"
sudo chmod 644 "$R/admin-live.js"
sudo python3 - <<'PY'
from pathlib import Path
p=Path('/www/wwwroot/admin.hackrobot.cn/index.html')
t=p.read_text(encoding='utf-8')
needle='admin-live.js'
if needle in t:
print('index already has admin-live.js')
else:
if '</body>' not in t:
raise SystemExit('no </body>')
t=t.replace('</body>', '<script src="/admin-live.js" defer></script></body>', 1)
p.write_text(t, encoding='utf-8')
print('injected admin-live.js')
print(p.read_text(encoding='utf-8')[-400:])
PY
echo '=== restart api ==='
sudo systemctl restart nomadmini-api
sleep 3
systemctl is-active nomadmini-api
echo '=== smoke ops token online/broadcast ==='
TOK=$(curl -sk -X POST https://admin.hackrobot.cn/api/ops/login \
-H 'content-type: application/json' \
-d '{"username":"hackrobot","password":"Xiao4669805@"}' \
| python3 -c 'import sys,json;print(json.load(sys.stdin)["token"])')
echo "tok_len=${#TOK}"
curl -sk -o /tmp/online.json -w 'online:%{http_code}\n' \
-H "Authorization: Bearer $TOK" \
https://admin.hackrobot.cn/api/admin/live/online
head -c 600 /tmp/online.json; echo
curl -sk -o /tmp/presence.json -w 'presence:%{http_code}\n' -X POST \
https://vip.hackrobot.cn/api/vip/live/presence \
-H 'content-type: application/json' \
-d '{"visitorId":"wire_smoke","nick":"wire","email":"wire@test.local","page":"/","role":"guest"}'
head -c 200 /tmp/presence.json; echo
curl -sk -o /tmp/online2.json -w 'online2:%{http_code}\n' \
-H "Authorization: Bearer $TOK" \
https://admin.hackrobot.cn/api/admin/live/online
python3 - <<'PY'
import json
from pathlib import Path
d=json.loads(Path('/tmp/online2.json').read_text(encoding='utf-8'))
web=d.get('webOnline') or []
print('webOnline', len(web), [x.get('nick') or x.get('id') for x in web[:5]])
PY
curl -sk -o /tmp/bc.json -w 'broadcast:%{http_code}\n' -X POST \
-H "Authorization: Bearer $TOK" \
-H 'content-type: application/json' \
-d '{"title":"运营台联通测试","body":"实时通知已接通","cta":"知道了","href":"https://vip.hackrobot.cn/","tone":"amber","ttlSec":30}' \
https://admin.hackrobot.cn/api/admin/live/broadcast
head -c 400 /tmp/bc.json; echo
curl -sk -o /dev/null -w 'admin-live.js:%{http_code}\n' https://admin.hackrobot.cn/admin-live.js
curl -sk https://admin.hackrobot.cn/ | tr '\n' ' ' | grep -o 'admin-live.js' | head -1 || echo 'WARN: html missing admin-live.js'
echo DONE
'''
def main() -> int:
if not LIVE_OPS.is_file() or not ADMIN_LIVE_JS.is_file():
print("missing source files")
return 1
text = LIVE_OPS.read_text(encoding="utf-8").replace("ebook_svc.", "app.")
if "ebook_svc." in text:
print("rewrite failed")
return 1
if "require_admin_or_ops" not in text:
print("dual auth missing")
return 1
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, 22, USER, PASSWORD, timeout=40, allow_agent=False, look_for_keys=False)
try:
sftp = c.open_sftp()
with sftp.file("/tmp/live_ops.py", "wb") as f:
f.write(text.encode("utf-8"))
with sftp.file("/tmp/admin-live.js", "wb") as f:
f.write(ADMIN_LIVE_JS.read_bytes())
with sftp.file("/tmp/wire_vip_ops_live_129.sh", "wb") as f:
f.write(REMOTE_SH.replace("\r\n", "\n").encode("utf-8"))
sftp.close()
_, o, e = c.exec_command("bash /tmp/wire_vip_ops_live_129.sh", timeout=120)
print(o.read().decode("utf-8", "replace"), flush=True)
err = e.read().decode("utf-8", "replace")
if err.strip():
print(err[-2000:], file=sys.stderr, flush=True)
return o.channel.recv_exit_status()
finally:
c.close()
if __name__ == "__main__":
raise SystemExit(main())