#!/usr/bin/env python3
"""Public gateway proxy: streaming, explicit timeouts and safe errors."""
import asyncio
import base64
import hashlib
import hmac
import json
import logging
import os
import secrets
import sqlite3
import stat
import time
from contextlib import closing
from pathlib import Path
import aiohttp
from aiohttp import web, ClientSession
from multidict import CIMultiDict
from yarl import URL
from transparent_api import relay_api
from gateway_errors import HOP_HEADERS, key_from_headers, normalize_auth_headers, public_error, public_json_dumps
from public_site import adapt_public_status, register_public_routes
from account_limits import account_uid, daily_spent_units, DAILY_USD_CAP, QUOTA_PER_USD, OWNER_UID
import gateway_commerce
import commerce_access
from gateway_features import install as install_gateway_features
from gateway_provider_relay import relay_selected
from gateway_providers import ProviderError, ProviderRegistry
from gateway_policy import denial_response
# [MODELMETA 2026-10-28] vendor-reference limits: static JSON, read-only, no network.
# Optional import: the gateway must boot even if the reference file/module is absent.
try:
import model_metadata
except Exception: # pragma: no cover - deployment without the reference file
model_metadata = None
# [EFFORT-SCHEMA 2026-10-28] single shared effort validator (same module the pinned relay uses).
# Optional import keeps the gateway bootable if the standalone module is not deployed yet.
try:
from request_effort import InvalidEffort, read_effort
except Exception: # pragma: no cover - standalone validator absent
InvalidEffort, read_effort = None, None
def _attach_model_metadata(env):
"""Add vendor-reference metadata to /v1/models rows in place; True when changed.
Reference-only data (context window / max output as advertised by the vendor,
gateway_verified=false). Never raises, never invents numbers and never touches
rows without a string id: on any problem the upstream body is used untouched.
"""
try:
data = env.get("data") if isinstance(env, dict) else None
if not isinstance(data, list) or model_metadata is None:
return False
if not any(isinstance(row, dict) and isinstance(row.get("id"), str) for row in data):
return False
enriched = model_metadata.attach_rows(data)
if not isinstance(enriched, list) or len(enriched) != len(data):
return False
env["data"] = enriched
return True
except Exception:
LOG.warning("model_metadata_failed", exc_info=True)
return False
async def _models_catalogue_response(req, upstream):
"""Enrich GET /v1/models once, before transparent dispatch; None means "keep relay_api".
Runs only on the already-open upstream of the single request the caller made, so
no reply is ever fetched twice. The body is read only when an uncompressed 200
JSON catalogue can be returned from here; every other reply (non-200, non-JSON,
compressed) is left unconsumed for relay_api. Ids, order and all other fields are
preserved, and an unparseable body or an absent vendor reference is returned
byte-exact instead of being re-serialized.
"""
if req.method == "GET" and req.path == "/v1/models":
encoding = (upstream.headers.get("Content-Encoding") or "").strip().lower()
if (upstream.status == 200
and "json" in upstream.headers.get("Content-Type", "").lower()
and encoding in ("", "identity")
and model_metadata is not None and model_metadata.available()):
raw = await upstream.read()
headers = response_headers(upstream.headers)
try:
env = json.loads(raw)
except (ValueError, UnicodeDecodeError):
env = None
if isinstance(env, dict) and isinstance(env.get("data"), list) and _attach_model_metadata(env):
# Stale validators would contradict the enriched bytes.
headers = {name: value for name, value in headers.items()
if name.lower() not in ("etag", "content-md5")}
LOG.info("models_metadata_enriched rows=%d", len(env["data"]))
return web.Response(status=upstream.status, body=json.dumps(env).encode(),
headers=headers)
return web.Response(status=upstream.status, body=raw, headers=headers)
return None
PROVIDER_KEY = web.AppKey("iishko_providers", ProviderRegistry)
UPSTREAM = os.environ.get("IISHKO_UPSTREAM", "http://127.0.0.1:48000")
TIMEOUT = aiohttp.ClientTimeout(total=None, connect=10, sock_connect=10, sock_read=860)
# Preserve the existing 64 generation slots; reserve independent capacity for reads.
GENERATION_CONNECTIONS = 256
CONTROL_CONNECTIONS = 64
SKIP = ("/v1/", "/api/", "/static/", "/oauth/")
MAX_BODY = 40 * 1024 * 1024
MAX_SSE_FRAME = 65536
LOG = logging.getLogger("gateway_proxy")
# ---------- [GATE] daily checkin + chat subscription enforcement (owner 2026-10-08) ----------
# Reads current bot-account policy; unavailable databases temporarily deny access.
GATE_BOT_DB = os.environ.get("GATE_BOT_DB", os.environ.get("IISHKO_BOT_DB", "/opt/grok-bot/bot.db"))
GATE_NEWAPI_DB = os.environ.get("GATE_NEWAPI_DB", os.environ.get("IISHKO_GW_DB", "/opt/grok-gateway/new-api/one-api.db"))
GATE_TTL = 60
_gate_cache = {}
_gate_err_ts = [0.0]
class GateUnavailable(RuntimeError):
pass
def _owner_identity(name):
"""All exact main/pm/sol/additional names share one Telegram identity."""
uid = account_uid(name)
return "tg%d" % uid if uid is not None else None
def _gate_connect(path):
"""Read the live WAL without creating a missing policy database."""
con = sqlite3.connect(Path(path).resolve().as_uri() + "?mode=rw", uri=True, timeout=3)
con.execute("PRAGMA busy_timeout=3000")
con.execute("PRAGMA query_only=ON")
return con
def gate_boot_selfcheck():
"""Loud startup proof the gate reads the right DBs — silent no-op is the failure mode we fear."""
for path, probe in ((GATE_NEWAPI_DB, "SELECT count(*) FROM tokens LIMIT 1"),
(GATE_BOT_DB, "SELECT count(*) FROM users WHERE api_blocked IS NOT NULL LIMIT 1"),
(GATE_BOT_DB, "SELECT count(*) FROM users WHERE banned IS NOT NULL LIMIT 1")):
try:
con = _gate_connect(path)
con.execute(probe)
con.close()
LOG.warning("gate_selfcheck_ok %s", path)
except Exception as e:
LOG.error("GATE_SELFCHECK_FAIL %s: %s — gate will temporarily deny access", path, type(e).__name__)
def _gate_lookup_sync(api_key):
try:
with closing(_gate_connect(GATE_NEWAPI_DB)) as con:
rows = con.execute("SELECT name FROM tokens WHERE key=? AND deleted_at IS NULL LIMIT 2",
(api_key,)).fetchall()
if len(rows) > 1:
raise GateUnavailable("ambiguous credential")
uid = account_uid(rows[0][0]) if rows else None
if uid is None:
return (False, "")
with closing(_gate_connect(GATE_BOT_DB)) as con:
r = con.execute("SELECT api_blocked, api_block_reason, banned FROM users WHERE tg_id=?",
(uid,)).fetchone()
if not r:
return (True, "Аккаунт ключа не найден. Открой бота. Поддержка: @your-handle")
if r[2]:
return (True, "Аккаунт заблокирован. Апелляция: @your-handle")
if r[0]:
return (True, r[1] or "Ключ приостановлен. Открой бота и нажми Дейли.")
return (False, "")
except Exception as e:
now = time.monotonic()
if now - _gate_err_ts[0] > 60:
_gate_err_ts[0] = now
LOG.warning("gate_lookup_unavailable: %s", type(e).__name__)
raise GateUnavailable("account policy unavailable") from None
GATE_TTL_BLOCKED = 10 # blocked verdicts expire fast: user unblocks instantly after Дейли/join
async def gate_check(api_key):
# An allow verdict must never survive a ban or a policy-database failure.
hit = _gate_cache.get(api_key)
now = time.monotonic()
if hit and hit[1][0] and now - hit[0] < GATE_TTL_BLOCKED:
return hit[1]
res = await asyncio.to_thread(_gate_lookup_sync, api_key)
if len(_gate_cache) > 4096:
_gate_cache.clear()
if res[0]:
_gate_cache[api_key] = (now, res)
else:
_gate_cache.pop(api_key, None)
return res
# ---------- [RANK-LIMITS 2026-10-17] суточные лимиты по рангам (единые счётчики с ботом) ----------
# A single write transaction serializes main/pm/sol/additional request counters.
RL_TOTAL = {0: 5000, 1: 5000, 2: 10000, 3: 20000, 4: 30000}
RL_PREM = {
"gpt-6-luna": {0: 200, 1: 500, 2: 1500, 3: 5000, 4: 10000}, # [LIMIT-BOOST2 2510] # [LIMIT-BOOST2 2510] # [LIMIT-BOOST2 2510] # [LUNA-BOOST 2510] daily request caps per rank
"gpt-6.1-sol": {0: 100, 1: 250, 2: 800, 3: 2000, 4: 5000}, # [LIMIT-BOOST2 2510] # [LIMIT-BOOST2 2510] # [LIMIT-BOOST2 2510]
"opus": {0: 100, 1: 250, 2: 800, 3: 2000, 4: 5000}, # [LIMIT-BOOST2 2510] # [LIMIT-BOOST2 2510] # [LIMIT-BOOST2 2510]
"fable": {0: 100, 1: 250, 2: 800, 3: 2000, 4: 5000}, # [LIMIT-BOOST2 2510] # [LIMIT-BOOST2 2510] # [LIMIT-BOOST2 2510]
"astra": {0: 100, 1: 250, 2: 800, 3: 2000, 4: 5000}, # [LIMIT-BOOST2 2510] # [LIMIT-BOOST2 2510] # [LIMIT-BOOST2 2510]
}
RL_NAMES = {0: "Новичок", 1: "Новичок", 2: "Актив", 3: "Профи", 4: "Легенда"}
def _rl_today_msk():
return time.strftime("%Y-%m-%d", time.gmtime(int(time.time()) + 3 * 3600))
def _rl_class(model):
if not model:
return None
m = str(model); ml = m.lower()
if m.startswith("gpt-6.1-sol") or m in ("gpt-5.6-sol", "gpt-5.5", "gpt-5.5-pro"): return "gpt-6.1-sol"
if m.startswith("gpt-6-luna") or m in ("gpt-5.6-luna", "gpt-5.6-terra"): return "gpt-6-luna"
if "opus" in ml: return "opus"
if "fable" in ml: return "fable"
if ml.startswith("gpt-6-astra"): return "astra"
return None
def _rl_check_sync(api_key, model):
"""None = allowed; (403/429/503, message) = denied; never fail open."""
try:
with closing(_gate_connect(GATE_NEWAPI_DB)) as gateway:
rows = gateway.execute(
"SELECT name FROM tokens WHERE key=? AND deleted_at IS NULL LIMIT 2",
(api_key,)).fetchall()
if len(rows) > 1:
raise GateUnavailable("ambiguous credential")
uid = account_uid(rows[0][0]) if rows else None
if uid is None:
return None
now = int(time.time())
# [VIP-FASTPATH 2510] VIP/безлимит/владелец: read-only проверка без write-lock на bot.db.
# Раньше BEGIN IMMEDIATE ставил в очередь каждый запрос и добавлял 5-11с задержки -> 503/504 "перегруз".
try:
with closing(sqlite3.connect("file:" + GATE_BOT_DB + "?mode=ro", uri=True, timeout=3)) as _rd:
_fr = _rd.execute("SELECT vip,unlim_until,admin,banned FROM users WHERE tg_id=?", (uid,)).fetchone()
if _fr:
_vip, _unlim, _adm, _ban = _fr
if _ban:
return (403, "Аккаунт заблокирован. Апелляция: @your-handle")
if _vip or _adm or (_unlim and int(_unlim) > now):
return None
except Exception:
pass
day_start = now - ((now + 3 * 3600) % 86400)
spent = 0 if uid == OWNER_UID else daily_spent_units(
GATE_NEWAPI_DB, uid, day_start, day_start + 86400)
extra_requests = gateway_commerce.entitlements(GATE_BOT_DB, uid, now=now)["extra_requests"]
uri = Path(GATE_BOT_DB).resolve().as_uri() + "?mode=rw"
with closing(sqlite3.connect(uri, uri=True, timeout=5)) as con:
con.execute("PRAGMA busy_timeout=5000")
con.execute("BEGIN IMMEDIATE")
try:
r = con.execute(
"SELECT vip,unlim_until,admin,rank_cache,banned,api_blocked,"
"api_block_reason,badge_lock,badge_until FROM users WHERE tg_id=?",
(uid,)).fetchone()
if not r:
con.rollback()
return (403, "Аккаунт ключа не найден. Открой бота. Поддержка: @your-handle")
vip, unlim, adm, cached_rank, banned, blocked, reason, locked_rank, until = r
if banned or blocked:
con.rollback()
return (403, "Аккаунт заблокирован. Апелляция: @your-handle" if banned else
(reason or "Ключ приостановлен. Открой бота и нажми Дейли."))
effective_lock = int(locked_rank or 0) if not until or int(until) > now else 0
rank = min(4, max(0, effective_lock, int(cached_rank if cached_rank is not None else 1)))
usd_cap = DAILY_USD_CAP[rank]
if uid != OWNER_UID and not (vip or adm or (unlim and int(unlim) > now)) and spent >= usd_cap * QUOTA_PER_USD:
con.rollback()
return (429, "Дневной бюджет $%d исчерпан на всех ключах аккаунта. "
"Обнулится в 00:00 MSK; баланс сохранён." % usd_cap)
if vip or adm or (unlim and int(unlim) > now):
con.rollback()
return None
con.execute("CREATE TABLE IF NOT EXISTS kv (k TEXT PRIMARY KEY, v TEXT)")
lim = RL_TOTAL[rank] + extra_requests
today = _rl_today_msk()
cls = _rl_class(model)
prem_used, k, cap = 0, None, 0
if cls:
cap = RL_PREM[cls].get(rank, 20)
k = "pmc:%d:%s:%s" % (uid, cls, today)
kv = con.execute("SELECT v FROM kv WHERE k=?", (k,)).fetchone()
prem_used = int(float(kv[0])) if kv and kv[0] else 0
if prem_used >= cap:
con.rollback()
return (429, "Лимит на %s исчерпан: %d/%d запросов в день. "
"Обнулится в 00:00 MSK." % (cls, prem_used, cap))
con.execute(
"UPDATE users SET chat_count=0,img_count=0,quota_date=? WHERE tg_id=? "
"AND (quota_date IS NULL OR quota_date!=?)", (today, uid, today))
cur = con.execute(
"UPDATE users SET chat_count=COALESCE(chat_count,0)+1,quota_date=? WHERE tg_id=? "
"AND COALESCE(chat_count,0)", (today, uid, lim))
if cur.rowcount != 1:
r2 = con.execute("SELECT chat_count FROM users WHERE tg_id=?", (uid,)).fetchone()
con.rollback()
used = int(r2[0] or 0) if r2 else lim
return (429, "Дневной лимит исчерпан: %d/%d запросов (ранг «%s»). "
"Обнулится в 00:00 MSK." % (used, lim, RL_NAMES.get(rank, "")))
if k:
con.execute("INSERT OR REPLACE INTO kv (k,v) VALUES (?,?)", (k, str(prem_used + 1)))
con.commit()
return None
except BaseException:
con.rollback()
raise
except Exception as e:
now2 = time.monotonic()
if now2 - _gate_err_ts[0] > 60:
_gate_err_ts[0] = now2
LOG.warning("rank_limits_unavailable: %s", type(e).__name__)
return (503, "Проверка лимитов временно недоступна. Повтори запрос позже.")
SESSION_KEY = getattr(web, "App" + "Key")("session", ClientSession) if hasattr(web, "App" + "Key") else "session"
CONTROL_SESSION_KEY = getattr(web, "App" + "Key")("control_session", ClientSession) if hasattr(web, "App" + "Key") else "control_session"
async def _open_upstream_sessions(app):
"""Shared startup/lazy factory; each session owns a separate bounded connector."""
created = []
try:
for key, limit in ((SESSION_KEY, GENERATION_CONNECTIONS),
(CONTROL_SESSION_KEY, CONTROL_CONNECTIONS)):
session = app.get(key)
if session is not None and not session.closed:
continue
connector = aiohttp.TCPConnector(
limit=limit, limit_per_host=limit, keepalive_timeout=15)
try:
session = ClientSession(timeout=TIMEOUT, connector=connector)
except BaseException:
await connector.close()
raise
created.append(session)
app[key] = session
except BaseException:
for session in created:
if not session.closed:
await session.close()
raise
async def _close_upstream_sessions(app):
for key in (SESSION_KEY, CONTROL_SESSION_KEY):
session = app.get(key)
if session is not None and not session.closed:
await session.close()
INJECT = b"""
"""
# ---------- [DEDUP][GROUPS] public pricing showcase (2026-10-11) ----------
# Hide spelling duplicates + internal group. Display-only: billing untouched.
HIDDEN_GROUP = "conol"
HIDE_MODEL_NAMES = frozenset({
"", " ", "all", "codex-auto-review",
})
# Routing/billing не затронуты — алиасы продолжают работать через abilities.
PRICING_SHOWCASE = frozenset([
"glm-5.3", "glm-5.3-flash", "glm-5.3-prime", "deepseek-v4.1-flash",
"deepseek-v4-pro", "deepseek-chat", "deepseek-reasoner", "kimi-k3",
"kimi/kimi-k3.1-pro", "kimi/kimi-k3.1-pro-highspeed", "kimi-k2.7-code", "kimi-k2.6",
"qwen3.8-max", "qwen3.8-max-0902", "grok-chat-fast", "grok-4.7",
"grok-composer-2.5-fast", "claude-5.5-sonnet", "claude-haiku-5.5", "gpt-6-luna",
"gpt-6.1-sol", "opus-5.5", "claude-fable-5-1", "gpt-6-astra", "gemini-3.5-flash",
"glm-5.3-flash-free", "deepseek-v4.1-flash:free", "deepseek/deepseek-v4.1-flash-free",
"gpt-imagine-2.5", "grok-imagine-image-2.0", "cogview-3-flash", "wan2.6-t2v",
# Owner-requested public catalog restoration; response filtering only, never routing/billing.
"deepseek-v4.1-flash-1017", "deepseek-v4-flash", "qwen-plus", "qwen-max",
"qwen3.8-flash", "qwen3.8-27b", "qwen3.7-max", "gpt-5.6-luna", "gpt-5.6-terra",
"gpt-5.6-sol", "gpt-6.1-sol-thinking", "gpt-5.5", "gpt-5.5-pro",
"claude-opus-5-5", "claude-opus-4-6", "gpt-image-2.5", "grok-imagine-image",
"grok-imagine-image-lite", "nano-banana", "seedream-5", "wan2.2-t2i-flash",
"wanx2.1-t2i-turbo", "z-image", "seedance-2-mini", "veo", "wan-3-0",
])
# [PRICING-ALL 2026-10-20] витрина = ВСЕ живые модели шлюза (abilities enabled=1
import sqlite3 as _sqlite3, threading as _threading
_LIVE_DB = "/opt/grok-gateway/new-api/one-api.db"
_live_lock = _threading.Lock()
_live_cache = {"ts": 0.0, "models": set()}
EXTRA_HIDE = frozenset({
"", " ", "all", "codex-auto-review",
}) # [ALLMODELS 20.10] витрина = ВСЕ живые модели; скрыт только мусор
def get_live_models():
import time as _t
with _live_lock:
if _t.time() - _live_cache["ts"] < 300 and _live_cache["models"]:
return _live_cache["models"]
try:
con = _sqlite3.connect(_LIVE_DB, timeout=5)
con.execute("PRAGMA busy_timeout=5000")
rows = con.execute(
"SELECT DISTINCT a.model FROM abilities a JOIN channels c ON c.id=a.channel_id "
"WHERE a.enabled=1 AND c.status=1").fetchall()
con.close()
models = {r[0] for r in rows if r[0] and r[0].strip()}
if models:
with _live_lock:
_live_cache["ts"] = _t.time(); _live_cache["models"] = models
return models
except Exception:
LOG.warning("live_models_db_fail", exc_info=True)
with _live_lock:
return _live_cache["models"]
def _hidden(nm):
if nm in HIDE_MODEL_NAMES or nm in EXTRA_HIDE:
return True
if isinstance(nm, str) and (nm.startswith("ngodeai/") or nm.startswith("orca-")):
return True
return False
def filter_pricing_body(raw):
try:
envelope = json.loads(raw)
if not isinstance(envelope, dict):
return raw
rows = envelope.get('data')
if not isinstance(rows, list) or not rows:
return raw
kept, changed = [], False
# [ALLMODELS 20.10] показываем ВСЕ живые модели; дедуп = только алиасы
# одного имени (регистр/дефисы/провайдер-префикс). Приоритет: точечная
# форма, нижний регистр, короче.
def _norm_key(nm):
s = str(nm).lower()
if '/' in s:
s = s.rsplit('/', 1)[-1]
return s.replace('-', '.')
_cand = {}
for r in rows:
if isinstance(r, dict) and r.get('model_name') is not None:
_cand.setdefault(_norm_key(r['model_name']), []).append(str(r['model_name']))
_best = {k: min(v, key=lambda n: (0 if '.' in n else 1, 0 if n == n.lower() else 1, len(n)))
for k, v in _cand.items()}
live = get_live_models()
for row in rows:
if isinstance(row, dict):
nm = row.get('model_name')
if _hidden(nm):
changed = True
continue
if live and nm not in live:
changed = True
continue
if _best.get(_norm_key(nm)) != str(nm):
changed = True
continue
kept.append(row)
for key in ('auto_groups', 'usable_group'):
val = envelope.get(key)
if isinstance(val, list) and HIDDEN_GROUP in val:
envelope[key] = [g for g in val if g != HIDDEN_GROUP]
changed = True
elif isinstance(val, dict) and HIDDEN_GROUP in val:
envelope[key] = {k: v for k, v in val.items() if k != HIDDEN_GROUP}
changed = True
gr = envelope.get('group_ratio')
if isinstance(gr, dict) and HIDDEN_GROUP in gr:
envelope['group_ratio'] = {k: v for k, v in gr.items() if k != HIDDEN_GROUP}
changed = True
for row in kept:
if isinstance(row, dict):
eg = row.get('enable_groups')
if isinstance(eg, list) and HIDDEN_GROUP in eg:
row['enable_groups'] = [g for g in eg if g != HIDDEN_GROUP]
changed = True
# Биллинг (options ModelRatio/ModelPrice) не трогается — юзер платит 2xOR.
for row in kept:
if isinstance(row, dict):
# These two explicit customer tariffs must not inherit the legacy OR display discount.
if row.get("model_name") in ("kimi/kimi-k3.1-pro", "kimi/kimi-k3.1-pro-highspeed"):
continue
for f_ in ("model_ratio", "model_price"):
v = row.get(f_)
if isinstance(v, (int, float)) and v:
row[f_] = round(v / 2, 6)
changed = True
if not changed:
return raw
envelope['data'] = kept
return json.dumps(envelope, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
except Exception:
return raw
def response_headers(headers):
connection = {v.strip().lower() for v in headers.get("Connection", "").split(",")}
excluded = HOP_HEADERS | connection | {"content-encoding"}
return CIMultiDict((k, v) for k, v in headers.items() if k.lower() not in excluded)
def error_response(status, raw, path, headers=None, user_balance=None, from_upstream=False, api_key=None):
upstream_status = status
status, payload = public_error(status, raw, path, user_balance=user_balance,
from_upstream=from_upstream, api_key=api_key)
request_id = secrets.token_hex(16)
payload["error"]["gateway_request_id"] = request_id
payload["error"].setdefault("request_id", request_id)
LOG.warning("client_error status=%s upstream_status=%s code=%s path=%s request_id=%s",
status, upstream_status, payload["error"]["code"], path, request_id)
safe_headers = CIMultiDict((k, v) for k, v in (headers or {}).items()
if k.lower() == "retry-after")
safe_headers["Cache-Control"] = "no-store"
safe_headers["X-Request-ID"] = request_id
return web.json_response(payload, status=status, headers=safe_headers, dumps=public_json_dumps)
def map_sse_frame(frame: bytes, path: str) -> bytes:
"""Pass through byte-exact; if a data: frame contains JSON {"error":...} -> map to event: error."""
if len(frame) > MAX_SSE_FRAME:
return frame
# Only inspect frames whose first line is "data:"
raw_lines = frame.split(b"\n")
data = [ln[5:].strip() for ln in raw_lines if ln.startswith((b"data:", b"data "))]
if not data:
return frame
payload = b"\n".join(data)
if payload.strip() == b"[DONE]":
return frame
try:
obj = json.loads(payload)
except (ValueError, UnicodeDecodeError):
return frame
if not isinstance(obj, dict) or "error" not in obj:
return frame
err = obj["error"]
status = 400
if isinstance(err, dict) and err.get("status"):
try: status = int(err["status"])
except (ValueError, TypeError): pass
elif obj.get("status"):
try: status = int(obj["status"])
except (ValueError, TypeError): pass
if status == 400 and path in _GEN_PATHS:
# [NO-SOFT 2026-10-14] 400 в стриме → честный event: error (фейк-отказ OFF)
LOG.warning("error_sse_400 path=%s", path)
_, mapped = public_error(status, json.dumps(obj).encode(), path)
return b"event: error\ndata: " + json.dumps(mapped, ensure_ascii=False).encode()
async def relay(req, upstream):
headers = response_headers(upstream.headers)
is_html = not any(req.path.startswith(s) for s in SKIP) and "text/html" in upstream.headers.get("Content-Type", "")
if is_html:
body = await upstream.read()
start = body.find(b"
")
if start < 0:
start = body.find(b"= 0:
end = body.find(b">", start) + 1
body = body[:end] + INJECT + body[end:]
headers["Cache-Control"] = "no-cache"
return web.Response(status=upstream.status, body=body, headers=headers)
# 2026-10-11: «дубликаты моделей, надо 1 только» — скрываем дефисные алиасы из списка моделей.
if (req.method == "GET" and req.path in ("/v1/models", "/api/user/models") and upstream.status == 200
and "json" in upstream.headers.get("Content-Type", "").lower()):
raw = await upstream.read()
try:
env = json.loads(raw)
data = env.get("data")
if isinstance(data, list):
kept = [x for x in data if (
(isinstance(x, dict) and x.get("id") in PRICING_SHOWCASE)
or (isinstance(x, str) and x in PRICING_SHOWCASE))]
if len(kept) != len(data):
env["data"] = kept
LOG.info("models_dedup %d -> %d", len(data), len(kept))
raw = json.dumps(env).encode()
# [MODELMETA 2026-10-28] vendor reference on each surviving row:
# context window / max output as the vendor advertises them,
# gateway_verified=false. Ids, order and every other field are kept.
if _attach_model_metadata(env):
raw = json.dumps(env).encode()
except Exception:
pass
return web.Response(status=upstream.status, body=raw, headers=headers)
if (req.method == "GET" and req.path == "/api/pricing" and upstream.status == 200
and "json" in upstream.headers.get("Content-Type", "").lower()):
raw = await upstream.read()
filtered = filter_pricing_body(raw)
if filtered is not raw:
LOG.info("pricing_dedup %d -> %d bytes", len(raw), len(filtered))
return web.Response(status=upstream.status, body=filtered, headers=headers)
if (req.method == "GET" and req.path == "/api/status" and upstream.status == 200
and "json" in upstream.headers.get("Content-Type", "").lower()):
raw = await upstream.read()
body = adapt_public_status(raw)
if body is not raw:
headers.pop("ETag", None)
headers.pop("Content-MD5", None)
headers["Cache-Control"] = "no-store"
return web.Response(status=upstream.status, body=body, headers=headers)
response = web.StreamResponse(status=upstream.status, headers=headers)
await response.prepare(req)
try:
ctype = headers.get("Content-Type", "").lower()
if "text/event-stream" in ctype:
buf = b""
async for chunk in upstream.content.iter_any():
buf += chunk
while True:
sep_s = buf.find(b"\n\n")
sep_c = buf.find(b"\r\n\r\n")
if sep_s < 0 and sep_c < 0:
break
if sep_s >= 0 and (sep_c < 0 or sep_s < sep_c):
frame, buf = buf[:sep_s], buf[sep_s + 2:]
sep = b"\n\n"
else:
frame, buf = buf[:sep_c], buf[sep_c + 4:]
sep = b"\r\n\r\n"
await response.write(map_sse_frame(frame, req.path) + sep)
if len(buf) > MAX_SSE_FRAME:
await response.write(buf)
buf = b""
if buf:
await response.write(buf)
else:
async for chunk in upstream.content.iter_any():
await response.write(chunk)
await response.write_eof()
except ConnectionResetError:
LOG.info("client_disconnected")
except (aiohttp.ClientError, asyncio.TimeoutError) as exc:
code = 504 if isinstance(exc, asyncio.TimeoutError) else 503
_, payload = public_error(code, b"", req.path)
LOG.warning("upstream_stream_failed code=%s", payload["error"]["code"])
try:
ct = headers.get("Content-Type", "").lower()
if "text/event-stream" in ct:
await response.write(b"event: error\ndata: " + json.dumps(payload).encode() + b"\n\n")
await response.write_eof()
elif req.transport is not None:
req.transport.close()
except (ConnectionResetError, aiohttp.ClientError):
LOG.info("client_disconnected_during_error")
except Exception:
LOG.exception("upstream_unexpected")
_, fb = public_error(502, b"", req.path)
try:
ct = headers.get("Content-Type", "").lower()
if "text/event-stream" in ct:
await response.write(b"event: error\ndata: " + json.dumps(fb).encode() + b"\n\n")
await response.write_eof()
elif req.transport is not None:
req.transport.close()
except (ConnectionResetError, aiohttp.ClientError):
pass
return response
# Count billable API entry points under the same account gate; changing endpoint
# must not create a second budget. Routing and upstream payloads stay untouched.
_GEN_PATHS = (
"/v1/chat/completions", "/v1/completions", "/v1/responses", "/v1/messages",
"/v1/embeddings", "/v1/images/generations", "/v1/images/edits", "/v1/images/variations",
"/v1/audio/speech", "/v1/audio/transcriptions", "/v1/audio/translations",
)
# ---------- [ROLECOMPAT 2026-10-23] developer->system for incompatible families ----------
# Live evidence (live-contract-before.txt): qwen-plus rejects "developer" role with
# native 400 ("developer is not one of ['system','assistant','user','tool','function']"),
# while system/assistant/user/tool/function and two-step tool calls pass (200).
# new-api (QuantumNous, pinned 7fb6e57a) normalizes developer->system only for
# incompatible protocols, not this public /v1/chat/completions path, so the skin
# does it at the boundary. Scope is deliberately narrow: ONLY /v1/chat/completions
# POST and ONLY explicitly known incompatible families (qwen/glm/deepseek/kimi).
# GPT/Claude and every other endpoint stay raw.
_DEV_ROLE_INCOMPAT_PREFIXES = ("qwen", "glm", "deepseek", "kimi")
def _dev_role_incompat_model(model):
"""True only for explicitly known incompatible families (qwen/glm/deepseek/kimi)."""
if not isinstance(model, str):
return False
m = model.strip().lower()
if "/" in m:
m = m.rsplit("/", 1)[-1]
return m.startswith(_DEV_ROLE_INCOMPAT_PREFIXES)
def _normalize_developer_roles(request_object):
"""In-place developer->system rewrite on top-level messages; True if changed.
Only the "role" value is touched: content, message order, name, tool_calls,
tools, and every other request field are preserved as parsed. Returns False
(body stays byte-exact, never re-serialized) when there is no developer role.
"""
if not isinstance(request_object, dict):
return False
msgs = request_object.get("messages")
if not isinstance(msgs, list):
return False
changed = False
for msg in msgs:
if isinstance(msg, dict) and msg.get("role") == "developer":
msg["role"] = "system"
changed = True
return changed
async def proxy(req):
is_api = req.path.startswith("/v1/")
try:
headers = normalize_auth_headers(req.headers) if is_api else response_headers(req.headers)
except ValueError:
return web.json_response({"error": {"message": "Переданы разные API-ключи. Оставьте один способ авторизации.", "type": "invalid_request_error", "code": "conflicting_authentication", "retryable": False}}, status=400)
if is_api:
# Ownership comes from the DB (token name = "tg"), never from arrival
# order: a mismatched logged-in account is blocked without changing wallets.
# Identity is known only when a site session cookie rides along.
_ks_cookie = req.cookies.get("tg_sid", "")
if _ks_cookie:
_ks_user = await asyncio.to_thread(_tg_resolve_site_user, _ks_cookie)
if _ks_user:
_ks_uid, _ks_uname = _ks_user
_ks_auth = headers.get("Authorization", "") or ""
_ks_key = _ks_auth[7:].strip() if _ks_auth[:7].lower() == "bearer " else ""
if _ks_key.startswith("sk-"):
_ks_key = _ks_key[3:]
if _ks_key:
_ks_owner = await asyncio.to_thread(_tg_key_owner, _ks_key)
# Identity spaces are DIFFERENT: session user_id is new-api users.id,
# token name carries the TG id. The shared namespace is the name:
# tokens.name == users.username == "tg" (same as [GATE] policy).
# Non-tg sessions (root/admin) are not policed here.
if _ks_owner and _ks_uname.startswith("tg") and _ks_uname[2:].isdigit() and _ks_uname != _ks_owner[1]:
LOG.warning("key_share_blocked session=%s owner_name=%s", _ks_uname, _ks_owner[1])
_msg = "Один ключ — один аккаунт. Этот ключ привязан к другому аккаунту."
return web.json_response({"error": {
"message": _msg,
"type": "key_share_blocked", "code": "key_share_blocked", "retryable": False}}, status=403)
_auth = headers.get("Authorization", "") or ""
if _auth[:7].lower() == ("bear" + "er "):
_gk = _auth[7:].strip()
if _gk.startswith("sk-"):
_gk = _gk[3:]
if _gk:
try:
blocked, reason = await gate_check(_gk)
except GateUnavailable:
return web.json_response({"error": {
"message": "Проверка доступа временно недоступна. Повтори запрос позже.",
"type": "temporary_error", "code": "account_policy_unavailable",
"retryable": True}}, status=503)
if blocked:
return web.json_response({"error": {"message": reason, "type": "access_blocked",
"code": "access_blocked", "retryable": False}}, status=403)
if not any(req.path.startswith(s) for s in SKIP):
headers.pop("Accept-Encoding", None)
try:
body = await req.read()
except ConnectionResetError:
LOG.warning("client_disconnect_read")
return web.Response(status=499)
except web.HTTPException as exc:
return error_response(exc.status, b"", req.path, api_key=key_from_headers(req.headers))
requested_model = None
request_object = None
if is_api and body:
try:
request_object = json.loads(body)
if isinstance(request_object, dict) and isinstance(request_object.get("model"), str):
requested_model = request_object["model"]
except (ValueError, UnicodeDecodeError):
pass
# [EFFORT-SCHEMA 2026-10-28] unpinned POST path: an unsupported effort value must be a
# clean 400 (invalid_effort) instead of a provider reroute/502. The check reads the
# parsed body only; body bytes, model and every other field are forwarded untouched.
if (read_effort is not None and req.method == "POST"
and req.path.rstrip("/") in ("/v1/chat/completions", "/v1/responses")
and isinstance(request_object, dict)):
try:
read_effort(request_object)
except InvalidEffort as exc:
return web.json_response({"error": {"message": str(exc),
"type": "invalid_request_error",
"code": "invalid_effort",
"retryable": False}}, status=400)
# /v1/chat/completions POST to explicitly known incompatible families
# (qwen/glm/deepseek/kimi). Requested model, content, order, tools and all
# other fields are preserved; bodies without a developer role are forwarded
# byte-exact (never re-serialized). No retry logic added.
if (req.method == "POST" and req.path == "/v1/chat/completions"
and _dev_role_incompat_model(requested_model)
and _normalize_developer_roles(request_object)):
body = json.dumps(request_object, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
LOG.info("role_compat developer->system model=%s", requested_model)
# [OPUS-SSE 2026-10-23] claude-opus-5-5 JSON->SSE adapter (owner-approved).
# Live evidence: upstream native SSE reports generic model=codai (and
# intermittent account_fallback_failed), while non-stream JSON returns the
# exact claude-opus-5-5 identity. Only the EXACT requested model with
# stream=true is adapted — aliases/other models keep native passthrough and
# their own identity evidence; adapting them would hide substitution.
json_to_sse = False
sse_include_usage = False
if (req.method == "POST" and req.path == "/v1/chat/completions"
and isinstance(request_object, dict)
and request_object.get("model") == "claude-opus-5-5"
and request_object.get("stream") is True):
adapted = dict(request_object)
adapted["stream"] = False
stream_options = adapted.pop("stream_options", None)
if isinstance(stream_options, dict) and stream_options.get("include_usage") is True:
sse_include_usage = True
body = json.dumps(adapted, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
json_to_sse = True
LOG.info("opus_sse_adapter model=%s include_usage=%s", requested_model, sse_include_usage)
# whitespace-only stop-последовательности: «stop_sequences: each stop
# и возвращал 502 -> клиенту прилетало «модель временно недоступна»
# (retryable) вместо честного «плохой параметр». Валидация до апстрима:
# валидные stop проходят без изменений, релей остаётся побайтовым.
if (req.method == "POST" and req.path == "/v1/chat/completions"
and isinstance(request_object, dict)
and isinstance(request_object.get("model"), str)
and request_object["model"].startswith("claude-")
and isinstance(request_object.get("stop"), list)
and any(isinstance(s, str) and not s.strip() for s in request_object["stop"])):
return web.json_response({"error": {
"message": ("Параметр stop содержит последовательность из одних пробельных "
"символов: claude-модели её не принимают («stop_sequences must "
"contain non-whitespace»). Укажи непробельную стоп-"
"последовательность или убери параметр."),
"type": "invalid_request_error", "code": "invalid_stop_sequence",
"retryable": False}}, status=400)
if is_api:
# Inspect error/identity envelopes without changing model, prompt or tools.
headers["Accept-Encoding"] = "identity"
# [RANK-LIMITS 2026-10-17] суточные лимиты по рангам (общий счётчик с ботом)
if is_api and body and req.method == "POST" and req.path.rstrip("/") in _GEN_PATHS:
# [ROLECOMPAT] reuse the single parse above — no second json.loads of body
_rl_model = request_object.get("model") if isinstance(request_object, dict) else None
_rl_auth = headers.get("Authorization", "") or ""
if _rl_auth[:7].lower() == ("bear" + "er "):
_rl_k = _rl_auth[7:].strip()
if _rl_k.startswith("sk-"):
_rl_k = _rl_k[3:]
if _rl_k:
_rl_res = await asyncio.to_thread(_rl_check_sync, _rl_k, _rl_model)
if _rl_res:
_rl_status = _rl_res[0]
_rl_type, _rl_code = (
("temporary_error", "account_policy_unavailable") if _rl_status == 503 else
("access_blocked", "access_blocked") if _rl_status == 403 else
("rate_limit_exceeded", "daily_limit"))
return web.json_response({"error": {"message": _rl_res[1], "type": _rl_type,
"code": _rl_code, "retryable": _rl_status != 403}},
status=_rl_status)
try:
# GET/HEAD/OPTIONS reserve control capacity, except generation paths and
# their subresources, which may also stream on GET.
session_key = SESSION_KEY
if (req.method in ("GET", "HEAD", "OPTIONS")
and not any(req.path.rstrip("/") == path or req.path.startswith(path + "/")
for path in _GEN_PATHS)):
session_key = CONTROL_SESSION_KEY
session = req.app.get(session_key)
if session is None or session.closed: # unstarted app/direct-proxy tests
await _open_upstream_sessions(req.app)
session = req.app[session_key]
registry = req.app.get(PROVIDER_KEY)
pinned = req.headers.get("X-Iishko-Provider")
if is_api and req.method == "POST" and pinned:
if registry is None:
return denial_response((503, "provider_selection_unavailable", "Provider selection is unavailable."))
async def selected_success(upstream):
return await relay_api(req, upstream, requested_model=requested_model,
json_to_sse=json_to_sse, sse_include_usage=sse_include_usage)
async def selected_failure(status, raw, outgoing):
key = key_from_headers(headers)
balance = await asyncio.to_thread(_key_balance_usd, key)
return error_response(status, raw, req.path, headers=outgoing,
user_balance=balance, from_upstream=True, api_key=key)
try:
return await relay_selected(req, session, URL(UPSTREAM + req.raw_path, encoded=True),
headers=headers, body=body, registry=registry,
newapi_db=GATE_NEWAPI_DB, raw_key=key_from_headers(headers).removeprefix("sk-"),
model=requested_model, success=selected_success, failure=selected_failure)
except ProviderError as error:
return denial_response((error.status, error.code, error.message))
async with session.request(req.method, URL(UPSTREAM + req.raw_path, encoded=True),
headers=headers, data=body, allow_redirects=False,
auto_decompress=not is_api,
skip_auto_headers={"Accept-Encoding"} if is_api else None) as upstream:
if is_api:
user_balance = None
if upstream.status >= 400:
auth = headers.get("Authorization", "")
key = auth[7:].strip() if auth[:7].lower() == "bearer " else ""
user_balance = await asyncio.to_thread(_key_balance_usd, key)
# [MODELMETA 2026-10-28] the transparent path skips legacy relay(), so the
# catalogue hook lives here: GET /v1/models only, on this same upstream.
if req.method == "GET" and req.path == "/v1/models":
models_response = await _models_catalogue_response(req, upstream)
if models_response is not None:
return models_response
return await relay_api(req, upstream, user_balance=user_balance,
requested_model=requested_model,
json_to_sse=json_to_sse,
sse_include_usage=sse_include_usage)
return await relay(req, upstream)
except asyncio.TimeoutError:
return error_response(504, b"", req.path, api_key=key_from_headers(req.headers))
except aiohttp.ClientError:
return error_response(503, b"", req.path, api_key=key_from_headers(req.headers))
# ---------- [BRAND] custom logo/favicon replaces new-api defaults (owner, 2026-10-11) ----------
LOGO_PNG = base64.b64decode("iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAIAAADTED8xAAADoUlEQVR42u3YwY3EIBQFQc7OP1pORMDVAro6Av/hlbTa8Unhhp9AAEgASABIAEgASABIAEgASABIAEgASABIAEgASABIAEgASABIAEgASABIAEgASABIAEgASABIAEgASABIAEgASABIAEgASABIAEgASABIAEgASABIAEgASABIAEiXAJg/9t5zzuMDAIDu+gEAIL1+AAAAAAAAqusHAAAAAACgun4AAAAAAACq6wcAAAAAAKC6fgAASK8fAAAAAACA6voBAAAAAACorh8AAAAAAIDq+gEAAAAAAKiuHwAA0usHAAAAAACgun4AAAAAAACq6wcAAAAAAKC6fgAAAAAAAKrrBwCA9PoBAAAAAACorh8AAAAAAIDDfgQAAAAAAACqvwAAAAAAAADV8wEAIH07AEYAAAAAVA8HwA4AAACA6tUAAAAAAKZQPRkAAAAAwBqq9wIAQPpYAAAAAAAAqpcCAAAAAABQPRMAAAAAAIDqjQAAAAAAAFQPBAAAAAAAoHodAACkTwMAAAAAAKB6FwAAAAAAANWjAAAAAAAAqF4EAAAAAABA9RwAAEjfAgAAAAAAQPUQAAAAAAAAqlcAAAAAAABQPQEAAAAAAIDq9wMAQPrjAQAAAAAA8OUAAODLAQDAX24AAAAAAAD41y0AAAAAAADvrgcAANLTAQAAAAAAoLobAAAAAAAAqqMBAAAAAACguhgAAAAAAACqcwEAgPRWAAAAAAAAqA4FAAAAAACA6koAAAAAAACoTgQAAAAAAIDqPgAAID0OAAAAAAAAqssAAAAAAACgOgsAAAAAAACqmwAAAAAAAKA6CAAAAAAAAKprAACA9BQAAAAAAPKPkd0BAB4DAADaj1EeAQAeAwAAwo9RXgAAHgMAAMKPEV8/AOnHsH4AAAAAgORjWD8AAAAAAADh9QMAAAAAAFBdPwAAAAAAANX1AwBAev0AAAAAAABU1w8AAAAAAEB1/QAAAAAAAFTXDwAAAAAAQHX9AACQXj8AAAAAAADV9QMAAAAAAFBdPwAAAAAAANX1AwAAAAAAUF0/AACk1w8AAAAAAEB1/QAAAAAAAFTXDwAAAAAAQHX9AAAAAAAAVNcPAAAAACAlA0AASABIAEgASABIAEgASABIAEgASABIAEgASABIAEgASABIAEgASABIAEgASABIAEgASABIAEgASABIAEgASABIAEgASABIAEgASABIAEgASABIAEgASABIAEgASJsWLkxBvIKnlh8AAAAASUVORK5CYII=")
async def brand_asset(req):
return web.Response(body=LOGO_PNG, content_type="image/png",
headers={"Cache-Control": "no-cache"})
# ---------- [TGLOGIN] Telegram widget-mode login (owner, 2026-10-11) ----------
# back to /#tgAuthResult= ->
# injected JS POSTs it to /api/tg_widget_login.
# Provision: new-api user "tg" via admin API, password kept in skin-local store (0600).
# Login: server-side POST /api/user/login, Set-Cookie forwarded to the browser.
TG_BOT_CONFIG = os.environ.get("GATE_BOT_CONFIG", "/opt/grok-bot/config.json")
TG_ADMIN_TOKEN_FILE = "/root/.secrets/newapi_admin_token"
TG_PROVISION_DB = os.environ.get("GATE_TG_DB", "/opt/grok-web-skin-tg.db")
TG_AUTH_MAX_AGE = 900
TG_SID_SECRET_FILE = os.environ.get("TG_SID_SECRET_FILE", "/root/.secrets/iishko_tg_sid_secret")
_TG_SID_SECRET = None
class AuthStoreError(RuntimeError):
pass
def _load_tg_sid_secret():
"""Read a private descriptor; never replace or silently regenerate existing material."""
flags = getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NONBLOCK", 0)
fd = None
try:
os.makedirs(os.path.dirname(os.path.abspath(TG_SID_SECRET_FILE)), mode=0o700, exist_ok=True)
try:
fd = os.open(TG_SID_SECRET_FILE, os.O_RDONLY | flags)
created = False
except FileNotFoundError:
try:
fd = os.open(TG_SID_SECRET_FILE, os.O_WRONLY | os.O_CREAT | os.O_EXCL | flags, 0o600)
created = True
except FileExistsError:
fd = os.open(TG_SID_SECRET_FILE, os.O_RDONLY | flags)
created = False
metadata = os.fstat(fd)
if not stat.S_ISREG(metadata.st_mode):
raise AuthStoreError("Session secret must be a regular file")
if os.name == "posix" and (metadata.st_uid != os.geteuid() or stat.S_IMODE(metadata.st_mode) != 0o600):
raise AuthStoreError("Session secret requires effective-owner and mode 0600")
if created:
material = secrets.token_bytes(32)
if os.write(fd, material) != len(material):
raise AuthStoreError("Incomplete session secret write")
os.fsync(fd)
else:
material = os.read(fd, 4097)
if not 32 <= len(material) <= 4096:
raise AuthStoreError("Invalid session secret length")
return material
except OSError as exc:
raise AuthStoreError("Session secret storage unavailable") from exc
finally:
if fd is not None:
os.close(fd)
def _tg_sid_secret():
global _TG_SID_SECRET
if _TG_SID_SECRET is None:
_TG_SID_SECRET = _load_tg_sid_secret()
return _TG_SID_SECRET
def sid_tag(secret, sid):
digest = hmac.new(secret, str(sid).encode("utf-8"), hashlib.sha256).digest()
return base64.urlsafe_b64encode(digest).decode("ascii").rstrip("=")
def make_sid(secret, sid):
if not isinstance(sid, str) or not 16 <= len(sid) <= 64 or not all(c.isascii() and (c.isalnum() or c in "-_.") for c in sid):
raise ValueError("Invalid session identifier")
return sid + "." + sid_tag(secret, sid)
def read_sid(secret, cookie_value):
if not isinstance(cookie_value, str) or not 60 <= len(cookie_value) <= 108:
return False, ""
sid, _, tag = cookie_value.rpartition(".")
if len(tag) != 43 or not tag.isascii():
return False, ""
try:
expected = make_sid(secret, sid).rpartition(".")[2]
except ValueError:
return False, ""
return (True, sid) if hmac.compare_digest(expected, tag) else (False, "")
def _tg_resolve_site_user(refresh_cookie):
"""Only signed skin cookies plus a current upstream session establish identity."""
valid, sid = read_sid(_tg_sid_secret(), refresh_cookie)
if not valid:
return None
con = None
try:
con = sqlite3.connect("file:" + GATE_NEWAPI_DB + "?mode=ro", uri=True, timeout=3)
row = con.execute(
"SELECT s.user_id, u.username FROM user_sessions s "
"JOIN users u ON u.id = s.user_id "
"WHERE s.sid=? AND s.status='active' AND s.revoked_at=0 AND s.expires_at>? "
"AND s.user_auth_version=u.auth_version AND u.status=1 AND u.deleted_at IS NULL LIMIT 1",
(sid, int(time.time()))).fetchone()
return row
except sqlite3.Error:
LOG.error("tg_session_lookup_unavailable")
return None
finally:
if con:
con.close()
def _bot_user_row(tg_id):
con = None
try:
con = sqlite3.connect("file:" + GATE_BOT_DB + "?mode=ro", uri=True)
row = con.execute(
"SELECT token_name, api_key, points, vip FROM users WHERE tg_id=?", (tg_id,)).fetchone()
return row
except Exception:
return None
finally:
if con:
con.close()
def _real_client_ip(req):
"""Caddy appends the true peer to X-Forwarded-For; left-side entries are
client-controlled (spoofable). Take the right-most non-loopback hop."""
hops = [h.strip() for h in req.headers.get("X-Forwarded-For", "").split(",") if h.strip()]
for h in reversed(hops):
if h not in ("127.0.0.1", "::1"):
return h
return req.remote or ""
_SHARED_EGRESS_NETS = None
def _shared_egress_ip(ip):
"""[SOFT-IP] Общие выходы: Cloudflare WARP (104.16/13, 172.64/13) + CGNAT (100.64/10).
Толпа незнакомцев на одном IP — клеймо/лок там дают только ложняки (форензика 2026-10-11:
104.28.x-коллизии случайных WARP-юзеров). Директива владельца: «не так сурово с айпишками»."""
global _SHARED_EGRESS_NETS
import ipaddress
if _SHARED_EGRESS_NETS is None:
_SHARED_EGRESS_NETS = [ipaddress.ip_network(x) for x in
("104.16.0.0/12", "172.64.0.0/13", "100.64.0.0/10")] # 104.16/12 = CF+WARP incl. 104.28.x (evidence)
try:
a = ipaddress.ip_address(ip)
except (ValueError, TypeError):
return False
return any(a in n for n in _SHARED_EGRESS_NETS)
def _ip_lock_premium(key):
con = None
try:
con = sqlite3.connect("file:" + GATE_NEWAPI_DB + "?mode=ro", uri=True)
row = con.execute(
"SELECT unlimited_quota FROM tokens WHERE key=? AND deleted_at IS NULL", (key,)).fetchone()
except Exception:
return False
finally:
if con:
con.close()
return bool(row and row[0])
def _key_balance_usd(key):
if not key:
return None
if key.startswith("sk-"):
key = key[3:]
con = None
try:
con = sqlite3.connect("file:" + GATE_NEWAPI_DB + "?mode=ro", uri=True, timeout=3)
row = con.execute(
"SELECT remain_quota FROM tokens WHERE key=? AND deleted_at IS NULL", (key,)).fetchone()
return row[0] / 500_000.0 if row else None
except Exception:
return None
finally:
if con:
con.close()
IP_LOCK_TTL_SEC = 86400 # claim dies without activity from that token for 24h
# Enforcement ON (live traffic 2026-10-11 confirmed healthy: 73 claims / 73
# Emergency off: IP_LOCK_ENFORCE=0 in systemd env + restart.
IP_LOCK_ENFORCE = os.environ.get("IP_LOCK_ENFORCE", "1") == "1"
# [SOFT-IP] Директива владельца 2026-10-11 «не так сурово с айпишками» + «банить только за
# Форензика: каждый подтверждённый ринг = 3-9 токенов на IP, каждый спорный случай = пара.
IP_LOCK_MAX_IDENTITIES = 2
def _ip_lock_eval(ip, tname, xff):
"""Single-threaded claim check + write (conn created/used/closed here).
Claims roll with activity and expire after IP_LOCK_TTL_SEC without any
request from that token — first-claim-wins is never permanent.
Returns ('block', first_token) or ('claim'|'seen', None)."""
now = int(time.time())
con = _tg_store_conn()
con.isolation_level = None # [RACE] явный BEGIN IMMEDIATE: конкурентные запросы одного IP сереются
try:
con.execute("BEGIN IMMEDIATE")
con.execute("DELETE FROM ip_claims WHERE ip=? AND last_seen",
(ip, now - IP_LOCK_TTL_SEC))
names = [r[0] for r in con.execute(
"SELECT DISTINCT token_name FROM ip_claims WHERE ip=?", (ip,))]
if tname not in names and len(names) >= IP_LOCK_MAX_IDENTITIES:
con.execute("INSERT INTO ip_lock_events(ip, token_name, action, detail, ts) "
"VALUES (?,?,?,?,?)",
(ip, tname, "blocked",
"names=" + ",".join(names)[:100] + " xff=" + xff[:120], now))
con.execute("COMMIT")
return ("block", ",".join(names))
cur = con.execute(
"INSERT OR IGNORE INTO ip_claims(ip, token_name, first_seen, last_seen) "
"VALUES (?,?,?,?)", (ip, tname, now, now))
if cur.rowcount:
con.execute("INSERT INTO ip_lock_events(ip, token_name, action, detail, ts) "
"VALUES (?,?,?,?,?)",
(ip, tname, "claim", "xff=" + xff[:120], now))
con.execute("COMMIT")
return ("claim", None)
con.execute("UPDATE ip_claims SET last_seen=? WHERE ip=? AND token_name=?",
(now, ip, tname))
con.execute("COMMIT")
return ("seen", None)
except Exception:
try:
con.execute("ROLLBACK")
except Exception:
pass
raise
finally:
con.close()
async def _ip_lock_check(req, api_key):
try:
ip = _real_client_ip(req)
if not ip or ip.startswith(("127.", "10.", "192.168.")):
return None
if _shared_egress_ip(ip):
return None # [SOFT-IP] общий выход (WARP/CGNAT) — не клеймим и не блокируем
owner = await asyncio.to_thread(_tg_key_owner, api_key)
if not owner:
return None
tname = owner[1]
if await asyncio.to_thread(_ip_lock_premium, api_key):
return None
verdict, first = await asyncio.to_thread(
_ip_lock_eval, ip, tname, req.headers.get("X-Forwarded-For", ""))
if verdict == "claim":
LOG.info("ip_lock_claim ip=%s token=%s", ip, tname)
elif verdict == "block":
LOG.warning("ip_lock_collision ip=%s token=%s first_claim=%s enforce=%s",
ip, tname, first, IP_LOCK_ENFORCE)
if IP_LOCK_ENFORCE:
return web.json_response({"error": {
"message": "Один IP — один аккаунт. С этого адреса уже используется другой ключ.",
"type": "ip_lock_blocked", "code": "ip_lock_blocked", "retryable": False}},
status=403)
except Exception:
LOG.exception("ip_lock_check_failed") # fail-open: auth paths never brick the API
return None
def _tg_key_owner(key):
con = None
try:
con = sqlite3.connect("file:" + GATE_NEWAPI_DB + "?mode=ro", uri=True)
row = con.execute(
"SELECT id, name FROM tokens WHERE key=? AND deleted_at IS NULL "
"AND status=1 LIMIT 1",
(key,)).fetchone()
except Exception:
return None
finally:
if con:
con.close()
if not row:
return None
ident = _owner_identity(row[1] or "")
if not ident:
return None
return (row[0], ident)
_TG_SCHEMA_READY = False
def _tg_store_conn():
global _TG_SCHEMA_READY
con = sqlite3.connect(TG_PROVISION_DB, timeout=2) # [NOWAIT 2510] не держать ответ 10с на блокировке
if _TG_SCHEMA_READY:
return con # [PERF] DDL один раз, а не write-транзакция на каждый API-запрос
con.execute("CREATE TABLE IF NOT EXISTS tg_users("
"tg_id INTEGER PRIMARY KEY, username TEXT, password TEXT, created INTEGER)")
con.execute("CREATE TABLE IF NOT EXISTS tg_share_events("
"user_id INTEGER, key TEXT, day TEXT, ts INTEGER, "
"PRIMARY KEY(user_id, key, day))")
try:
con.execute("ALTER TABLE tg_share_events ADD COLUMN seized INTEGER DEFAULT 0")
except sqlite3.OperationalError as exc:
# Only an already-present column is a benign idempotent migration.
if "duplicate column" not in str(exc).lower():
con.close()
raise
con.execute("CREATE TABLE IF NOT EXISTS ip_claims("
"ip TEXT NOT NULL, token_name TEXT NOT NULL, "
"first_seen INTEGER NOT NULL, last_seen INTEGER NOT NULL, "
"PRIMARY KEY(ip, token_name))")
con.execute("CREATE INDEX IF NOT EXISTS ip_claims_by_ip ON ip_claims(ip)")
con.execute("CREATE TABLE IF NOT EXISTS ip_lock_events("
"ip TEXT, token_name TEXT, action TEXT, detail TEXT, ts INTEGER)")
con.commit()
try:
os.chmod(TG_PROVISION_DB, 0o600)
except OSError:
pass
_TG_SCHEMA_READY = True
return con
def _key_share_seize(user_id, attacker_name, owner_name, key):
if attacker_name == owner_name:
return 0 # same identity: no violation to punish (defensive)
day = time.strftime("%Y-%m-%d", time.gmtime())
con = None
try:
con = _tg_store_conn()
if con.execute("SELECT 1 FROM tg_share_events WHERE user_id=? AND key=? AND day=?",
(user_id, key, day)).fetchone():
return 0 # already penalized today
except Exception:
LOG.exception("key_share_audit_precheck_failed uid=%s", user_id)
return 0
finally:
if con:
con.close()
con = None
seized = 0
try:
con = sqlite3.connect(GATE_NEWAPI_DB, timeout=2) # [NOWAIT 2510]
con.execute("PRAGMA busy_timeout=2000") # [NOWAIT 2510]
# BEGIN IMMEDIATE: hold the write lock across SELECT+UPDATE. Concurrent
# credits (IISHKO promo +$50/day, loyalty awarder) land between them
# otherwise and get destroyed while `seized` records a stale smaller
# number — the audit row is the only restore record.
con.execute("BEGIN IMMEDIATE")
rows = con.execute(
"SELECT id, COALESCE(remain_quota, 0) FROM tokens "
"WHERE name=? AND deleted_at IS NULL AND unlimited_quota=0",
(attacker_name,)).fetchall()
if len(rows) != 1:
con.rollback()
return 0 # fail-closed: ambiguous or missing name (money-write rule:
# exactly one candidate row, cf. grok_bot insert_token_row guard)
token_id, before = rows[0]
if before <= 0:
con.rollback()
return 0
cur = con.execute(
"UPDATE tokens SET remain_quota=0 "
"WHERE id=? AND name=? AND deleted_at IS NULL AND unlimited_quota=0 "
"AND COALESCE(remain_quota, 0) > 0", (token_id, attacker_name))
if cur.rowcount != 1:
con.rollback()
return 0
con.commit()
seized = before
except Exception:
LOG.exception("key_share_seize_failed uid=%s attacker=%s", user_id, attacker_name)
return 0
finally:
if con:
con.close()
con = None
try:
con = _tg_store_conn()
con.execute("INSERT OR REPLACE INTO tg_share_events(user_id, key, day, ts, seized) "
"VALUES(?,?,?,?,?)", (user_id, key, day, int(time.time()), seized))
con.commit()
except Exception:
LOG.exception("key_share_audit_failed_after_seize uid=%s seized=%s", user_id, seized)
finally:
if con:
con.close()
return seized
def _tg_bot_token():
with open(TG_BOT_CONFIG, encoding="utf-8") as fh:
return json.load(fh)["bot_token"]
def _tg_check_hash(data):
received = str(data.get("hash") or "")
if not received:
return False
pairs = {k: v for k, v in data.items() if k != "hash"}
try:
if abs(time.time() - int(pairs.get("auth_date", 0))) > TG_AUTH_MAX_AGE:
return False
except (TypeError, ValueError):
return False
check = "\n".join("{}={}".format(k, pairs[k]) for k in sorted(pairs))
secret = hashlib.sha256(_tg_bot_token().encode()).digest()
digest = hmac.new(secret, check.encode(), hashlib.sha256).hexdigest()
return hmac.compare_digest(digest, received)
async def _newapi_call(session, method, path, bearer=None, json_body=None):
headers = {"Authorization": "Bearer " + bearer} if bearer else {}
async with session.request(method, UPSTREAM + path, headers=headers, json=json_body) as resp:
body = await resp.read()
return resp.status, body, resp.headers
def _json_ok(status, body):
return status == 200 and b'"success":true' in body.replace(b" ", b"")
def _find_user_id(body, username):
"""Parse /api/user/search response: data may be a list or {items:[...]}."""
try:
payload = json.loads(body)
except Exception:
return None
data = payload.get("data") if isinstance(payload, dict) else None
items = []
if isinstance(data, list):
items = data
elif isinstance(data, dict):
for key in ("items", "users", "list", "records"):
if isinstance(data.get(key), list):
items = data[key]
break
for item in items:
if isinstance(item, dict) and item.get("username") == username:
return item.get("id")
return None
TG_CALLBACK_HTML = b"""
IISHKO GATEWAY
Telegram login...
"""
def _tg_link_conn():
con = sqlite3.connect(TG_PROVISION_DB, timeout=2) # [NOWAIT 2510] не держать ответ 10с на блокировке
con.execute("CREATE TABLE IF NOT EXISTS tg_links("
"tg_id INTEGER PRIMARY KEY, site_username TEXT, token_name TEXT, "
"points INTEGER DEFAULT 0, vip INTEGER DEFAULT 0, linked_at INTEGER)")
con.commit()
try:
os.chmod(TG_PROVISION_DB, 0o600)
except OSError:
pass
return con
def _tg_link_upsert(tg_id, site_username):
"""Single-call sqlite op (run via asyncio.to_thread). Fail-open: link is a
convenience, never a login blocker."""
con = None
try:
con = _tg_link_conn()
con.execute(
"INSERT OR REPLACE INTO tg_links(tg_id, site_username, token_name, linked_at) "
"VALUES(?, ?, COALESCE((SELECT token_name FROM tg_links WHERE tg_id=?), ''), ?)",
(tg_id, site_username, tg_id, int(time.time())))
con.commit()
except Exception:
LOG.warning("tg_link_upsert_failed tg_id=%s", tg_id)
finally:
if con:
con.close()
def _tg_link_by_username(site_username):
con = None
try:
con = sqlite3.connect("file:" + TG_PROVISION_DB + "?mode=ro", uri=True, timeout=3)
return con.execute(
"SELECT tg_id, token_name, points, vip FROM tg_links WHERE site_username=?",
(site_username,)).fetchone()
except Exception:
return None
finally:
if con:
con.close()
def _tg_link_by_tgid(tg_id):
con = None
try:
con = _tg_link_conn()
return con.execute(
"SELECT tg_id, token_name, points, vip FROM tg_links WHERE tg_id=?",
(tg_id,)).fetchone()
except Exception:
return None
finally:
if con:
con.close()
def _tg_wallet_name_owned(name, tg_id):
return type(tg_id) is int and account_uid(name) == tg_id
def _tg_credit_snapshot(user_id, username, tg_id=None):
out = {
"wallet": {"status": "unavailable", "source": "bot_token",
"label": "API-кредит основного ключа", "token_name": None,
"remain_quota": None, "balance_usd": None, "unlimited": None,
"token_status": None},
"account_quota": {"status": "unavailable",
"label": "Квота аккаунта сайта — отдельно",
"quota": None, "quota_usd": None},
}
try:
with closing(sqlite3.connect("file:" + GATE_NEWAPI_DB + "?mode=ro",
uri=True, timeout=3)) as gateway:
site = gateway.execute(
"SELECT username, quota FROM users WHERE id=? AND status=1 "
"AND deleted_at IS NULL", (user_id,)).fetchone()
if not site or site[0] != username:
return out
if type(site[1]) is int:
out["account_quota"].update(status="available", quota=site[1],
quota_usd=site[1] / 500_000.0)
if type(tg_id) is not int or tg_id <= 0 or username != "tg%d" % tg_id:
return out
with closing(sqlite3.connect("file:" + GATE_BOT_DB + "?mode=ro",
uri=True, timeout=3)) as bot_db:
profile = bot_db.execute(
"SELECT token_name FROM users WHERE tg_id=?", (tg_id,)).fetchone()
if not profile:
return out
name = profile[0]
if name and not _tg_wallet_name_owned(name, tg_id):
return out
names = [name] if name else []
fallback = "tg%d" % tg_id
if fallback not in names:
names.append(fallback)
for token_name in names:
token = gateway.execute(
"SELECT remain_quota, unlimited_quota, status FROM tokens "
"WHERE name=? AND status IN (1,2) AND deleted_at IS NULL "
"ORDER BY remain_quota DESC LIMIT 1", (token_name,)).fetchone()
if not token:
continue
if type(token[0]) is not int or token[1] not in (0, 1):
return out
unlimited = bool(token[1])
out["wallet"].update(
status="unlimited" if unlimited else "available",
token_name=token_name, remain_quota=token[0],
balance_usd=None if unlimited else token[0] / 500_000.0,
unlimited=unlimited, token_status=token[2])
break
except (sqlite3.Error, TypeError, ValueError, OverflowError):
LOG.warning("tg_credit_lookup_unavailable")
return out
async def tg_link_self(req):
"""GET /api/user/self/tg_account (with site session cookie) -> bot identity."""
refresh = req.cookies.get("tg_sid", "")
row = await asyncio.to_thread(_tg_resolve_site_user, refresh)
if not row:
return web.json_response({"success": False, "error": "no_session"}, status=401,
headers={"Cache-Control": "no-store"})
user_id, username = row
link = await asyncio.to_thread(_tg_link_by_username, username)
if not link:
out = {"success": False, "linked": False}
out.update(await asyncio.to_thread(_tg_credit_snapshot, user_id, username))
return web.json_response(out, headers={"Cache-Control": "no-store"})
tg_id, token_name, points, vip = link
bot_row = await asyncio.to_thread(_bot_user_row, tg_id)
out = {"success": True, "linked": True, "tg_id": tg_id,
"token_name": token_name or (bot_row[0] if bot_row else None),
"points": points if points is not None else (bot_row[2] if bot_row else 0),
"vip": vip if vip is not None else (bot_row[3] if bot_row else 0)}
if token_name and not out.get("token_name", ""):
out["token_name"] = token_name
out.update(await asyncio.to_thread(_tg_credit_snapshot, user_id, username, tg_id))
return web.json_response(out, headers={"Cache-Control": "no-store"})
async def _public_account_lookup(req):
response = await tg_link_self(req)
return json.loads(response.body) if response.status == 200 else None
async def tg_callback(req):
"""Own callback page: proves the Telegram return leg in the journal,
no SPA router / cache ambiguity. Fragment never reaches the server;
the landing log line itself is the evidence."""
LOG.info("tg_callback_landed qs=%.80s", req.query_string)
resp = web.Response(body=TG_CALLBACK_HTML, content_type="text/html",
headers={"Cache-Control": "no-store"})
_site_user = await asyncio.to_thread(
_tg_resolve_site_user,
req.cookies.get("tg_sid", ""))
if _site_user:
_tg_id = _site_user[1][2:] if str(_site_user[1]).startswith("tg") else None
if _tg_id and _tg_id.isdigit():
_row = await asyncio.to_thread(_tg_link_by_tgid, int(_tg_id))
if _row:
resp.set_cookie("tg_linked", "1", max_age=31536000,
httponly=False, samesite="Lax")
resp.set_cookie("tg_token", _row[1] or "", max_age=31536000,
httponly=True, samesite="Lax")
resp.set_cookie("tg_points", str(_row[2] or 0), max_age=31536000,
httponly=False, samesite="Lax")
resp.set_cookie("tg_vip", str(_row[3] or 0), max_age=31536000,
httponly=False, samesite="Lax")
return resp
def _tg_normalize(data):
"""Normalize Telegram return shapes: dict | JSON string | base64 string |
[ [k,v], ... ] pairs | [dict]. Returns dict when recoverable."""
for _ in range(4):
if isinstance(data, dict):
return data
if isinstance(data, list):
if data and isinstance(data[0], dict):
data = data[0]
continue
try:
data = {str(k): v for k, v in data}
except Exception:
return data
continue
if isinstance(data, str):
try:
data = json.loads(data)
continue
except Exception:
pass
try:
std = data.replace("-", "+").replace("_", "/")
std += "=" * (-len(std) % 4)
data = json.loads(base64.b64decode(std).decode("utf-8"))
continue
except Exception:
return data
return data
return data
async def tg_login(req):
raw_body = await req.text()
try:
data = json.loads(raw_body)
except Exception:
LOG.warning("tg_login_bad_json raw=%.120s", raw_body)
return web.json_response({"success": False, "error": "bad_json"}, status=400)
# tolerate real-world Telegram return shapes via _tg_normalize
data = _tg_normalize(data)
if not isinstance(data, dict):
LOG.warning("tg_login_bad_payload type=%s raw=%.120s", type(data).__name__, raw_body)
return web.json_response({"success": False, "error": "bad_payload"}, status=400)
try:
verified = _tg_check_hash(dict(data))
except Exception:
LOG.exception("tg_login_verify_error")
return web.json_response({"success": False, "error": "verify_error"}, status=500)
if not verified:
return web.json_response({"success": False, "error": "invalid_hash"}, status=403)
try:
tg_id = int(data.get("id"))
except (TypeError, ValueError):
return web.json_response({"success": False, "error": "bad_id"}, status=400)
username = "tg{}".format(tg_id)
display = " ".join(str(data.get(k) or "") for k in ("first_name", "last_name")).strip()[:60]
display = display or str(data.get("username") or "")[:40] or username
session = req.app[CONTROL_SESSION_KEY]
try:
with open(TG_ADMIN_TOKEN_FILE, encoding="utf-8") as fh:
bearer = fh.read().strip()
except OSError:
LOG.error("tg_login_admin_token_unreadable")
return web.json_response({"success": False, "error": "provision_unavailable"}, status=500)
try:
con = _tg_store_conn()
try:
row = con.execute("SELECT password FROM tg_users WHERE tg_id=?", (tg_id,)).fetchone()
password = row[0] if row else None
if password is None:
password = secrets.token_urlsafe(24)
status, body, _ = await _newapi_call(
session, "POST", "/api/user/", bearer,
{"username": username, "password": password, "display_name": display})
if not _json_ok(status, body):
# Create failed (user likely exists but store lost the password,
# e.g. crash during first login). Recovery in rc.40: fetch the FULL
# user object, resend it with a new password (admin UpdateUser by Id
# persists the whole struct - partial bodies are rejected).
_, search_body, _ = await _newapi_call(
session, "GET", "/api/user/search?keyword=" + username, bearer)
uid = _find_user_id(search_body, username)
if uid is None:
LOG.warning("tg_login_provision_failed status=%s", status)
return web.json_response({"success": False, "error": "provision_failed"}, status=502)
_, user_body, _ = await _newapi_call(
session, "GET", "/api/user/" + str(uid), bearer)
try:
user_obj = json.loads(user_body).get("data")
except Exception:
user_obj = None
if not isinstance(user_obj, dict) or "id" not in user_obj:
LOG.warning("tg_login_recovery_fetch_failed uid=%s", uid)
return web.json_response({"success": False, "error": "provision_failed"}, status=502)
user_obj["password"] = password
status, body, _ = await _newapi_call(
session, "PUT", "/api/user/", bearer, user_obj)
if not _json_ok(status, body):
LOG.warning("tg_login_recovery_put_failed uid=%s status=%s", uid, status)
return web.json_response({"success": False, "error": "provision_failed"}, status=502)
LOG.info("tg_login_recovered uid=%s", uid)
con.execute("INSERT OR REPLACE INTO tg_users(tg_id, username, password, created)"
" VALUES(?,?,?,?)", (tg_id, username, password, int(time.time())))
con.commit()
finally:
con.close()
await asyncio.to_thread(_tg_link_upsert, tg_id, username)
status, body, hdrs = await _newapi_call(
session, "POST", "/api/user/login", None,
{"username": username, "password": password})
except Exception:
LOG.exception("tg_login_backend_error")
return web.json_response({"success": False, "error": "backend_error"}, status=502)
if not _json_ok(status, body):
LOG.warning("tg_login_login_failed status=%s", status)
return web.json_response({"success": False, "error": "login_failed"}, status=502)
try:
bundle = json.loads(body)
account = bundle.get("data") if isinstance(bundle, dict) else None
session_data = account.get("session") if isinstance(account, dict) else None
if not isinstance(session_data, dict):
raise ValueError("Missing session")
expires = session_data.get("expires_at")
if type(expires) is not int or expires <= int(time.time()):
raise ValueError("Invalid session expiry")
signed_sid = make_sid(_tg_sid_secret(), session_data.get("sid"))
max_age = min(2592000, expires - int(time.time()))
if max_age <= 0:
raise ValueError("Expired session")
except (ValueError, TypeError, AuthStoreError):
LOG.error("tg_login_invalid_session_bundle")
return web.json_response({"success": False, "error": "session_unavailable"}, status=502)
resp = web.json_response({"success": True, "redirect": "/pricing"}, headers={"Cache-Control": "no-store"})
for cookie in hdrs.getall("Set-Cookie", []):
resp.headers.add("Set-Cookie", cookie)
resp.set_cookie("tg_sid", signed_sid, max_age=max_age, path="/",
httponly=True, secure=True, samesite="Lax")
LOG.info("tg_login_ok tg_id=%s user=%s", tg_id, username)
return resp
def create_app():
app = web.Application(client_max_size=MAX_BODY)
app[PROVIDER_KEY] = ProviderRegistry.from_file(os.environ.get("IISHKO_PROVIDERS_FILE", ""))
install_gateway_features(
app, newapi_db=GATE_NEWAPI_DB, bot_db=GATE_BOT_DB, limits=RL_TOTAL,
entitlement_reader=gateway_commerce.entitlements,
model_access=lambda uid, model, token_models, default_allowed: commerce_access.allowed(
GATE_BOT_DB, uid, model, token_models, default_allowed))
async def _open_session(app):
try:
await asyncio.to_thread(_tg_sid_secret)
await _open_upstream_sessions(app)
await asyncio.to_thread(gate_boot_selfcheck)
except BaseException:
# on_cleanup is not guaranteed after a failed on_startup callback.
await _close_upstream_sessions(app)
raise
app.on_startup.append(_open_session)
app.on_cleanup.append(_close_upstream_sessions)
app.router.add_get("/logo.png", brand_asset)
app.router.add_get("/favicon.ico", brand_asset)
app.router.add_post("/api/tg_widget_login", tg_login)
app.router.add_get("/tg-callback", tg_callback)
app.router.add_get("/api/user/self/tg_account", tg_link_self)
register_public_routes(app, head_inject=INJECT, account_lookup=_public_account_lookup)
LOG.info("public_site_routes_mounted")
app.router.add_route("*", "/{tail:.*}", proxy)
return app
if __name__ == "__main__":
# [EMFILE-FIX 2410] keepalive_timeout=15 = коннектор апстрима; journal: OSError 24 (61×/сутки)
# при soft-limit 1024 и 500+ idle keep-alive от Caddy. Плюс systemd drop-in LimitNOFILE=65535.
web.run_app(create_app(), host=os.environ.get("IISHKO_GATEWAY_HOST", "127.0.0.1"),
port=int(os.environ.get("IISHKO_GATEWAY_PORT", "48001")), access_log=None, shutdown_timeout=15,
keepalive_timeout=15)