Download tiktok_auth.py from Reooiq/Hode: direct link, hf CLI and curl.
- Browser
- Download file 21.7 kB
-
https://huggingface.co/spaces/Reooiq/Hode/resolve/main/tiktok_auth.py
- Command line
-
hf download hf://spaces/Reooiq/Hode/tiktok_auth.py
-
curl -L -o tiktok_auth.py https://huggingface.co/spaces/Reooiq/Hode/resolve/main/tiktok_auth.py
21.7 kB
| """TikTok session-token support (Secrets/env vars + optional on-volume store). | |
| Why this exists | |
| --------------- | |
| Age-restricted (18+) TikTok LIVE rooms return **no stream URLs** to an | |
| anonymous visitor: `api-live/user/room` comes back with `status=2` but empty | |
| `streamData`/`hevcStreamData`, and `webcast/room/info/` answers with a | |
| `prompts`/error payload instead of `stream_url`. The room is therefore | |
| "unobservable" and can never be recorded or relayed. | |
| TikTok's own web client unlocks those rooms by sending a logged-in session. | |
| The cookie set that the reference implementations use is: | |
| sessionid, sessionid_ss, sid_tt (+ tt-target-idc for the account's DC) | |
| and the query flag user_is_login=true | |
| This module builds exactly that, and nothing else changes: same endpoints, | |
| same source ranking, same original-quality download. Sending the cookie to the | |
| signed CDN pull URL was verified harmless (identical FLV bytes with and | |
| without it), so one code path covers both API calls and video download. | |
| Secrets handling | |
| ---------------- | |
| Tokens are never logged, never returned by any API response, and never written | |
| into the recordings directory. Every outward-facing string is masked. | |
| """ | |
| import json, os, re, threading | |
| from pathlib import Path | |
| # Account data-centre cookie; only used when a session id is present. | |
| DEFAULT_TT_TARGET_IDC = 'useast1a' | |
| # sessionid / sessionid_ss / sid_tt / tt-target-idc | |
| SESSION_COOKIE_NAMES = ('sessionid', 'sessionid_ss', 'sid_tt') | |
| AUTH_CHECK_URL = 'https://www.tiktok.com/passport/web/account/info/' | |
| _lock = threading.RLock() | |
| _store_path = None | |
| _store_cache = None | |
| # --------------------------------------------------------------------------- # | |
| # storage | |
| # --------------------------------------------------------------------------- # | |
| def configure(path): | |
| """Point the optional on-volume token store at `<ROOT>/tiktok-tokens.json`.""" | |
| global _store_path, _store_cache | |
| with _lock: | |
| _store_path = Path(path) if path else None | |
| _store_cache = None | |
| def _norm(user): | |
| """Env-var-safe account key: TIKTOK_SESSIONID_MY.NAME -> MY_NAME.""" | |
| return re.sub(r'[^A-Z0-9]', '_', str(user or '').strip().upper()) | |
| def _read_store(): | |
| global _store_cache | |
| if _store_cache is not None: | |
| return _store_cache | |
| data = {} | |
| if _store_path: | |
| try: | |
| loaded = json.loads(_store_path.read_text(encoding='utf-8')) | |
| if isinstance(loaded, dict): | |
| data = {str(k): v for k, v in loaded.items() if isinstance(v, dict)} | |
| except (FileNotFoundError, ValueError, OSError): | |
| data = {} | |
| _store_cache = data | |
| return data | |
| def _write_store(data): | |
| global _store_cache | |
| if not _store_path: | |
| raise RuntimeError('مخزن التوكنات غير مهيأ؛ استخدم متغيرات Secrets بدلًا منه') | |
| tmp = _store_path.with_suffix('.tmp') | |
| tmp.write_text(json.dumps(data, ensure_ascii=False), encoding='utf-8') | |
| try: | |
| os.chmod(tmp, 0o600) | |
| except OSError: | |
| pass | |
| tmp.replace(_store_path) | |
| try: | |
| os.chmod(_store_path, 0o600) | |
| except OSError: | |
| pass | |
| _store_cache = data | |
| def _env(name): | |
| return (os.getenv(name) or '').strip() | |
| # --------------------------------------------------------------------------- # | |
| # parsing | |
| # --------------------------------------------------------------------------- # | |
| def parse_token(raw): | |
| """Accept whatever the user can realistically copy, return (sessionid, extra_cookies). | |
| Supported inputs: | |
| * bare session id 1a2b3c... | |
| * `sessionid=1a2b3c...` | |
| * full Cookie header `sessionid=x; sid_tt=x; ttwid=y; tt-target-idc=useast1a` | |
| * Netscape cookies.txt line `.tiktok.com\tTRUE\t/\tTRUE\t0\tsessionid\tx` | |
| * several of the above separated by newlines / commas / semicolons | |
| Unknown cookie names are preserved (e.g. ttwid, msToken) and sent as-is. | |
| """ | |
| text = str(raw or '').strip() | |
| if not text: | |
| return '', {} | |
| text = text.replace('\r', '\n') | |
| pairs = {} | |
| sessionid = '' | |
| for line in text.split('\n'): | |
| line = line.strip() | |
| if not line or line.startswith('#'): | |
| continue | |
| if '\t' in line and line.count('\t') >= 6: # Netscape cookies.txt | |
| parts = line.split('\t') | |
| pairs[parts[5].strip()] = parts[6].strip() | |
| continue | |
| # a Cookie header may use ';' as separator, a token list may use ',' | |
| chunks = re.split(r'[;,]', line) if ('=' in line) else [line] | |
| for chunk in chunks: | |
| chunk = chunk.strip() | |
| if not chunk: | |
| continue | |
| if '=' in chunk: | |
| k, _, v = chunk.partition('=') | |
| pairs[k.strip()] = v.strip() | |
| elif not sessionid: | |
| sessionid = chunk | |
| for name in SESSION_COOKIE_NAMES: | |
| if pairs.get(name) and not sessionid: | |
| sessionid = pairs[name] | |
| if sessionid: | |
| for name in SESSION_COOKIE_NAMES: | |
| pairs.setdefault(name, sessionid) | |
| idc = pairs.get('tt-target-idc') or pairs.get('tt_target_idc') or _env('TIKTOK_TT_TARGET_IDC') or DEFAULT_TT_TARGET_IDC | |
| if sessionid: | |
| pairs['tt-target-idc'] = idc.strip() | |
| return sessionid.strip(), {k: v for k, v in pairs.items() if v} | |
| def session_expiry(pairs): | |
| """Decode `sid_guard` if present: "<sid>|<issued>|<ttl_seconds>|<HTTP date>". | |
| TikTok issues short-lived web sessions (the sample we were given had | |
| ttl=21600, i.e. 6 hours), so an expired token is the single most common | |
| reason a pasted token "doesn't work". Reporting the deadline up front saves | |
| a debugging round trip. Returns None when sid_guard is absent. | |
| """ | |
| raw = (pairs or {}).get('sid_guard') | |
| if not raw: | |
| return None | |
| try: | |
| from urllib.parse import unquote | |
| parts = unquote(str(raw)).split('|') | |
| if len(parts) < 3: | |
| return None | |
| issued = int(parts[1]) | |
| ttl = int(parts[2]) | |
| except (ValueError, TypeError): | |
| return None | |
| import time as _time | |
| expires = issued + ttl | |
| return {'issued_at': issued, 'ttl_seconds': ttl, 'expires_at': expires, | |
| 'expired': _time.time() > expires, | |
| 'seconds_left': max(0, expires - int(_time.time())), | |
| 'expires_text': _time.strftime('%Y-%m-%d %H:%M UTC', _time.gmtime(expires))} | |
| def mask(value): | |
| """Safe display form. Never reveals enough of the token to be usable.""" | |
| s = str(value or '') | |
| if not s: | |
| return '' | |
| if len(s) <= 12: | |
| return '*' * len(s) | |
| return '%s…%s (%d حرفًا)' % (s[:4], s[-4:], len(s)) | |
| def _looks_like_sessionid(value): | |
| """sessionid is a long opaque token; reject obvious copy/paste mistakes early.""" | |
| s = str(value or '').strip() | |
| if len(s) < 20: | |
| return False, 'قصير جدًا (%d) — التوكن الصحيح عادةً أكثر من 100 حرف' % len(s) | |
| if len(s) > 4096: | |
| return False, 'طويل بشكل غير طبيعي (%d)' % len(s) | |
| if re.search(r'[\s"\']', s): | |
| return False, 'يحتوي مسافة أو علامة اقتباس — انسخ القيمة وحدها' | |
| if not re.fullmatch(r'[A-Za-z0-9%_\-:.+/=]+', s): | |
| return False, 'يحتوي رموزًا غير متوقعة' | |
| return True, '' | |
| # --------------------------------------------------------------------------- # | |
| # lookup | |
| # --------------------------------------------------------------------------- # | |
| def session_for(user=None): | |
| """Resolve the effective session for an account. | |
| Precedence (highest first). Secrets always win over the UI store, and a | |
| per-account value always wins over a global one: | |
| 1. TIKTOK_SESSIONID_<USER> per-account session id (Secret) | |
| 2. TIKTOK_COOKIES_<USER> per-account cookie header (Secret) | |
| 3. TIKTOK_TOKENS[user] per-account map entry (Secret) | |
| 4. TIKTOK_SESSIONID global, every account (Secret) | |
| 5. TIKTOK_COOKIES global cookie header (Secret) | |
| 6. store[user] per-account, saved from the UI | |
| 7. store['_default'] global, saved from the UI | |
| Rationale for 1-5 beating 6-7: a token pasted into the UI earlier must not | |
| silently override a freshly rotated Secret and keep failing in a way that | |
| looks like TikTok's fault. | |
| """ | |
| key = _norm(user) if user else '' | |
| if key: | |
| raw = _env('TIKTOK_SESSIONID_' + key) | |
| if raw: | |
| sid, pairs = parse_token(raw) | |
| return _pack(sid, pairs, 'TIKTOK_SESSIONID_' + key, user) | |
| raw = _env('TIKTOK_COOKIES_' + key) | |
| if raw: | |
| sid, pairs = parse_token(raw) | |
| return _pack(sid, pairs, 'TIKTOK_COOKIES_' + key, user) | |
| mapping = _env('TIKTOK_TOKENS') | |
| if mapping: | |
| for chunk in re.split(r'[;\n]', mapping): | |
| if not chunk.strip(): | |
| continue | |
| name, _, value = chunk.partition('=') | |
| if not value: | |
| name, _, value = chunk.partition(':') | |
| if _norm(name.strip()) == key and value.strip(): | |
| sid, pairs = parse_token(value) | |
| return _pack(sid, pairs, 'TIKTOK_TOKENS', user) | |
| raw = _env('TIKTOK_SESSIONID') | |
| if raw: | |
| sid, pairs = parse_token(raw) | |
| return _pack(sid, pairs, 'TIKTOK_SESSIONID', user) | |
| raw = _env('TIKTOK_COOKIES') | |
| if raw: | |
| sid, pairs = parse_token(raw) | |
| return _pack(sid, pairs, 'TIKTOK_COOKIES', user) | |
| store = _read_store() | |
| entry = None | |
| source_label = 'مخزن التطبيق' | |
| if user: | |
| entry = store.get(str(user).lower()) or store.get(key) | |
| if not (isinstance(entry, dict) and (entry.get('cookie') or entry.get('sessionid'))): | |
| entry = store.get('_default') | |
| source_label = 'مخزن التطبيق (افتراضي)' | |
| if isinstance(entry, dict) and (entry.get('cookie') or entry.get('sessionid')): | |
| sid, pairs = parse_token(entry.get('cookie') or entry.get('sessionid')) | |
| return _pack(sid, pairs, source_label, user) | |
| return _pack('', {}, None, user) | |
| def _pack(sessionid, pairs, source, user): | |
| cookie = '; '.join('%s=%s' % (k, v) for k, v in pairs.items()) if pairs else '' | |
| return {'user': str(user or '').lower(), 'sessionid': sessionid, 'cookie': cookie, | |
| 'authenticated': bool(sessionid), 'source': source, | |
| 'tt_target_idc': pairs.get('tt-target-idc', ''), 'masked': mask(sessionid), | |
| 'expiry': session_expiry(pairs)} | |
| def headers(user=None, extra=None): | |
| """Headers for any tiktok.com / webcast.tiktok.com / CDN pull request.""" | |
| result = {'Referer': 'https://www.tiktok.com/'} | |
| sess = session_for(user) | |
| if sess['cookie']: | |
| result['Cookie'] = sess['cookie'] | |
| if extra: | |
| result.update(extra) | |
| return result | |
| def extra_params(user=None): | |
| """TikTok gates some payloads on this flag; harmless when anonymous.""" | |
| return {'user_is_login': 'true'} if session_for(user)['authenticated'] else {} | |
| def describe(users=()): | |
| """Non-secret summary for the UI/state endpoint.""" | |
| users = list(users or ()) | |
| per_account = {} | |
| for u in users: | |
| s = session_for(u) | |
| per_account[u] = {'authenticated': s['authenticated'], 'source': s['source'], | |
| 'masked': s['masked'], 'tt_target_idc': s['tt_target_idc'], | |
| 'expiry': s.get('expiry')} | |
| glob = session_for(None) | |
| known_vars = sorted({n for n in os.environ if n.startswith('TIKTOK_')}) | |
| return {'default_authenticated': glob['authenticated'], 'default_source': glob['source'], | |
| 'default_masked': glob['masked'], 'default_expiry': glob.get('expiry'), | |
| 'accounts': per_account, | |
| 'accounts_with_token': [u for u, v in per_account.items() if v['authenticated']], | |
| 'env_variables_present': known_vars, | |
| 'store_configured': bool(_store_path), | |
| 'store_entries': sorted(k for k in _read_store() if k != '_default')} | |
| # --------------------------------------------------------------------------- # | |
| # save / delete (on-volume store) | |
| # --------------------------------------------------------------------------- # | |
| def save(user, token): | |
| user = ('_default' if not user else str(user).strip().lower()) | |
| sessionid, pairs = parse_token(token) | |
| if not sessionid: | |
| raise ValueError('لم يُعثر على sessionid صالح فيما لصقته') | |
| ok, why = _looks_like_sessionid(sessionid) | |
| if not ok: | |
| raise ValueError('صيغة التوكن غير مقبولة: ' + why) | |
| with _lock: | |
| data = dict(_read_store()) | |
| data[user] = {'cookie': '; '.join('%s=%s' % (k, v) for k, v in pairs.items()), | |
| 'sessionid': sessionid, 'tt_target_idc': pairs.get('tt-target-idc', ''), | |
| 'sid_guard': pairs.get('sid_guard', '')} | |
| _write_store(data) | |
| return {'user': user, 'masked': mask(sessionid), 'tt_target_idc': pairs.get('tt-target-idc', '')} | |
| def delete(user): | |
| user = ('_default' if not user else str(user).strip().lower()) | |
| with _lock: | |
| data = dict(_read_store()) | |
| if user not in data: | |
| return False | |
| del data[user] | |
| _write_store(data) | |
| return True | |
| # --------------------------------------------------------------------------- # | |
| # validation | |
| # --------------------------------------------------------------------------- # | |
| def validate(token, user=None, timeout=25): | |
| """Check a token against TikTok itself. Returns a plain-language report. | |
| Never raises for a *bad* token — a bad token is a normal, reportable result. | |
| Raises only on programmer/transport errors. | |
| """ | |
| from curl_cffi import requests | |
| sessionid, pairs = parse_token(token) | |
| report = {'ok': False, 'stage': 'format', 'sessionid_masked': mask(sessionid), | |
| 'tt_target_idc': pairs.get('tt-target-idc', ''), 'account': None, 'checks': [], | |
| 'expiry': session_expiry(pairs)} | |
| if report['expiry'] and report['expiry']['expired']: | |
| report['checks'].append('انتهت صلاحية هذه الجلسة يوم %s (عمرها %d ساعة)' | |
| % (report['expiry']['expires_text'], max(1, report['expiry']['ttl_seconds'] // 3600))) | |
| if not sessionid: | |
| report['message'] = 'لم يُعثر على sessionid. الصق قيمة الكوكي sessionid نفسها، أو كامل سطر Cookie.' | |
| return report | |
| ok, why = _looks_like_sessionid(sessionid) | |
| if not ok: | |
| report['message'] = 'صيغة غير مقبولة: ' + why | |
| return report | |
| report['checks'].append('الصيغة مقبولة') | |
| cookie = '; '.join('%s=%s' % (k, v) for k, v in pairs.items()) | |
| report['stage'] = 'auth' | |
| try: | |
| r = requests.get(AUTH_CHECK_URL, impersonate='chrome', timeout=timeout, | |
| headers={'Referer': 'https://www.tiktok.com/', 'Cookie': cookie}) | |
| payload = r.json() | |
| except Exception: | |
| report['message'] = 'تعذر الوصول إلى تيك توك للتحقق (شبكة أو حظر). أعد المحاولة.' | |
| return report | |
| data = payload.get('data') if isinstance(payload.get('data'), dict) else {} | |
| if data.get('error_code') or payload.get('message') == 'error': | |
| name = str(data.get('name') or '') | |
| if name == 'session_expired' or data.get('error_code') == 13: | |
| exp = report.get('expiry') | |
| detail = (' (انتهت فعليًا يوم %s)' % exp['expires_text']) if exp and exp['expired'] else '' | |
| report['message'] = ('تيك توك رفض التوكن: الجلسة منتهية أو غير صالحة%s. ' | |
| 'سجّل الدخول في المتصفح وانسخ sessionid من جديد — ' | |
| 'جلسات تيك توك قصيرة العمر وتنتهي خلال ساعات.' % detail) | |
| else: | |
| report['message'] = 'تيك توك رفض التوكن (%s / %s).' % (data.get('error_code'), name or 'unknown') | |
| return report | |
| report['ok'] = True | |
| report['stage'] = 'accepted' | |
| ident = {} | |
| for field in ('username', 'unique_id', 'nickname', 'screen_name', 'uid', 'user_id', 'sec_uid', | |
| 'email', 'mobile', 'has_password', 'is_18_plus', 'birthday', 'verified'): | |
| if data.get(field) not in (None, ''): | |
| ident[field] = str(data[field])[:60] | |
| report['account'] = ident | |
| report['checks'].append('تيك توك قبل التوكن وأعاده كجلسة مسجّلة دخول') | |
| who = ident.get('username') or ident.get('unique_id') or ident.get('nickname') or 'حساب مرتبط' | |
| report['message'] = 'التوكن صالح ومقبول. مرتبط بـ: %s' % who | |
| if ident.get('birthday') or ident.get('is_18_plus'): | |
| report['checks'].append('بيانات العمر ظاهرة في الجلسة (مهم لفتح البثوث المقيّدة 18+)') | |
| if user: | |
| report['checks'].append('سيُستخدم هذا التوكن للحساب @%s' % str(user).lower()) | |
| return report | |
| def unlock_check(user, timeout=25): | |
| """Does the configured session actually expose stream URLs for `user`? | |
| Compares anonymous vs authenticated lookups, so it reports the *effect* | |
| rather than just token validity. Read-only: creates nothing. | |
| """ | |
| from curl_cffi import requests | |
| user = str(user).strip().lower().lstrip('@') | |
| if not re.fullmatch(r'[A-Za-z0-9_.]{1,32}', user): | |
| raise ValueError('اسم حساب غير صالح') | |
| sess = session_for(user) | |
| def probe(with_token): | |
| hdrs = {'Referer': 'https://www.tiktok.com/'} | |
| if with_token and sess['cookie']: | |
| hdrs['Cookie'] = sess['cookie'] | |
| params = {'aid': 1988, 'uniqueId': user, 'sourceType': 54, 'staleTime': 0} | |
| if with_token and sess['authenticated']: | |
| params['user_is_login'] = 'true' | |
| r = requests.get('https://www.tiktok.com/api-live/user/room', params=params, | |
| impersonate='chrome', headers=hdrs, timeout=timeout) | |
| j = r.json() | |
| d = (j.get('data') or {}) | |
| live = d.get('liveRoom') or {} | |
| blocks = [live[k] for k in ('streamData', 'hevcStreamData') if isinstance(live.get(k), dict)] | |
| urls = 0 | |
| for b in blocks: | |
| p = (b.get('pull_data') or {}).get('stream_data') | |
| try: | |
| s = json.loads(p) if isinstance(p, str) else (p or {}) | |
| except ValueError: | |
| s = {} | |
| for _q, item in (s.get('data') or {}).items(): | |
| if ((item.get('main') or {}).get('flv')): | |
| urls += 1 | |
| return {'status': live.get('status'), 'urls': urls, | |
| 'not_found': j.get('message') == 'user_not_found'} | |
| anon = probe(False) | |
| if anon['not_found']: | |
| return {'user': user, 'result': 'user_not_found', 'token_configured': sess['authenticated'], | |
| 'message': 'تيك توك يقول أن الحساب غير موجود أو لم يبث مباشرًا قط. التوكن لا يحل هذه الحالة.'} | |
| if not sess['authenticated']: | |
| state = 'live' if anon['status'] in (2, '2') else 'offline' | |
| if state == 'live' and anon['urls'] == 0: | |
| return {'user': user, 'result': 'needs_token', 'token_configured': False, 'anonymous': anon, | |
| 'message': 'الحساب مباشر لكن تيك توك لا يعطي روابط فيديو بدون تسجيل دخول — هذه حالة تقييد عمري. أضف توكن.'} | |
| return {'user': user, 'result': state, 'token_configured': False, 'anonymous': anon, | |
| 'message': 'بدون توكن: %s وروابط الفيديو = %d.' % (state, anon['urls'])} | |
| auth = probe(True) | |
| gained = auth['urls'] - anon['urls'] | |
| if gained > 0: | |
| return {'user': user, 'result': 'unlocked', 'token_configured': True, | |
| 'anonymous': anon, 'authenticated': auth, | |
| 'message': 'التوكن يعمل ✔ روابط الفيديو: %d بدون توكن ← %d مع التوكن.' % (anon['urls'], auth['urls'])} | |
| if anon['urls'] > 0 and auth['urls'] > 0: | |
| return {'user': user, 'result': 'already_open', 'token_configured': True, | |
| 'anonymous': anon, 'authenticated': auth, | |
| 'message': 'الحساب مفتوح أصلًا بدون توكن (%d رابط). التوكن لا يضر لكن ليس سبب المشكلة.' % anon['urls']} | |
| return {'user': user, 'result': 'not_unlocked', 'token_configured': True, | |
| 'anonymous': anon, 'authenticated': auth, | |
| 'message': ('التوكن مقبول لكن لم يفتح روابط الفيديو لهذا الحساب الآن. ' | |
| 'الأسباب المحتملة: الحساب غير مباشر حاليًا، أو عمر الحساب المرتبط بالتوكن أقل من 18، ' | |
| 'أو الحساب محظور عنك. جرّب والفحص أثناء بث حي.')} | |
| def classify_restriction(payload): | |
| """True when a webcast payload is the age-restriction / prompts error shape.""" | |
| if not isinstance(payload, dict): | |
| return False | |
| data = payload.get('data') | |
| if not isinstance(data, dict): | |
| return False | |
| if 'prompts' in data and not data.get('stream_url'): | |
| return True | |
| return len(data) <= 1 and payload.get('status_code') not in (0, None) | |