Files
katelyatv/patches/fix_userlist_usernames.py
jinghui 7dc23a29ed v-fixed44: 修复管理页用户配置 React #31(用户对象当用户名写入列表) + 全新用户管理面板
根因: getAllUsers() 返回 User 对象数组,config.ts 当作用户名字符串使用,
导致 Users[].username 变成对象,管理页渲染对象触发 Minified React error #31。
- 修编译产物 chunks/{3498,8583}.js 与源码 src/lib/config.ts(两处)
- 清理 Redis admin:config 嵌套脏数据 41 -> 23 条
- 新增原生 JS 用户管理面板 public-live/user-admin.js(列表/添加/改密/设为管理/封禁/删除)
- middleware 放行 /user-admin.js; layout 注入面板加载器
- 新增幂等补丁脚本 patches/fix_userlist_usernames.py
- 镜像 katelyatv:fixed44
2026-11-06 22:53:53 +08:00

170 lines
6.7 KiB
Python

#!/usr/bin/env python3
"""
修复「管理页 → 用户配置」React #31 崩溃 + 新增独立用户管理面板。
根因:redis.db.ts 的 getAllUsers() 返回 User 对象数组,而 config.ts 把它当用户名
字符串使用,导致 Users[].username 被写成 {username, role, created_at} 对象,
管理页把该对象当文本渲染 → Minified React error #31。
本脚本对**运行中的容器**做幂等修补(重建镜像/重新 docker run 后需再跑一次):
1. /app/.next/server/chunks/{3498,8583}.js —— getAllUsers 结果取用户名字符串
2. /app/.next/server/src/middleware.js —— 放行 /user-admin.js
3. layout chunk —— 在 /admin 注入 /user-admin.js 加载器
4. /app/public/user-admin.js —— 全新用户管理面板(原生 JS)
5. Redis admin:config 的 Users 去嵌套 / 去重(先备份)
用法: python3 patches/fix_userlist_usernames.py [--repair-data]
"""
import json
import os
import shutil
import subprocess
import sys
import time
CT = os.environ.get("KAT_CONTAINER", "katelyatv")
REDIS = os.environ.get("KAT_REDIS", "katelyatv-redis")
BASE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
LAYOUT = "layout-7c2e94ab10d85f36.js"
LOADER_TAG = "USER-MGMT-LOADER-V1"
def sh(cmd, **kw):
return subprocess.run(cmd, shell=isinstance(cmd, str), check=False,
capture_output=True, text=True, **kw)
def node(script):
r = sh(["docker", "exec", "-u", "0", CT, "node", "-e", script])
print(r.stdout.strip() or r.stderr.strip())
return r.returncode == 0
def patch_server_chunks():
script = r'''
const fs=require('fs');
const files=['3498','8583'].map(n=>'/app/.next/server/chunks/'+n+'.js');
const from='userNames=await storage.getAllUsers()}';
const to='userNames=(await storage.getAllUsers()).map(e=>typeof e=="string"?e:(e&&typeof e.username=="string"?e.username:"")).filter(Boolean)}';
let touched=0;
for(const f of files){
if(!fs.existsSync(f)){console.log('skip missing',f);continue}
let s=fs.readFileSync(f,'utf8');
if(s.includes('typeof e=="string"?e:')){console.log('already patched',f);continue}
const c=s.split(from).length-1;
if(!c){console.log('ANCHOR MISS',f);continue}
fs.writeFileSync(f,s.split(from).join(to)); touched+=c;
console.log('patched',f,'x'+c);
}
console.log('total',touched);
'''
return node(script)
def patch_middleware():
script = r'''
const fs=require('fs');const p='/app/.next/server/src/middleware.js';
if(!fs.existsSync(p)){console.log('no middleware.js');process.exit(0)}
let s=fs.readFileSync(p,'utf8');
if(s.includes('"/user-admin.js"')){console.log('already allowlisted');process.exit(0)}
if(!s.includes('"/hls.min.js",')){console.log('ANCHOR MISS middleware');process.exit(0)}
s=s.replace('"/hls.min.js",','"/hls.min.js","/user-admin.js",');
fs.writeFileSync(p,s);console.log('middleware allowlisted');
'''
return node(script)
def patch_layout():
script = r'''
const fs=require('fs');const p='/app/.next/static/chunks/app/%(layout)s';
if(!fs.existsSync(p)){console.log('no layout chunk');process.exit(0)}
let s=fs.readFileSync(p,'utf8');
if(s.includes('%(tag)s')){console.log('loader already present');process.exit(0)}
s += '\n/*%(tag)s*/(function(){function go(){try{if(location.pathname!=="/admin")return;'
+ 'if(document.getElementById("kat-um"))return;var s=document.createElement("script");s.id="kat-um";'
+ 's.src="/user-admin.js?v=3";s.async=true;document.head.appendChild(s);}catch(e){}}'
+ 'go();setInterval(go,1500);})();\n';
fs.writeFileSync(p,s);console.log('loader injected');
''' % {"layout": LAYOUT, "tag": LOADER_TAG}
ok = node(script)
sh(["docker", "exec", "-u", "0", CT, "sh", "-c",
"chown 1001:1001 /app/.next/static/chunks/app/%s; chmod 644 /app/.next/static/chunks/app/%s" % (LAYOUT, LAYOUT)])
return ok
def copy_panel():
src = os.path.join(BASE, "public-live", "user-admin.js")
if not os.path.exists(src):
print("missing", src)
return False
r = sh(["docker", "cp", src, "%s:/app/public/user-admin.js" % CT])
if r.returncode != 0:
print(r.stderr)
return False
sh(["docker", "exec", "-u", "0", CT, "sh", "-c",
"chown 1001:1001 /app/public/user-admin.js; chmod 644 /app/public/user-admin.js"])
print("panel copied")
return True
def repair_data():
out = os.path.join("/vol1/1000/HD1/APP/hermes/cache/scratch/kat",
"cfg_before_repair_%d.json" % int(time.time()))
with open(out, "wb") as fh:
r = subprocess.run(["docker", "exec", REDIS, "redis-cli", "--raw", "GET", "admin:config"],
capture_output=True)
fh.write(r.stdout)
cfg = json.loads(r.stdout.decode("utf-8"))
users = cfg["UserConfig"]["Users"]
rank = {"user": 0, "admin": 1, "owner": 2}
out_users, order, flattened = {}, [], 0
for e in users:
if not isinstance(e, dict):
continue
uname, role = e.get("username"), e.get("role") or "user"
created, banned, d = e.get("created_at") or "", bool(e.get("banned")), 0
while isinstance(uname, dict) and d < 10:
flattened += 1
role = uname.get("role") or role
created = uname.get("created_at") or created
banned = banned or bool(uname.get("banned"))
uname, d = uname.get("username"), d + 1
if not isinstance(uname, str) or not uname.strip():
continue
uname = uname.strip()
role = role if role in rank else "user"
rec = out_users.get(uname)
if rec is None:
rec = {"username": uname, "role": role}
if created:
rec["created_at"] = created
if banned:
rec["banned"] = True
out_users[uname] = rec
order.append(uname)
else:
if rank[role] > rank.get(rec["role"], 0):
rec["role"] = role
if created and not rec.get("created_at"):
rec["created_at"] = created
if banned:
rec["banned"] = True
cfg["UserConfig"]["Users"] = [out_users[u] for u in order]
payload = json.dumps(cfg, ensure_ascii=False).encode("utf-8")
r2 = subprocess.run(["docker", "exec", "-i", REDIS, "redis-cli", "-x", "SET", "admin:config"],
input=payload, capture_output=True)
print("data repair: %d -> %d users (flattened %d), backup %s, redis: %s"
% (len(users), len(order), flattened, out, r2.stdout.decode().strip()))
if __name__ == "__main__":
patch_server_chunks()
patch_middleware()
patch_layout()
copy_panel()
if "--repair-data" in sys.argv:
repair_data()
print("restarting app…")
sh(["docker", "restart", CT])
print("done")