#!/usr/bin/env python3 """Continue dy.nomadro.live ops harden: env/oauth/NAT, token probe, firewall persist, start assigned Nekos.""" from __future__ import annotations import json import sys import time import paramiko sys.stdout.reconfigure(encoding="utf-8", errors="replace") HOST = "108.174.50.68" PASS = "Xiao4669805" PUBLIC = "https://dy.nomadro.live" REDIRECT = f"{PUBLIC}/api/shorts/oauth/callback" NAT = "108.174.50.68" def ssh(): c = paramiko.SSHClient() c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) c.connect( HOST, 22, "root", PASS, timeout=45, allow_agent=False, look_for_keys=False, banner_timeout=120, ) return c def run(c, cmd, t=300): print(f"\n===== {cmd[:120].replace(chr(10), ' ')} =====", flush=True) _i, o, e = c.exec_command(cmd, timeout=t) out = (o.read() + e.read()).decode("utf-8", "replace") code = o.channel.recv_exit_status() print(out[-16000:] if len(out) > 16000 else out, flush=True) return code, out c = ssh() # 1) Align public URL / redirect / NAT in env + settings code, _ = run( c, rf""" set -euo pipefail python3 - <<'PY' from pathlib import Path p = Path('/etc/douyinweb.env') text = p.read_text(encoding='utf-8') if p.exists() else '' kv = {{}} lines = [] for ln in text.splitlines(): if '=' in ln and not ln.strip().startswith('#'): k,v = ln.split('=',1) kv[k.strip()] = v lines.append(ln) want = {{ 'DY_PUBLIC_BASE_URL': '{PUBLIC}', 'PUBLIC_BASE': '{PUBLIC}', 'DY_SITE_URL': '{PUBLIC}', 'DY_NEKO_NAT1TO1': '{NAT}', 'DY_NEKO_VPS_NAT1TO1': '{NAT}', }} changed = False for k,v in want.items(): if kv.get(k) != v: kv[k] = v changed = True print('set', k, v) else: print('ok', k, v) # rewrite file preserving unknown keys order roughly out_lines = [] seen = set() for ln in lines: if '=' in ln and not ln.strip().startswith('#'): k = ln.split('=',1)[0].strip() if k in want: out_lines.append(f'{{k}}={{want[k]}}') seen.add(k) continue out_lines.append(ln) for k,v in want.items(): if k not in seen: out_lines.append(f'{{k}}={{v}}') changed = True if changed: p.write_text('\\n'.join(out_lines) + '\\n', encoding='utf-8') print('env_updated') else: print('env_unchanged') PY cd /opt/douyinWEB/backend set -a; source /etc/douyinweb.env; set +a ./.venv/bin/python - <<'PY' import json from app import db from app import config sm = db.get_settings_map() upd = {{}} redir = '{REDIRECT}' pub = '{PUBLIC}' if str(sm.get('shorts_oauth_redirect_uri') or '').strip() != redir: upd['shorts_oauth_redirect_uri'] = redir # rewrite profiles redirect if present profiles = sm.get('shorts_oauth_profiles') if isinstance(profiles, str): try: profiles = json.loads(profiles) except Exception: profiles = None if isinstance(profiles, list): changed = False for p in profiles: if isinstance(p, dict) and str(p.get('redirect_uri') or '').strip() not in ('', redir): p['redirect_uri'] = redir changed = True elif isinstance(p, dict) and not str(p.get('redirect_uri') or '').strip(): p['redirect_uri'] = redir changed = True if changed or (isinstance(profiles, list) and profiles): # always normalize stored profiles redirect for p in profiles: if isinstance(p, dict): p['redirect_uri'] = redir upd['shorts_oauth_profiles'] = profiles if upd: db.update_settings_map(upd) print('settings_upd', list(upd.keys())) else: print('settings_ok') print('cfg_public', getattr(config.settings, 'public_base_url', None) or getattr(config.settings, 'public_base', None)) print('cfg_nat', getattr(config.settings, 'neko_nat1to1', None)) print('redir', db.get_settings_map().get('shorts_oauth_redirect_uri')) profiles = db.get_settings_map().get('shorts_oauth_profiles') if isinstance(profiles, list): for p in profiles: cid = str(p.get('client_id') or '')[:28] print('profile', p.get('name') or p.get('id'), cid+'…', 'redir', p.get('redirect_uri')) PY """, ) # 2) Persist firewall + check RAM before starting Nekos code2, out2 = run( c, r""" set -euo pipefail # ensure rules iptables -C INPUT -p udp --dport 52000:52499 -j ACCEPT 2>/dev/null || iptables -I INPUT -p udp --dport 52000:52499 -j ACCEPT iptables -C INPUT -p tcp --dport 52000:52499 -j ACCEPT 2>/dev/null || iptables -I INPUT -p tcp --dport 52000:52499 -j ACCEPT iptables -C INPUT -p udp --dport 52300:52320 -j ACCEPT 2>/dev/null || iptables -I INPUT -p udp --dport 52300:52320 -j ACCEPT if command -v netfilter-persistent >/dev/null 2>&1; then netfilter-persistent save || true echo saved_netfilter elif command -v iptables-save >/dev/null 2>&1; then mkdir -p /etc/iptables iptables-save > /etc/iptables/rules.v4 echo saved_iptables_rules else echo no_persist_tool fi if command -v ufw >/dev/null 2>&1 && ufw status 2>/dev/null | grep -qi active; then ufw allow 52000:52499/udp || true ufw allow 52000:52499/tcp || true ufw allow 52300:52320/udp || true fi echo '--- mem ---' free -h | head -3 echo '--- units ---' systemctl is-active douyinweb-api douyinweb-web douyinweb-pb douyinweb-s3 || true """, ) # 3) Probe OAuth refresh tokens (shorts + assign via youtube client) code3, _ = run( c, r""" set -euo pipefail cd /opt/douyinWEB/backend set -a; source /etc/douyinweb.env; set +a ./.venv/bin/python - <<'PY' import json, time from app import db from app import yt_assign_db from app import yt_long_db try: from app.youtube_client import refresh_access_token, get_channel_oauth_status except Exception: refresh_access_token = None get_channel_oauth_status = None # discover helpers import inspect from app import youtube_client as yc funcs = [n for n in dir(yc) if 'refresh' in n.lower() or 'oauth' in n.lower() or 'credential' in n.lower()] print('yc_funcs', funcs[:40]) def try_refresh(label, client_id, client_secret, refresh_token): cid = (client_id or '').strip() sec = (client_secret or '').strip() rt = (refresh_token or '').strip() if not rt: return {'label': label, 'ok': False, 'err': 'no_rt'} # common patterns in this codebase for name in ('refresh_access_token', 'exchange_refresh_token', 'fetch_access_token', 'token_from_refresh'): fn = getattr(yc, name, None) if callable(fn): try: out = fn(cid, sec, rt) if len(inspect.signature(fn).parameters) >= 3 else fn(rt) if isinstance(out, dict): ok = bool(out.get('access_token') or out.get('ok') or out.get('token')) return {'label': label, 'ok': ok, 'via': name, 'err': (out.get('error') or out.get('err') or '')[:120]} return {'label': label, 'ok': True, 'via': name} except Exception as e: return {'label': label, 'ok': False, 'via': name, 'err': str(e)[:160]} # raw http import urllib.request, urllib.parse data = urllib.parse.urlencode({ 'client_id': cid, 'client_secret': sec, 'refresh_token': rt, 'grant_type': 'refresh_token', }).encode() req = urllib.request.Request('https://oauth2.googleapis.com/token', data=data, method='POST') try: with urllib.request.urlopen(req, timeout=25) as r: body = json.loads(r.read().decode()) return {'label': label, 'ok': bool(body.get('access_token')), 'via': 'http', 'exp': body.get('expires_in')} except Exception as e: err = str(e) try: import urllib.error if isinstance(e, urllib.error.HTTPError): err = e.read().decode('utf-8','replace')[:200] except Exception: pass return {'label': label, 'ok': False, 'via': 'http', 'err': err[:200]} results = [] for ch in db.list_shorts_channels() or []: results.append(try_refresh( f"shorts:{ch.get('name')}", ch.get('client_id'), ch.get('client_secret'), ch.get('refresh_token'), )) for ch in (yt_long_db.list_channels() if hasattr(yt_long_db,'list_channels') else []) or []: results.append(try_refresh( f"long:{ch.get('name')}", ch.get('client_id'), ch.get('client_secret'), ch.get('refresh_token'), )) # assign groups often store oauth on linked shorts / own fields groups = yt_assign_db.list_groups(include_urls=False) or [] for g in groups: rt = g.get('refresh_token') or '' if not rt: continue results.append(try_refresh( f"assign:{g.get('name')}", g.get('client_id'), g.get('client_secret'), rt, )) ok_n = sum(1 for r in results if r.get('ok')) bad = [r for r in results if not r.get('ok')] print('oauth_probe_total', len(results), 'ok', ok_n, 'bad', len(bad)) for r in results: print(json.dumps(r, ensure_ascii=False)) # unique neko slots from assign slots = sorted({int(g.get('neko_instance_id') or 0) for g in groups if int(g.get('neko_instance_id') or 0) > 0}) print('assign_neko_slots', slots) PY """, t=240, ) # 4) Restart API if env changed, ensure capacity, start assigned neko slots (mem permitting) code4, _ = run( c, r""" set -euo pipefail # reload env into API systemctl daemon-reload systemctl restart douyinweb-api sleep 4 systemctl is-active douyinweb-api cd /opt/douyinWEB/backend set -a; source /etc/douyinweb.env; set +a export DY_NEKO_NAT1TO1=108.174.50.68 ./.venv/bin/python - <<'PY' import json from app import youtube_neko as yn from app import yt_assign_db groups = yt_assign_db.list_groups(include_urls=False) or [] slots = sorted({int(g.get('neko_instance_id') or 0) for g in groups if 1 <= int(g.get('neko_instance_id') or 0) <= 8}) print('slots', slots) # mem gate: need ~1.2G free per extra container roughly import subprocess mem = subprocess.check_output("free -b | awk '/Mem:/{print $7}'", shell=True).decode().strip() avail = int(mem or 0) print('mem_available_b', avail) # always ensure compose/capacity for 8, but start only slots if mem ok yn.ensure_capacity(8, start_instances=set(), reconcile_running=False) # start assigned + keep 1 if already up; max concurrent starts based on avail # keep 2GB headroom budget = max(0, avail - 2_000_000_000) max_start = max(1, min(len(slots) or 1, budget // 1_400_000_000)) print('max_start', max_start) to_start = set(slots[:max_start] if slots else [1]) # if 1 running already include it status = yn.status_snapshot() if hasattr(yn, 'status_snapshot') else None print('to_start', sorted(to_start)) # use docker start for reliability import subprocess as sp for i in sorted(to_start): name = f'douyinweb-neko-{i}' sp.run(['docker', 'start', name], check=False) print('started_cmds_done') PY sleep 8 docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' curl -s http://127.0.0.1:8014/api/health | head -c 300; echo curl -sk https://dy.nomadro.live/api/health | head -c 300; echo curl -sk -o /dev/null -w 'neko1:%{http_code}\n' https://dy.nomadro.live/neko/1/ """, t=300, ) c.close() print("\nALL_DONE", flush=True)