Compare commits

..
Author SHA1 Message Date
3970260761 b48a526935 feat: 记录用户最后登录时间 + 面板时间列兼容毫秒时间戳
- patches/last-login.js: 最小 Redis RESP 客户端(touch/readMany)
- patches/inject_last_login.py: 注入 login 路由两条成功分支写 u:<user>:last_login,
  admin/users 回填 last_login_at / created_at(含 est 标记),可重复执行
- patches/apply.sh: 新增 4h 步骤,重建 .next 后自动恢复
- public-live/user-admin.js: toDate 兼容毫秒时间戳与 ISO
- patches/backfill_user_times.py: 默认演练(IDLETIME 在 Redis 重载后同值,会造假数据)
2026-11-07 01:26:12 +08:00
3970260761 f9b248fd07 v-fixed44-hub-r2: 公告弹窗可按ID屏蔽/本地覆盖(announcement.json), 下线旧公告; 仅is_popup=1才弹 2026-11-07 00:52:08 +08:00
8 changed files with 461 additions and 10 deletions

No files matched your search

+26
View File
@@ -2,6 +2,32 @@
格式参考本机发版惯例:按日期分条,`🐛修复` / `✨新功能`。
## v-fixed44-hub-r3 (2026-11-07)
### ✨ 新功能
- 👤 **记录用户最后登录时间**:登录成功即写入 Redis `u:<用户名>:last_login`(毫秒时间戳),管理面板用户列表「最后登录」列直接显示;从未登录过的显示「从未登录」。
此前一直不记录——源码 `src/lib/redis.db.ts` 有 `touchLogin()`,但线上 `.next` 是旧编译产物,这段逻辑没被编译进去。
实现:`patches/last-login.js`(不依赖 node_modules 的最小 Redis RESP 客户端)+ `patches/inject_last_login.py`,注入 login 路由的**两条**成功分支(环境变量 owner 分支、用户库分支)与 `admin/users` 返回。写入失败静默,绝不影响登录。
已并入 `patches/apply.sh`(步骤 4h),`npm run build` 覆盖 `.next` 后重跑即可恢复。
### 🐛 修复
- 🕒 管理面板的时间列对毫秒时间戳会显示成裸数字(`1793985861570`)→ 前端 `toDate/fmtDate/fmtDateTime` 同时兼容毫秒时间戳与 ISO 字符串。
- ⚠️ `backfill_user_times.py` 改为**默认演练,不写入**:Redis 重启/RDB 重载后所有键的 IDLETIME 从加载时刻统一起算,用它估算"最后登录"会把全部账号写成同一时间(实测 18 个账号全部 00:24,已清理)。需要实跑加 `--force`。
## v-fixed44-hub-r2 (2026-11-07)
### ✨ 新功能
- 📢 公告弹窗可按 ID 屏蔽 / 本地覆盖:`public-live/announcement.json`
```json
{ "block_ids": [13], "override": { "enabled": true, "title": "标题", "content": "正文", "is_popup": 1 } }
```
`block_ids` 里的公告不再显示;`override` 填了就用它当弹窗内容;文件热改即生效(无需重启容器)。
默认写入 `block_ids: [13]`,即下线旧的「所有资源免费观看,请勿信片中的广告!」公告弹窗。
### 🐛 修复
- 🔔 只有 `is_popup=1` 的公告才弹窗;此前会把列表里第一条普通公告也当作弹窗弹出。
- 🔁 授权中心返回空公告时正确清空弹窗(不再残留上一次结果)。
## v-fixed44 (2026-11-06)
### ✨ 新功能
+21 -2
View File
@@ -119,6 +119,16 @@ async function heartbeat() {
} catch (e) { state.hub_ok = false; console.log("[LICENSE] heartbeat err " + String(e && e.message || e)); }
}
// 本地公告控制:/app/announcement.json(可热改,无需重启)
// { "block_ids": [13], "override": { "enabled": true, "title": "...", "content": "...", "is_popup": 1 } }
function loadLocalAnnouncement() {
try {
const p = process.env.LOCAL_ANNOUNCEMENT_FILE || "/app/public/announcement.json";
if (!FS.existsSync(p)) return null;
return JSON.parse(FS.readFileSync(p, "utf8")) || null;
} catch (e) { return null; }
}
async function fetchAnnouncements() {
const ctl = new AbortController();
const tm = setTimeout(() => ctl.abort(), TIMEOUT);
@@ -128,8 +138,17 @@ async function fetchAnnouncements() {
const j = await r.json();
if (j && j.code === 200 && j.data) {
const ok = (arr) => (Array.isArray(arr) ? arr.filter(x => x && (x.project_id == null || String(x.project_id) === PROJECT_ID)) : []);
state.announcements = ok(j.data.list);
state.popup = ok(j.data.popup)[0] || state.announcements[0] || null; // 授权中心返回空列表即覆盖为空
const local = loadLocalAnnouncement() || {};
const blockIds = Array.isArray(local.block_ids) ? local.block_ids.map(String) : [];
const keep = (arr) => ok(arr).filter(x => !blockIds.includes(String(x.id)));
state.announcements = keep(j.data.list);
const ov = local.override;
if (ov && ov.enabled !== false && (ov.title || ov.content)) {
state.popup = { id: "local", title: ov.title || "", content: ov.content || "", is_popup: ov.is_popup == null ? 1 : ov.is_popup, project_id: PROJECT_ID, local: true };
} else {
const wantPopup = (x) => Number(x.is_popup) === 1;
state.popup = keep(j.data.popup).filter(wantPopup)[0] || state.announcements.filter(wantPopup)[0] || null;
}
state.hub_ok = true;
console.log("[LICENSE] announcements n=" + state.announcements.length + " popup=" + (state.popup ? String(state.popup.title || "").slice(0, 30) : "-"));
}
+3
View File
@@ -53,6 +53,9 @@ echo "[4f/5] 注入 /ipv6 线路选择页 + 首页 IPV4/IPV6 切换按钮..."
python3 "$DIR/inject_ipv6.py" || echo "ipv6 inject failed (non-fatal)"
python3 "$DIR/patch_middleware_whitelist.py" || echo "middleware whitelist failed (non-fatal)"
echo "[4h/5] 用户最后登录/注册时间记录..."
python3 "$DIR/inject_last_login.py" || echo "last_login inject failed (non-fatal)"
echo "[4g/5] 前端资源防陈旧缓存(chunk按内容改名)..."
docker cp "$DIR/patch_cachebust.js" "$C:/tmp/patch_cachebust.js"
docker exec "$C" node /tmp/patch_cachebust.js || true
+82
View File
@@ -0,0 +1,82 @@
#!/usr/bin/env python3
"""回填用户时间字段(默认演练,不写入):
⚠️ 教训:Redis 重启/RDB 重载后所有键的 IDLETIME 会从加载时刻统一起算,
此时「用空闲时长估算上次登录」会把所有账号写成同一个时间(假数据)。
实测本机就是这种情况,因此不推荐实跑;last_login 由 inject_last_login.py 从此刻起真实记录。
- 缺失 created_at 的老账号:写入首次记录时间并标记 created_at_est=1(面板显示「约」)
- 缺失 last_login 的账号:用 u:<name>:pwd 的空闲时长估算,标记 last_login_est=1
用法:python3 backfill_user_times.py [--dry|--force] (默认 --dry)
环境变量:KAT_REDIS(默认 katelyatv-redis)
"""
import json
import os
import subprocess
import sys
import time
REDIS = os.environ.get("KAT_REDIS", "katelyatv-redis")
DRY = "--force" not in sys.argv
def rc(*args):
r = subprocess.run(
["docker", "exec", REDIS, "redis-cli", "--raw", *args],
capture_output=True, text=True,
)
return r.stdout.strip()
def main():
cfg_raw = rc("GET", "admin:config")
users = set()
try:
cfg = json.loads(cfg_raw)
for u in (cfg.get("UserConfig") or {}).get("Users") or []:
n = u.get("username")
if isinstance(n, dict):
n = n.get("username")
if n:
users.add(str(n))
except Exception as e:
print("读取 admin:config 失败,仅按 pwd 键回填:", e)
pwd_keys = [k for k in rc("KEYS", "u:*:pwd").splitlines() if k.strip()]
pwd_users = {}
for k in pwd_keys:
parts = k.split(":")
if len(parts) == 3:
pwd_users[parts[1]] = k
users |= set(pwd_users.keys())
now_ms = int(time.time() * 1000)
created = last = 0
for name in sorted(users):
# created_at
if not rc("GET", f"u:{name}:created_at"):
if not DRY:
rc("SET", f"u:{name}:created_at", str(now_ms))
rc("SET", f"u:{name}:created_at_est", "1")
created += 1
# last_login
if not rc("GET", f"u:{name}:last_login"):
key = pwd_users.get(name)
if key:
idle = rc("OBJECT", "IDLETIME", key)
try:
idle_s = int(idle)
except ValueError:
idle_s = None
if idle_s is not None and idle_s >= 0:
ts = now_ms - idle_s * 1000
if not DRY:
rc("SET", f"u:{name}:last_login", str(ts))
rc("SET", f"u:{name}:last_login_est", "1")
last += 1
print(f"users={len(users)} created_filled={created} last_login_filled={last} dry={DRY}")
if __name__ == "__main__":
main()
+139
View File
@@ -0,0 +1,139 @@
#!/usr/bin/env python3
"""LASTLOGIN-V1 —— 让线上编译产物记录「最后登录时间」
问题:源码 src/lib/redis.db.ts 已实现 touchLogin(),但运行中的 .next 是旧版编译产物,
login 路由里没有这段逻辑 → Redis 中不存在 u:<user>:last_login,管理端最后登录时间恒为空。
做法(不改 .next 结构,不重建镜像):
1. 安装最小 Redis 客户端到 /app/last-login.js(源文件 patches/last-login.js)
2. login/route.js:登录校验通过后写入 u:<user>:last_login = 当前毫秒时间戳(失败静默,不影响登录)
3. admin/users/route.js:返回用户列表时回填 last_login_at 字段
幂等:以 /*LASTLOGIN-V1*/ 标记判定,已注入则只刷新 /app/last-login.js。
用法:python3 patches/inject_last_login.py
"""
import os
import subprocess
import sys
import tempfile
MARK = "/*LASTLOGIN-V1*/"
CONTAINER = os.environ.get("KAT_CONTAINER", "katelyatv")
HERE = os.path.dirname(os.path.abspath(__file__))
HELPER = os.path.join(HERE, "last-login.js")
HELPER_DEST = "/app/last-login.js"
LOGIN = "/app/.next/server/app/api/login/route.js"
ADMINS = "/app/.next/server/app/api/admin/users/route.js"
LOGIN_ANCHOR = 'let e=i.NextResponse.json({ok:!0}),n=await g(t,r,s?.role||"user",!1),a=new Date;'
# 环境变量 owner 分支(.env 里的 USERNAME 登录走这里)
LOGIN_OWNER_ANCHOR = 'let e=i.NextResponse.json({ok:!0}),s=await g(t,r,"owner",!1),n=new Date;'
LOGIN_INJECT = (
MARK
+ 'try{require("/app/last-login.js").touch(t)}catch(_e){}'
)
ADMIN_ANCHOR = "return i.NextResponse.json({users:n,total:n.length})"
ADMIN_INJECT = (
MARK
+ 'try{const __kaM=await require("/app/last-login.js").readMany('
"n.map(function(x){return x.username}));"
"n.forEach(function(x){const v=__kaM[x.username]||{};"
"if(v.last_login){x.last_login_at=Number(v.last_login);"
"if(v.last_login_est)x.last_login_estimated=true}"
"if(!x.created_at&&v.created_at){x.created_at=Number(v.created_at);"
"if(v.created_at_est)x.created_at_estimated=true}});}catch(_e){}"
)
def strip_old(src):
"""移除本补丁早先注入的片段,保证可重复执行不叠加。"""
while MARK in src:
i = src.index(MARK)
j = src.find("catch(_e){}", i)
if j < 0:
break
src = src[:i] + src[j + len("catch(_e){}"):]
return src
def sh(cmd):
return subprocess.run(cmd, shell=True, capture_output=True, text=True)
def install_helper():
if not os.path.exists(HELPER):
print(" ✗ 缺少 %s" % HELPER)
return False
r = sh("docker cp %s %s:%s" % (HELPER, CONTAINER, HELPER_DEST))
if r.returncode:
print(" ✗ 复制 helper 失败: %s" % r.stderr.strip())
return False
fix_perm(HELPER_DEST)
print(" ✓ 已安装 %s" % HELPER_DEST)
return True
def fix_perm(path):
sh("docker exec -u root %s sh -c 'chown 1001:1001 %s 2>/dev/null; chmod 644 %s'" % (CONTAINER, path, path))
def read_container(path):
tmp = tempfile.mktemp(suffix=".js")
r = sh("docker cp %s:%s %s" % (CONTAINER, path, tmp))
if r.returncode:
print(" ✗ 读取 %s 失败: %s" % (path, r.stderr.strip()))
return None, tmp
with open(tmp, encoding="utf-8") as f:
return f.read(), tmp
def write_container(src, path):
r = sh("docker cp %s %s:%s" % (src, CONTAINER, path))
if r.returncode:
print(" ✗ 写回 %s 失败: %s" % (path, r.stderr.strip()))
return False
fix_perm(path)
return True
def patch_file(path, pairs, label):
"""pairs: [(anchor, inject), ...] —— 一次读取、一次写回,避免多锚点互相覆盖。"""
src, tmp = read_container(path)
if src is None:
return False
src = strip_old(src)
for anchor, inject in pairs:
if anchor not in src:
print(" ✗ %s 锚点未找到: %s" % (label, anchor[:60]))
return False
src = src.replace(anchor, inject + anchor, 1)
tmp_js = tmp + ".patched.js"
with open(tmp_js, "w", encoding="utf-8") as f:
f.write(src)
chk = sh("node --check %s" % tmp_js)
if chk.returncode:
print(" ✗ %s 语法检查失败: %s" % (label, chk.stderr.strip()[:300]))
return False
if not write_container(tmp_js, path):
return False
print(" ✓ %s 已注入" % label)
return True
def main():
print("== LASTLOGIN-V1 ==")
ok = install_helper()
ok = patch_file(LOGIN, [(LOGIN_ANCHOR, LOGIN_INJECT), (LOGIN_OWNER_ANCHOR, LOGIN_INJECT)],
"login/route.js(普通用户 + owner 两条登录分支)") and ok
ok = patch_file(ADMINS, [(ADMIN_ANCHOR, ADMIN_INJECT)], "admin/users/route.js(回填最后登录/注册时间)") and ok
if not ok:
print("!! 有步骤失败")
return 1
print("完成,重启容器后生效:docker restart %s" % CONTAINER)
return 0
if __name__ == "__main__":
sys.exit(main())
+141
View File
@@ -0,0 +1,141 @@
/* LASTLOGIN-V1 —— 记录/读取用户最后登录时间(Redis: u:<username>:last_login,毫秒时间戳)
*
* 背景:源码 src/lib/redis.db.ts 已有 touchLogin,但线上 .next 是旧版编译产物,没有这段逻辑。
* 本文件是补丁用的最小 Redis(RESP) 客户端,不依赖 node_modules,供 patches/inject_last_login.py
* 注入到 /app/.next/server/app/api/login/route.js 与 .../admin/users/route.js 使用。
*/
"use strict";
const net = require("net");
function target() {
const raw = process.env.REDIS_URL || "redis://katelyatv-redis:6379";
const u = new URL(raw);
return {
host: u.hostname || "katelyatv-redis",
port: Number(u.port || 6379),
pass: process.env.REDIS_PASSWORD || (u.password ? decodeURIComponent(u.password) : ""),
db: String(process.env.REDIS_DATABASE || (u.pathname || "/0").replace(/^\//, "") || "0"),
};
}
function enc(v) {
v = String(v);
return "$" + Buffer.byteLength(v) + "\r\n" + v + "\r\n";
}
function build(cmd) {
return "*" + cmd.length + "\r\n" + cmd.map(enc).join("");
}
function parse(s, i) {
if (i >= s.length) return null;
const t = s[i];
const nl = s.indexOf("\r\n", i);
if (nl < 0) return null;
const head = s.slice(i + 1, nl);
if (t === "+" || t === "-") return [head, nl + 2];
if (t === ":") return [Number(head), nl + 2];
if (t === "$") {
const n = Number(head);
if (n < 0) return [null, nl + 2];
const end = nl + 2 + n;
if (s.length < end + 2) return null;
return [s.slice(nl + 2, end), end + 2];
}
if (t === "*") {
const n = Number(head);
if (n < 0) return [null, nl + 2];
let p = nl + 2;
const arr = [];
for (let k = 0; k < n; k++) {
const r = parse(s, p);
if (!r) return null;
arr.push(r[0]);
p = r[1];
}
return [arr, p];
}
return null;
}
function run(commands, timeout) {
return new Promise((resolve, reject) => {
let cfg;
try {
cfg = target();
} catch (e) {
reject(e);
return;
}
const pre = [];
if (cfg.pass) pre.push(["AUTH", cfg.pass]);
pre.push(["SELECT", cfg.db]);
let payload = "";
for (const c of pre) payload += build(c);
for (const c of commands) payload += build(c);
const want = pre.length + commands.length;
const sock = net.createConnection({ host: cfg.host, port: cfg.port });
let buf = "";
let settled = false;
const done = (err, val) => {
if (settled) return;
settled = true;
try {
sock.destroy();
} catch (e) {
/* ignore */
}
if (err) reject(err);
else resolve(val);
};
sock.setTimeout(timeout || 2000, () => done(new Error("redis timeout")));
sock.on("error", (e) => done(e));
sock.on("data", (d) => {
buf += d.toString("utf8");
const out = [];
let p = 0;
for (let k = 0; k < want; k++) {
const r = parse(buf, p);
if (!r) return;
out.push(r[0]);
p = r[1];
}
done(null, out.slice(pre.length));
});
sock.write(payload);
});
}
// 登录成功后调用,失败静默(绝不影响登录)
function touch(username) {
if (!username) return Promise.resolve(false);
return run([["SET", "u:" + username + ":last_login", String(Date.now())]])
.then(() => true)
.catch(() => false);
}
// 批量读取,返回 { username: { last_login, created_at, last_login_est, created_at_est } }
function readMany(usernames) {
const list = (usernames || []).filter(Boolean);
if (!list.length) return Promise.resolve({});
const fields = ["last_login", "created_at", "last_login_est", "created_at_est"];
const cmds = [];
for (const u of list) for (const f of fields) cmds.push(["GET", "u:" + u + ":" + f]);
return run(cmds)
.then((vals) => {
const m = {};
list.forEach((u, i) => {
const o = {};
fields.forEach((f, j) => {
const v = vals[i * fields.length + j];
if (v) o[f] = v;
});
m[u] = o;
});
return m;
})
.catch(() => ({}));
}
module.exports = { touch, readMany, _run: run };
+5
View File
@@ -0,0 +1,5 @@
{
"_说明": "站点公告控制:block_ids 里的公告ID不再显示;override 填写后会替换授权中心公告作为弹窗内容(enabled=false 可停用)",
"block_ids": [13],
"override": null
}
+44 -8
View File
@@ -5,6 +5,7 @@
var API_CFG = '/api/admin/config';
var API_USER = '/api/admin/user';
var API_USERS = '/api/admin/users';
var state = { users: [], allowRegister: false, loading: false, open: false };
function el(tag, attrs, kids) {
@@ -44,18 +45,37 @@
function load() {
state.loading = true; render();
return fetch(API_CFG, { headers: { 'Cache-Control': 'no-cache' } })
var times = {};
// 时间信息(注册/最后登录)来自 /api/admin/users
var pTimes = fetch(API_USERS, { headers: { 'Cache-Control': 'no-cache' } })
.then(function (r) { return r.json(); })
.then(function (j) {
var arr = (j && Array.isArray(j.users)) ? j.users : [];
arr.forEach(function (x) {
if (x && x.username) times[String(x.username)] = x;
});
})
.catch(function () { });
return pTimes
.then(function () {
return fetch(API_CFG, { headers: { 'Cache-Control': 'no-cache' } });
})
.then(function (r) { return r.json(); })
.then(function (cfg) {
var root = (cfg && cfg.Config) ? cfg.Config : (cfg || {});
var uc = root.UserConfig || {};
var list = Array.isArray(uc.Users) ? uc.Users : [];
state.users = list.filter(function (u) { return u && typeof u === 'object'; }).map(function (u) {
var name = String(typeof u.username === 'object' && u.username ? (u.username.username || '') : (u.username || ''));
var t = times[name] || {};
return {
username: String(typeof u.username === 'object' && u.username ? (u.username.username || '') : (u.username || '')),
role: String(u.role || 'user'),
username: name,
role: String(u.role || t.role || 'user'),
banned: !!u.banned,
created_at: u.created_at ? String(u.created_at) : ''
created_at: t.created_at ? String(t.created_at) : (u.created_at ? String(u.created_at) : ''),
created_at_estimated: !!(t.created_at_estimated || u.created_at_estimated),
last_login_at: t.last_login_at ? String(t.last_login_at) : '',
last_login_estimated: !!(t.last_login_estimated || u.last_login_estimated)
};
});
state.allowRegister = !!uc.AllowRegister;
@@ -66,10 +86,25 @@
function roleLabel(r) { return r === 'owner' ? '站长' : r === 'admin' ? '管理员' : '普通用户'; }
function toDate(v) {
if (!v) return null;
var s = String(v);
var d = /^\d+$/.test(s) ? new Date(Number(s)) : new Date(v);
return isNaN(d.getTime()) ? null : d;
}
function fmtDateTime(v) {
if (!v) return '从未登录';
var d = toDate(v);
if (!d) return String(v).slice(0, 16).replace('T', ' ');
var p = function (n) { return (n < 10 ? '0' : '') + n; };
return d.getFullYear() + '-' + p(d.getMonth() + 1) + '-' + p(d.getDate()) + ' ' + p(d.getHours()) + ':' + p(d.getMinutes());
}
function fmtDate(v) {
if (!v) return '-';
var d = new Date(v);
if (isNaN(d.getTime())) return String(v).slice(0, 10);
var d = toDate(v);
if (!d) return String(v).slice(0, 10);
var p = function (n) { return (n < 10 ? '0' : '') + n; };
return d.getFullYear() + '-' + p(d.getMonth() + 1) + '-' + p(d.getDate());
}
@@ -135,7 +170,7 @@
}));
var table = el('table', { style: 'width:100%;border-collapse:collapse;font-size:13px' });
var thead = el('thead', {}, [el('tr', {}, ['用户名', '角色', '状态', '注册时间', '操作'].map(function (h) {
var thead = el('thead', {}, [el('tr', {}, ['用户名', '角色', '状态', '注册时间', '最后登录', '操作'].map(function (h) {
return el('th', { text: h, style: 'text-align:left;padding:8px 6px;color:#6b7280;font-weight:600;border-bottom:1px solid #e5e7eb;white-space:nowrap' });
}))]);
table.appendChild(thead);
@@ -185,7 +220,8 @@
el('td', { text: u.username, style: 'padding:8px 6px;border-bottom:1px solid #f3f4f6;font-weight:500;color:#111827;white-space:nowrap' }),
el('td', { text: roleLabel(u.role), style: 'padding:8px 6px;border-bottom:1px solid #f3f4f6;color:#374151;white-space:nowrap' }),
el('td', { text: u.banned ? '已封禁' : '正常', style: 'padding:8px 6px;border-bottom:1px solid #f3f4f6;color:' + (u.banned ? '#dc2626' : '#059669') + ';white-space:nowrap' }),
el('td', { text: fmtDate(u.created_at), style: 'padding:8px 6px;border-bottom:1px solid #f3f4f6;color:#6b7280;white-space:nowrap' }),
el('td', { text: (u.created_at ? (u.created_at_estimated ? '约 ' : '') + fmtDate(u.created_at) : '未记录'), style: 'padding:8px 6px;border-bottom:1px solid #f3f4f6;color:#6b7280;white-space:nowrap', title: u.created_at_estimated ? '该账号早于时间记录功能上线,此处为首次记录时间' : '' }),
el('td', { text: (u.last_login_at && u.last_login_estimated ? '约 ' : '') + fmtDateTime(u.last_login_at), title: u.last_login_estimated ? '按账号活跃记录推算的近似时间' : '', style: 'padding:8px 6px;border-bottom:1px solid #f3f4f6;color:' + (u.last_login_at ? '#6b7280' : '#9ca3af') + ';white-space:nowrap' }),
el('td', { style: 'padding:8px 6px;border-bottom:1px solid #f3f4f6' }, [ops])
]);
tbody.appendChild(tr);