Files
LihonT/services/members/server.py
cheb0chik 86b014e15a LihonT 2 Serena beta 2 (hotfix)
Fixes the freezes while scrolling the feed and opening a profile: reading a user name made the mod ask TikTok which account is
signed in, which read the name again through the same hooks, thousands of levels deep, every few seconds. The time of the next
question is now set before it is asked, and a nested call only hands the name back. Adds a light timer of the places where TikTok
calls into the mod (lines "perf" in the diary), the avatar frame closed packs on the server (grants by account id), the
winter pack of frames, the mirror page generator and the beat video script.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-04 10:10:53 +03:00

423 lines
23 KiB
Python

"""Self-reported LihonT presence registry. Standard library only; bind to localhost.
This is a community marker, not proof of TikTok account ownership or official
verification. A modified client can claim another UID. No TikTok credentials
are accepted. Installation secrets permit withdrawing only that installation's
contribution. Public lookup responses expose only requested membership bits.
Avatar outlines are different: one is published for an account only after that
account's public bio held its code (the same proof as the niche badge), and the
installation that proved it keeps the right to change it.
"""
from __future__ import annotations
import argparse
import base64
import hmac
import secrets
import urllib.request
import hashlib
import json
import re
import sqlite3
import threading
import time
from collections import defaultdict, deque
from contextlib import contextmanager
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
UID = re.compile(r"[1-9][0-9]{4,24}\Z")
INSTALL = re.compile(r"[a-f0-9]{64}\Z")
LIFETIME = 30 * 86400
UNIQUE = re.compile(r"[A-Za-z0-9_.]{2,24}\Z")
# Avatar outlines a member can publish; the round one is TikTok's own and is never stored.
SHAPES = ("flower", "squircle", "hexagon", "heart", "triangle")
# Avatar frames: "pack.frame" ids of the catalog on the site (the catalog itself is not known here, only the shape of the id).
FRAME = re.compile(r"[a-z0-9][a-z0-9_-]{0,23}\.[a-z0-9][a-z0-9_-]{0,23}\Z")
# Packs whose frames only the accounts that were given them may use. A grant is one frame ("vip.creator") or a whole pack ("vip.*").
RESTRICTED_PACKS = ("vip",)
GRANT = re.compile(r"[a-z0-9][a-z0-9_-]{0,23}\.(\*|[a-z0-9][a-z0-9_-]{0,23})\Z")
# The niche-mod badge can be claimed until this moment (Moscow time).
CLAIM_DEADLINE = 1794735240 # 2026-11-15 12:34:00 +03:00
def fetch_profile(unique_id):
"""Public TikTok profile page of @unique_id as (account id, bio), or None. Anonymous GET only."""
request = urllib.request.Request(
"https://www.tiktok.com/@" + unique_id,
headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/124.0 Safari/537.36"})
with urllib.request.urlopen(request, timeout=20) as response:
page = response.read(3_000_000).decode("utf-8", "replace")
match = re.search(r'<script id="__UNIVERSAL_DATA_FOR_REHYDRATION__"[^>]*>(.*?)</script>', page, re.S)
if not match:
return None
user = (json.loads(match.group(1)).get("__DEFAULT_SCOPE__", {})
.get("webapp.user-detail", {}).get("userInfo", {}).get("user", {}))
if not user.get("id"):
return None
return str(user["id"]), str(user.get("signature") or "")
def frame_permitted(frame, grants):
"""True when the frame is open to everyone, or one of `grants` (frame ids and "pack.*") covers it."""
pack = frame.split(".", 1)[0]
return pack not in RESTRICTED_PACKS or frame in grants or pack + ".*" in grants
def valid_uid(value):
return isinstance(value, str) and UID.fullmatch(value) is not None
class Registry:
def __init__(self, path, clock=time.time, fetcher=fetch_profile):
self.path, self.clock, self.fetcher = str(path), clock, fetcher
with self.connect() as db:
db.execute("PRAGMA journal_mode=WAL")
db.execute("CREATE TABLE IF NOT EXISTS presence (installation TEXT NOT NULL, uid TEXT NOT NULL, last_seen INTEGER NOT NULL, frame_color TEXT NOT NULL DEFAULT 'green', PRIMARY KEY(installation, uid))")
columns = {row[1] for row in db.execute("PRAGMA table_info(presence)")}
if "frame_color" not in columns:
db.execute("ALTER TABLE presence ADD COLUMN frame_color TEXT NOT NULL DEFAULT 'green'")
db.execute("CREATE INDEX IF NOT EXISTS presence_uid ON presence(uid, last_seen)")
db.execute("CREATE TABLE IF NOT EXISTS blocked (uid TEXT PRIMARY KEY)")
db.execute("CREATE TABLE IF NOT EXISTS supporters (uid TEXT PRIMARY KEY, granted_at INTEGER NOT NULL)")
db.execute("CREATE TABLE IF NOT EXISTS niche (uid TEXT PRIMARY KEY, unique_id TEXT NOT NULL, granted_at INTEGER NOT NULL)")
db.execute("CREATE TABLE IF NOT EXISTS shapes (uid TEXT PRIMARY KEY, shape TEXT NOT NULL, updated_at INTEGER NOT NULL)")
db.execute("CREATE TABLE IF NOT EXISTS avatar_frames (uid TEXT PRIMARY KEY, frame TEXT NOT NULL, updated_at INTEGER NOT NULL)")
db.execute("CREATE TABLE IF NOT EXISTS frame_grants (uid TEXT NOT NULL, frame TEXT NOT NULL, granted_at INTEGER NOT NULL, PRIMARY KEY(uid, frame))")
db.execute("CREATE TABLE IF NOT EXISTS shape_owner (uid TEXT PRIMARY KEY, installation TEXT NOT NULL, unique_id TEXT NOT NULL, verified_at INTEGER NOT NULL)")
db.execute("CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)")
db.execute("INSERT OR IGNORE INTO meta(key,value) VALUES('code_secret',?)", (secrets.token_hex(32),))
@contextmanager
def connect(self):
db = sqlite3.connect(self.path, timeout=10)
try:
with db:
yield db
finally:
db.close()
def presence(self, uid, installation, withdraw=False, frame_color="green"):
if not valid_uid(uid) or not isinstance(installation, str) or not INSTALL.fullmatch(installation):
raise ValueError("Invalid account ID or installation code")
digest = hashlib.sha256(installation.encode("ascii")).hexdigest()
if frame_color not in ("none", "green", "red", "yellow"):
frame_color = "green"
now = int(self.clock())
with self.connect() as db:
db.execute("DELETE FROM presence WHERE last_seen < ?", (now - LIFETIME,))
if withdraw:
db.execute("DELETE FROM presence WHERE installation=? AND uid=?", (digest, uid))
else:
if db.execute("SELECT 1 FROM blocked WHERE uid=?", (uid,)).fetchone():
raise ValueError("Account excluded from the registry")
existing = db.execute("SELECT 1 FROM presence WHERE installation=? AND uid=?", (digest, uid)).fetchone()
if not existing and db.execute("SELECT COUNT(*) FROM presence WHERE installation=?", (digest,)).fetchone()[0] >= 20:
raise ValueError("Too many accounts for one installation")
db.execute("INSERT INTO presence(installation,uid,last_seen,frame_color) VALUES(?,?,?,?) ON CONFLICT(installation,uid) DO UPDATE SET last_seen=excluded.last_seen,frame_color=excluded.frame_color", (digest, uid, now, frame_color))
return {"ok": True}
def code(self, uid):
"""The proof string for an account: it only ever goes into that account's own bio."""
if not valid_uid(uid):
raise ValueError("Invalid account ID")
with self.connect() as db:
secret = db.execute("SELECT value FROM meta WHERE key='code_secret'").fetchone()[0]
digest = hmac.new(bytes.fromhex(secret), uid.encode("ascii"), "sha256").digest()
return "LT-" + base64.b32encode(digest)[:8].decode("ascii")
def claim(self, uid, unique_id):
"""Gives the niche-mod badge to `uid` when its public bio holds the account's code."""
if not valid_uid(uid) or not isinstance(unique_id, str) or not UNIQUE.fullmatch(unique_id):
raise ValueError("Invalid account")
with self.connect() as db:
if db.execute("SELECT 1 FROM niche WHERE uid=?", (uid,)).fetchone():
return {"ok": True, "granted": True}
if db.execute("SELECT 1 FROM blocked WHERE uid=?", (uid,)).fetchone():
raise ValueError("Account excluded")
if self.clock() > CLAIM_DEADLINE:
raise ValueError("The badge can no longer be claimed")
try:
profile = self.fetcher(unique_id)
except Exception:
raise ValueError("Could not read the TikTok profile, try again later")
if profile is None:
raise ValueError("Profile not found")
found_uid, bio = profile
if found_uid != uid:
raise ValueError("That profile belongs to another account")
if self.code(uid) not in bio:
return {"ok": True, "granted": False, "reason": "code_missing"}
with self.connect() as db:
db.execute("INSERT OR IGNORE INTO niche(uid,unique_id,granted_at) VALUES(?,?,?)",
(uid, unique_id, int(self.clock())))
return {"ok": True, "granted": True}
def shape(self, uid, installation, shape, unique_id=None):
"""Publishes (or, for "circle", withdraws) the avatar outline of `uid`.
The installation that proved the account stays bound to it, so that installation changes the outline
again without another proof. Any other installation has to prove the account first: its public bio
must hold the account's code, exactly as for the niche badge.
"""
if not valid_uid(uid) or not isinstance(installation, str) or not INSTALL.fullmatch(installation):
raise ValueError("Invalid account ID or installation code")
if shape != "circle" and shape not in SHAPES:
raise ValueError("Unknown shape")
digest = hashlib.sha256(installation.encode("ascii")).hexdigest()
with self.connect() as db:
if db.execute("SELECT 1 FROM blocked WHERE uid=?", (uid,)).fetchone():
raise ValueError("Account excluded")
owner = db.execute("SELECT installation FROM shape_owner WHERE uid=?", (uid,)).fetchone()
has_shape = db.execute("SELECT 1 FROM shapes WHERE uid=?", (uid,)).fetchone()
proven = owner is not None and hmac.compare_digest(owner[0], digest)
if not proven and shape == "circle" and not has_shape:
return {"ok": True, "published": True, "shape": "circle"} # nothing to withdraw
if not proven:
reply = self._prove(uid, digest, unique_id)
if reply is not None:
return reply
with self.connect() as db:
if shape == "circle":
db.execute("DELETE FROM shapes WHERE uid=?", (uid,))
else:
db.execute("INSERT INTO shapes(uid,shape,updated_at) VALUES(?,?,?) "
"ON CONFLICT(uid) DO UPDATE SET shape=excluded.shape,updated_at=excluded.updated_at",
(uid, shape, int(self.clock())))
return {"ok": True, "published": True, "shape": shape}
def _prove(self, uid, digest, unique_id):
"""The account proves itself with the code in its public bio; the installation is then bound to it.
Returns None once the installation is bound, else the reply that tells the client what is missing."""
if not isinstance(unique_id, str) or not UNIQUE.fullmatch(unique_id):
return {"ok": True, "published": False, "reason": "proof_needed", "code": self.code(uid)}
try:
profile = self.fetcher(unique_id)
except Exception:
raise ValueError("Could not read the TikTok profile, try again later")
if profile is None:
raise ValueError("Profile not found")
found_uid, bio = profile
if found_uid != uid:
raise ValueError("That profile belongs to another account")
if self.code(uid) not in bio:
return {"ok": True, "published": False, "reason": "code_missing", "code": self.code(uid)}
with self.connect() as db:
db.execute("INSERT INTO shape_owner(uid,installation,unique_id,verified_at) VALUES(?,?,?,?) "
"ON CONFLICT(uid) DO UPDATE SET installation=excluded.installation,"
"unique_id=excluded.unique_id,verified_at=excluded.verified_at",
(uid, digest, unique_id, int(self.clock())))
return None
def avatar_frame(self, uid, installation, frame, unique_id=None):
"""Publishes (or, for "none", withdraws) the avatar frame of `uid`, on the same terms as the avatar outline:
the account is proven once by the code in its bio, and the proving installation keeps the right to change it."""
if not valid_uid(uid) or not isinstance(installation, str) or not INSTALL.fullmatch(installation):
raise ValueError("Invalid account ID or installation code")
if frame != "none" and not (isinstance(frame, str) and FRAME.fullmatch(frame)):
raise ValueError("Unknown frame")
if frame != "none" and not self.frame_allowed(uid, frame):
raise ValueError("This frame is not available for this account")
digest = hashlib.sha256(installation.encode("ascii")).hexdigest()
with self.connect() as db:
if db.execute("SELECT 1 FROM blocked WHERE uid=?", (uid,)).fetchone():
raise ValueError("Account excluded")
owner = db.execute("SELECT installation FROM shape_owner WHERE uid=?", (uid,)).fetchone()
has_frame = db.execute("SELECT 1 FROM avatar_frames WHERE uid=?", (uid,)).fetchone()
proven = owner is not None and hmac.compare_digest(owner[0], digest)
if not proven and frame == "none" and not has_frame:
return {"ok": True, "published": True, "frame": "none"} # nothing to withdraw
if not proven:
reply = self._prove(uid, digest, unique_id)
if reply is not None:
return reply
with self.connect() as db:
if frame == "none":
db.execute("DELETE FROM avatar_frames WHERE uid=?", (uid,))
else:
db.execute("INSERT INTO avatar_frames(uid,frame,updated_at) VALUES(?,?,?) "
"ON CONFLICT(uid) DO UPDATE SET frame=excluded.frame,updated_at=excluded.updated_at",
(uid, frame, int(self.clock())))
return {"ok": True, "published": True, "frame": frame}
def lookup(self, uids):
if not isinstance(uids, list) or len(uids) > 100 or any(not valid_uid(uid) for uid in uids):
raise ValueError("Request at most 100 account IDs")
uids = list(dict.fromkeys(uids))
if not uids:
return {"members": {}}
placeholders = ",".join("?" for _ in uids)
with self.connect() as db:
rows = db.execute("SELECT uid,frame_color FROM presence WHERE uid IN (" + placeholders + ") AND last_seen >= ? AND uid NOT IN (SELECT uid FROM blocked)", uids + [int(self.clock()) - LIFETIME]).fetchall()
niche = {row[0] for row in db.execute(
"SELECT uid FROM niche WHERE uid IN (" + placeholders + ") AND uid NOT IN (SELECT uid FROM blocked)", uids
).fetchall()}
supporters = {row[0] for row in db.execute(
"SELECT uid FROM supporters WHERE uid IN (" + placeholders + ")", uids
).fetchall()}
shapes = {row[0]: row[1] for row in db.execute(
"SELECT uid,shape FROM shapes WHERE uid IN (" + placeholders + ") AND uid NOT IN (SELECT uid FROM blocked)", uids
).fetchall() if row[1] in SHAPES}
frames_of = {row[0]: row[1] for row in db.execute(
"SELECT uid,frame FROM avatar_frames WHERE uid IN (" + placeholders + ") AND uid NOT IN (SELECT uid FROM blocked)", uids
).fetchall() if FRAME.fullmatch(row[1])}
grants = {}
for row in db.execute("SELECT uid,frame FROM frame_grants WHERE uid IN (" + placeholders + ")", uids).fetchall():
grants.setdefault(row[0], []).append(row[1])
frames_of = {uid: frame for uid, frame in frames_of.items() if frame_permitted(frame, grants.get(uid, []))}
colors = {}
for uid, color in rows:
colors.setdefault(uid, color if color in ("none", "green", "red", "yellow") else "green")
return {"members": {uid: uid in colors for uid in uids}, "frames": colors,
"supporters": {uid: uid in supporters for uid in uids},
"niche": {uid: uid in niche for uid in uids}, "shapes": shapes, "avatar_frames": frames_of, "frame_grants": grants, "ttl": 300}
def frame_allowed(self, uid, frame):
"""May this account use this frame? Open packs: always; closed packs: only with a grant."""
if frame.split(".", 1)[0] not in RESTRICTED_PACKS:
return True
with self.connect() as db:
rows = db.execute("SELECT frame FROM frame_grants WHERE uid=?", (uid,)).fetchall()
return frame_permitted(frame, [row[0] for row in rows])
def set_frame_grant(self, uid, frame, enabled=True):
"""Admin-only when invoked from the server CLI; never exposed over HTTP. `frame` is "pack.name" or "pack.*"."""
if not valid_uid(uid):
raise ValueError("Invalid account ID")
if not isinstance(frame, str) or not GRANT.fullmatch(frame):
raise ValueError("Invalid frame")
with self.connect() as db:
if enabled:
db.execute("INSERT OR IGNORE INTO frame_grants(uid,frame,granted_at) VALUES(?,?,?)", (uid, frame, int(self.clock())))
else:
db.execute("DELETE FROM frame_grants WHERE uid=? AND frame=?", (uid, frame))
return {"uid": uid, "frame": frame, "granted": bool(enabled)}
def set_supporter(self, uid, enabled=True):
"""Admin-only when invoked from the server CLI; never exposed over HTTP."""
if not valid_uid(uid):
raise ValueError("Invalid account ID")
with self.connect() as db:
if enabled:
db.execute("INSERT OR IGNORE INTO supporters(uid,granted_at) VALUES(?,?)",
(uid, int(self.clock())))
else:
db.execute("DELETE FROM supporters WHERE uid=?", (uid,))
return {"uid": uid, "supporter": bool(enabled)}
class Limits:
def __init__(self):
self.events = defaultdict(deque)
self.lock = threading.Lock()
def allow(self, ip, operation):
key = ip, operation
window, count = ((60, 120) if operation == "lookup" else (3600, 10) if operation == "claim"
else (3600, 30) if operation in ("shape", "avatar_frame") else (3600, 40))
now = time.monotonic()
with self.lock:
if len(self.events) > 10000:
for old in list(self.events):
if not self.events[old] or self.events[old][-1] < now - 3600:
del self.events[old]
if len(self.events) > 10000 and key not in self.events:
return False
queue = self.events[key]
while queue and queue[0] < now - window:
queue.popleft()
if len(queue) >= count:
return False
queue.append(now)
return True
class Handler(BaseHTTPRequestHandler):
server_version = "LihonT-Members/1"
def log_message(self, fmt, *args):
# Do not log payloads, installation codes or account IDs.
pass
def send_json(self, status, payload):
raw = json.dumps(payload, separators=(",", ":")).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Cache-Control", "no-store")
self.send_header("Content-Length", str(len(raw)))
self.end_headers()
self.wfile.write(raw)
def do_GET(self):
self.send_json(200 if self.path == "/members/v1/health" else 404,
{"ok": True} if self.path == "/members/v1/health" else {"error": "Not found"})
def do_POST(self):
operation = self.path.removeprefix("/members/v1/")
if self.path != "/members/v1/" + operation or operation not in ("presence", "lookup", "withdraw", "code", "claim", "shape", "avatar_frame"):
return self.send_json(404, {"error": "Not found"})
# This server binds to localhost; nginx overwrites this header.
ip = self.headers.get("X-Real-IP", self.client_address[0])
if not self.server.limits.allow(ip, operation if operation in ("lookup", "claim", "shape", "avatar_frame") else "presence"):
return self.send_json(429, {"error": "Try again later"})
try:
length = int(self.headers.get("Content-Length", "0"))
if not 0 < length <= 8192:
return self.send_json(413, {"error": "Invalid payload size"})
self.connection.settimeout(10)
payload = json.loads(self.rfile.read(length))
if not isinstance(payload, dict):
raise ValueError("Expected an object")
if operation == "lookup":
result = self.server.registry.lookup(payload.get("uids"))
elif operation == "code":
result = {"code": self.server.registry.code(payload.get("uid")),
"deadline": CLAIM_DEADLINE, "open": time.time() <= CLAIM_DEADLINE}
elif operation == "claim":
result = self.server.registry.claim(payload.get("uid"), payload.get("unique_id"))
elif operation == "shape":
result = self.server.registry.shape(payload.get("uid"), payload.get("installation"),
payload.get("shape"), payload.get("unique_id"))
elif operation == "avatar_frame":
result = self.server.registry.avatar_frame(payload.get("uid"), payload.get("installation"),
payload.get("frame"), payload.get("unique_id"))
else:
result = self.server.registry.presence(payload.get("uid"), payload.get("installation"), operation == "withdraw", payload.get("frame_color", "green"))
self.send_json(200, result)
except (ValueError, TypeError, UnicodeError) as exc:
self.send_json(400, {"error": str(exc)})
except Exception:
self.send_json(503, {"error": "Service temporarily unavailable"})
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--database", required=True)
parser.add_argument("--port", type=int, default=18746)
parser.add_argument("--grant-supporter", metavar="UID", help="Grant the LihonT supporter badge locally")
parser.add_argument("--revoke-supporter", metavar="UID", help="Revoke the LihonT supporter badge locally")
parser.add_argument("--grant-frame", nargs=2, metavar=("UID", "FRAME"), help="Give an account a closed frame (vip.name) or a whole pack (vip.*)")
parser.add_argument("--revoke-frame", nargs=2, metavar=("UID", "FRAME"), help="Take a closed frame away from an account")
args = parser.parse_args()
Path(args.database).resolve().parent.mkdir(parents=True, exist_ok=True)
if args.grant_frame or args.revoke_frame:
registry = Registry(args.database)
uid, frame = args.grant_frame or args.revoke_frame
print(json.dumps(registry.set_frame_grant(uid, frame, enabled=bool(args.grant_frame))))
return
if args.grant_supporter or args.revoke_supporter:
registry = Registry(args.database)
print(json.dumps(registry.set_supporter(args.grant_supporter or args.revoke_supporter,
enabled=bool(args.grant_supporter))))
return
server = ThreadingHTTPServer(("127.0.0.1", args.port), Handler)
server.registry = Registry(args.database)
server.limits = Limits()
server.serve_forever()
if __name__ == "__main__":
main()