diff --git a/.cursor/rules/admin-hosts-never-confuse.mdc b/.cursor/rules/admin-hosts-never-confuse.mdc new file mode 100644 index 0000000..7d572ee --- /dev/null +++ b/.cursor/rules/admin-hosts-never-confuse.mdc @@ -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` diff --git a/AGENTS.md b/AGENTS.md index 9aa276a..013a617 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 / 小程序包。 diff --git a/README.md b/README.md index 2aff495..6138b98 100644 --- a/README.md +++ b/README.md @@ -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` | diff --git a/apps/admin/deploy/_vip_live_assets/admin-leads-online.js b/apps/admin/deploy/_vip_live_assets/admin-leads-online.js new file mode 100644 index 0000000..0a9b8d5 --- /dev/null +++ b/apps/admin/deploy/_vip_live_assets/admin-leads-online.js @@ -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 ? "在线" : "离线"; + } + 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 ? "在线" : "离线"; + 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(); + } +})(); diff --git a/apps/admin/deploy/_vip_live_assets/admin-live.js b/apps/admin/deploy/_vip_live_assets/admin-live.js new file mode 100644 index 0000000..62b0bd7 --- /dev/null +++ b/apps/admin/deploy/_vip_live_assets/admin-live.js @@ -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(); + } +})(); diff --git a/apps/admin/deploy/_vip_live_assets/admin-user-tags.js b/apps/admin/deploy/_vip_live_assets/admin-user-tags.js new file mode 100644 index 0000000..ec256c7 --- /dev/null +++ b/apps/admin/deploy/_vip_live_assets/admin-user-tags.js @@ -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(); + } +})(); diff --git a/apps/admin/deploy/_vip_live_assets/vip-live.js b/apps/admin/deploy/_vip_live_assets/vip-live.js new file mode 100644 index 0000000..405f9be --- /dev/null +++ b/apps/admin/deploy/_vip_live_assets/vip-live.js @@ -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 = + '
运营通知
' + + "" + + '' + + ''; + 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(); + } +})(); diff --git a/apps/admin/src/pages/VipUsers.tsx b/apps/admin/src/pages/VipUsers.tsx index c25154c..b0d8984 100644 --- a/apps/admin/src/pages/VipUsers.tsx +++ b/apps/admin/src/pages/VipUsers.tsx @@ -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
+ 向正在浏览 vip.hackrobot.cn 的访客实时弹窗(SSE)。标题必填。
+