douyinWEB/scripts/_align_assign_neko_tm_both.py
2026-09-13 22:10:49 -05:00

172 lines
7.1 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Align assign-neko TM on PHYSICAL + VPS: offline load-extension, never touch Secure Preferences."""
import sys
from pathlib import Path
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
ROOT = Path(__file__).resolve().parents[1]
FILES = {
"browser-launch.sh": ROOT / "backend/neko/browser-launch.sh",
"policies.json": ROOT / "backend/neko/policies/policies.json",
"Preferences": ROOT / "backend/neko/tampermonkey-seed/Default/Preferences",
"manifest.json": ROOT
/ "backend/neko/tampermonkey-seed/Default/Extensions/dhdgffkkebhmkfjojejmpbldmpobfkfo/5.5.0_0/manifest.json",
}
# Seed TM into profile only (Preferences + Extensions). NEVER Secure Preferences / Cookies.
SEED_PROFILE = r'''
import json, shutil
from pathlib import Path
EXT="dhdgffkkebhmkfjojejmpbldmpobfkfo"
BASE=Path("/home/neko/.config/google-chrome/Default")
SEED=Path("/etc/neko/tampermonkey-seed/Default")
SEED_EXT=SEED/"Extensions"/EXT
SEED_PREF=SEED/"Preferences"
def load(p):
try: return json.loads(p.read_text(encoding="utf-8"))
except Exception: return {}
if not SEED_EXT.exists():
raise SystemExit("NO_SEED_EXT")
# copy extension files if missing or empty
dst=BASE/"Extensions"/EXT
if dst.exists():
shutil.rmtree(dst, ignore_errors=True)
(BASE/"Extensions").mkdir(parents=True, exist_ok=True)
shutil.copytree(SEED_EXT, dst)
# strip update_url
mf=dst/"5.5.0_0"/"manifest.json"
if mf.exists():
md=load(mf); md.pop("update_url", None)
mf.write_text(json.dumps(md, ensure_ascii=False, indent=3)+"\n", encoding="utf-8")
# Preferences only — NEVER Secure Preferences
seed_entry=((load(SEED_PREF).get("extensions") or {}).get("settings") or {}).get(EXT) or {}
entry=dict(seed_entry) if isinstance(seed_entry, dict) else {}
entry.update({"state":1,"path":f"{EXT}/5.5.0_0","location":4,"from_webstore":False})
entry.pop("disable_reasons", None)
mf2=entry.get("manifest")
if isinstance(mf2, dict):
mf2=dict(mf2); mf2.pop("update_url", None); entry["manifest"]=mf2
pref=BASE/"Preferences"
d=load(pref) if pref.exists() else {}
d.setdefault("extensions",{}).setdefault("settings",{})[EXT]=dict(entry)
d.setdefault("extensions",{}).setdefault("ui",{})["developer_mode"]=True
pref.write_text(json.dumps(d, separators=(",",":")), encoding="utf-8")
print("seeded_tm_ok")
'''
REMOTE_SH = r'''
set -e
ROOT=/opt/douyinWEB/backend/neko
# in-place overwrite (preserve bind-mount inodes)
cat /tmp/browser-launch.sh.tmfix > "$ROOT/browser-launch.sh"
chmod 755 "$ROOT/browser-launch.sh"
cat /tmp/policies.json.tmfix > "$ROOT/policies/policies.json"
chmod 644 "$ROOT/policies/policies.json"
cat /tmp/Preferences.tmfix > "$ROOT/tampermonkey-seed/Default/Preferences"
chmod 644 "$ROOT/tampermonkey-seed/Default/Preferences"
MF="$ROOT/tampermonkey-seed/Default/Extensions/dhdgffkkebhmkfjojejmpbldmpobfkfo/5.5.0_0/manifest.json"
if [ -f "$MF" ]; then cat /tmp/manifest.json.tmfix > "$MF"; chmod 644 "$MF"; fi
# ensure chromium policy dirs also get same file if separate mounts exist on host
for d in /etc/opt/chrome/policies/managed /etc/chromium/policies/managed /etc/chromium-browser/policies/managed; do
if [ -d "$d" ] || [ -L "$d" ]; then
mkdir -p "$d" 2>/dev/null || true
fi
done
echo "=== remount check browser-launch ==="
# force container remount of host files by stop/start running assign nekos
NAMES=$(docker ps --format '{{.Names}}' | grep -E '^douyinweb-neko-[0-9]+$' | sort || true)
echo "running: $NAMES"
for name in $NAMES; do
echo "===== SEED $name ====="
docker exec -i "$name" tee /tmp/_seed_tm.py < /tmp/_seed_tm_profile.py >/dev/null
docker exec "$name" python3 /tmp/_seed_tm.py || echo SEED_FAIL
# verify policy mount
docker exec "$name" bash -lc 'ls -la /etc/opt/chrome/policies/managed/policies.json 2>/dev/null || echo NO_POLICY_MOUNT; grep -n Offline /etc/neko/browser-launch.sh | head -3 || echo NO_OFFLINE_IN_LAUNCH'
docker exec "$name" supervisorctl restart google-chrome || docker exec "$name" supervisorctl start google-chrome || true
done
# if none running, still update host assets; operator starts manually
sleep 12
for name in $NAMES; do
echo "===== VERIFY $name ====="
docker exec -i "$name" python3 - <<'PY'
import json, os, re, urllib.request
from pathlib import Path
ext="dhdgffkkebhmkfjojejmpbldmpobfkfo"
e=((json.loads(Path("/home/neko/.config/google-chrome/Default/Preferences").read_text()).get("extensions") or {}).get("settings") or {}).get(ext) or {}
print("tm", e.get("state"), e.get("location"), e.get("from_webstore"), "path", e.get("path"))
print("ext", Path(f"/home/neko/.config/google-chrome/Default/Extensions/{ext}/5.5.0_0/manifest.json").exists())
found=False
for pid in os.listdir("/proc"):
if not pid.isdigit(): continue
try: cmd=open(f"/proc/{pid}/cmdline","rb").read().replace(b"\x00",b" ").decode()
except Exception: continue
if "google-chrome" in cmd and "--type=" not in cmd and "load-extension" in cmd:
m=re.search(r"--load-extension=([^ ]+)", cmd)
print("load_ext", m.group(1) if m else None); found=True; break
if not found: print("load_ext NONE")
try:
tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=4).read())
except Exception as ex:
print("cdp", ex); tabs=[]
print("tm_sw", sum(1 for t in tabs if t.get("type")=="service_worker" and "dhdgff" in (t.get("url") or "")))
PY
done
'''
def do_host(label: str, host: str, port: int, user: str, pw: str, use_sudo: bool) -> None:
print(f"\n########## {label} ##########", flush=True)
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(host, port, user, pw, timeout=45, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
for name, path in FILES.items():
with sftp.file(f"/tmp/{name}.tmfix", "wb") as f:
f.write(path.read_bytes())
print("up", name, flush=True)
with sftp.file("/tmp/_seed_tm_profile.py", "wb") as f:
f.write(SEED_PROFILE.encode())
with sftp.file("/tmp/_align_tm_remote.sh", "wb") as f:
f.write(REMOTE_SH.encode())
sftp.close()
if use_sudo:
cmd = f"echo {pw} | sudo -S -p '' bash /tmp/_align_tm_remote.sh"
else:
cmd = "bash /tmp/_align_tm_remote.sh"
_i, o, e = c.exec_command(cmd, timeout=420)
print((o.read() + e.read()).decode("utf-8", "replace"), flush=True)
c.close()
def main() -> None:
# Ensure local seed prefs/manifest are offline
pref = FILES["Preferences"]
import json
d = json.loads(pref.read_text(encoding="utf-8"))
e = d["extensions"]["settings"]["dhdgffkkebhmkfjojejmpbldmpobfkfo"]
e["location"] = 4
e["from_webstore"] = False
if isinstance(e.get("manifest"), dict):
e["manifest"].pop("update_url", None)
pref.write_text(json.dumps(d, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
mf = FILES["manifest.json"]
md = json.loads(mf.read_text(encoding="utf-8"))
md.pop("update_url", None)
mf.write_text(json.dumps(md, ensure_ascii=False, indent=3) + "\n", encoding="utf-8")
do_host("PHYSICAL", "107.173.30.245", 4014, "eric", "4669805", True)
do_host("VPS", "107.173.30.245", 22, "root", "Xiao4669805", False)
if __name__ == "__main__":
main()