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

212 lines
6.2 KiB
Python

#!/usr/bin/env python3
"""Fix admin login + seed OAuth B + prepare Neko on dy.nomadro.live."""
from __future__ import annotations
import json
import sys
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
HOST = "108.174.50.68"
PASS = "Xiao4669805"
ADMIN_USER = "hackrobot"
ADMIN_PASS = "Xiao4669805@"
REDIRECT = "https://dy.nomadro.live/api/shorts/oauth/callback"
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=180):
print(f"\n$ {cmd[:200]}", flush=True)
_i, o, e = c.exec_command(cmd, timeout=t)
out = (o.read() + e.read()).decode("utf-8", "replace")
print(out[-12000:] if len(out) > 12000 else out, flush=True)
return o.channel.recv_exit_status(), out
c = ssh()
# 1) Force-reset admin to known password (env may not have matched hashed DB)
code, _ = run(
c,
r"""
set -euo pipefail
cd /opt/douyinWEB/backend
# Match API process secrets
set -a
# shellcheck disable=SC1091
source /etc/douyinweb.env
set +a
export DY_SESSION_SECRET="${SESSION_SECRET:-${DY_SESSION_SECRET:-}}"
export DY_ADMIN_USERNAME=hackrobot
export DY_ADMIN_PASSWORD='Xiao4669805@'
export DY_AUTH_ENABLED=true
./.venv/bin/python - <<'PY'
from app.session_auth import (
ensure_default_admin_credentials,
verify_admin,
get_admin_credentials,
hash_password,
_secret,
)
from app import db, config
want_user = "hackrobot"
want_pass = "Xiao4669805@"
print("secret_len", len(_secret()))
print("cfg_admin", config.settings.admin_username, "pass_len", len(str(config.settings.admin_password or "")))
db.update_settings_map({
"admin_username": want_user,
"admin_password_hash": hash_password(want_pass),
})
ensure_default_admin_credentials()
# ensure_default may overwrite with settings.admin_password — force again after aligning env
db.update_settings_map({
"admin_username": want_user,
"admin_password_hash": hash_password(want_pass),
})
u, _h = get_admin_credentials()
print("admin_user", u)
print("verify", verify_admin(want_user, want_pass))
PY
# Also align systemd unit admin/session with known password
grep -q '^DY_ADMIN_PASSWORD=' /etc/douyinweb.env || true
# Ensure env file has DY_* aliases API/config expects
python3 - <<'PY'
from pathlib import Path
p = Path('/etc/douyinweb.env')
text = p.read_text(encoding='utf-8')
lines = text.splitlines()
kv = {}
for ln in lines:
if '=' in ln and not ln.strip().startswith('#'):
k,v = ln.split('=',1)
kv[k.strip()] = v
# keep SESSION_SECRET; expose DY_ aliases
sess = kv.get('DY_SESSION_SECRET') or kv.get('SESSION_SECRET') or ''
kv['SESSION_SECRET'] = sess
kv['DY_SESSION_SECRET'] = sess
kv['DY_ADMIN_USERNAME'] = 'hackrobot'
kv['DY_ADMIN_PASSWORD'] = 'Xiao4669805@'
kv['ADMIN_USER'] = 'hackrobot'
kv['DY_PUBLIC_BASE_URL'] = kv.get('DY_PUBLIC_BASE_URL') or kv.get('PUBLIC_BASE') or 'https://dy.nomadro.live'
out = []
for k,v in kv.items():
out.append(f'{k}={v}')
p.write_text('\n'.join(out)+'\n', encoding='utf-8')
print('env_updated', 'session_len', len(sess))
PY
systemctl daemon-reload
systemctl restart douyinweb-api
sleep 3
curl -sS -o /tmp/login.json -w 'http:%{http_code}\n' -X POST http://127.0.0.1:8014/api/auth/login \
-H 'Content-Type: application/json' \
-d '{"username":"hackrobot","password":"Xiao4669805@"}'
cat /tmp/login.json; echo
""",
)
assert code == 0
# 2) Seed OAuth profile B from leftover client_secret JSON + redirect URI
code, _ = run(
c,
rf"""
set -euo pipefail
cd /opt/douyinWEB/backend
./.venv/bin/python - <<'PY'
import json, glob
from pathlib import Path
from app import db
from app import shorts_oauth
files = list(Path('/opt/douyinWEB').glob('client_secret_*.json'))
print('secret_files', [str(p.name) for p in files])
assert files, 'missing client_secret json'
raw = json.loads(files[0].read_text(encoding='utf-8'))
web = raw.get('web') or raw.get('installed') or raw
cid = str(web.get('client_id') or '').strip()
sec = str(web.get('client_secret') or '').strip()
print('client_id', cid[:40]+'...')
assert cid and sec
redirect = "{REDIRECT}"
profiles = shorts_oauth.normalize_oauth_profiles(db.get_settings_map().get('shorts_oauth_profiles'))
# merge B
out = []
for p in profiles:
row = dict(p)
if row.get('id') == 'B':
row['client_id'] = cid
row['client_secret'] = sec
row['label'] = row.get('label') or '谷歌账号 B'
out.append(row)
db.update_settings_map({{
'shorts_oauth_profiles': out,
'shorts_oauth_redirect_uri': redirect,
'shorts_oauth_client_id': cid, # legacy fallback
'shorts_oauth_client_secret': sec,
}})
sm = db.get_settings_map()
print('redirect', sm.get('shorts_oauth_redirect_uri'))
for p in shorts_oauth.normalize_oauth_profiles(sm.get('shorts_oauth_profiles')):
print(p['id'], 'cid', (p.get('client_id') or '')[:28], 'sec', bool(p.get('client_secret')))
PY
""",
)
assert code == 0
# 3) Ensure Neko compose capacity (create containers, do not start all)
code, _ = run(
c,
r"""
set -euo pipefail
cd /opt/douyinWEB/backend
./.venv/bin/python - <<'PY'
from app import youtube_neko as yn
# create fleet definitions (no mass start) — capacity for assign later
print('docker', yn._docker_available())
out = yn.ensure_capacity(4, start_instances=set(), reconcile_running=False)
print(out)
# list
for i in yn.list_instances(4, check_http=False):
print('neko', i.get('id'), i.get('status'), i.get('exists'), i.get('running'))
PY
docker ps -a --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | head
""",
t=300,
)
# 4) Public login page + API via domain
code, _ = run(
c,
r"""
set +e
curl -sS -o /dev/null -w 'pub_login:%{http_code}\n' --max-time 20 https://dy.nomadro.live/login
curl -sS -c /tmp/dyj -b /tmp/dyj -o /tmp/login2.json -w 'pub_api_login:%{http_code}\n' -X POST https://dy.nomadro.live/api/auth/login \
-H 'Content-Type: application/json' \
-d '{"username":"hackrobot","password":"Xiao4669805@"}'
cat /tmp/login2.json; echo
curl -sS -b /tmp/dyj -o /dev/null -w 'me:%{http_code}\n' https://dy.nomadro.live/api/auth/me
""",
)
c.close()
print("DONE")