# -*- coding: utf-8 -*- import asyncio from contextlib import closing from pathlib import Path import hashlib import json import math import os import re import secrets import sqlite3 import sys import time os.chdir(os.path.dirname(os.path.abspath(__file__))) sys.path[:0] = os.environ.get("IISHKO_RUNTIME_PATHS", os.environ.get("IISHKO_APP_ROOT", str(Path(__file__).resolve().parent.parent))).split(os.pathsep) import key_issue_guard from account_limits import account_uid, account_token_names import account_balances from runtime_config import bot_db_path, econ_state_path, gateway_db_path _so = sys.stdout sys.stdout = sys.stderr try: import grok_bot as g finally: sys.stdout = _so BOT_DB = bot_db_path(g.CFG["bot_db"]) # Same value the imported bot resolved, so both sides share one gateway database. GW_DB = g.CFG.get('newapi_db') or gateway_db_path() Q = g.QUOTA_PER_UNIT class KeyErrorSafe(ValueError): pass def _fail(message): raise KeyErrorSafe(message) def _connect(): con = sqlite3.connect(Path(GW_DB).resolve().as_uri() + '?mode=rw', uri=True, timeout=20, isolation_level=None) con.row_factory = sqlite3.Row con.execute('PRAGMA busy_timeout=20000') try: con.execute('ATTACH DATABASE ? AS bot', (Path(BOT_DB).resolve().as_uri() + '?mode=rw',)) con.execute('CREATE TABLE IF NOT EXISTS wa_key_operations (' 'uid INTEGER NOT NULL, request_id TEXT NOT NULL,digest TEXT NOT NULL,' 'result TEXT NOT NULL,PRIMARY KEY(uid,request_id))') con.execute('CREATE TABLE IF NOT EXISTS wa_key_locks (' 'tid INTEGER PRIMARY KEY,uid INTEGER NOT NULL,name TEXT NOT NULL)') return con except Exception: con.close() raise def _user(con, uid): if type(uid) is not int or not 0 < uid <= 9223372036854775807: _fail('Некорректный пользователь') row = con.execute('SELECT * FROM bot.users WHERE tg_id=?', (uid,)).fetchone() if not row: _fail('Сначала открой бота и зарегистрируйся') u = dict(row) if u['banned'] or u['api_blocked']: _fail('Доступ к API заблокирован. Поддержка: @your-handle') if u.get('token_name') and account_uid(u['token_name']) != uid: _fail('Ключ не принадлежит аккаунту. Нужна проверка поддержки') if u.get('api_key'): if not isinstance(u['api_key'], str): _fail('Не удалось подтвердить ключ аккаунта') owners = con.execute('SELECT name FROM tokens WHERE key=?', (u['api_key'].removeprefix('sk-'),)).fetchall() if any(account_uid(r['name']) != uid for r in owners): _fail('Ключ не принадлежит аккаунту. Нужна проверка поддержки') return u def _name(uid, n, promo=False): if type(n) is not int or n < (-1 if promo else 0) or n > 1000000: _fail('Некорректный номер ключа') return 'pm%d' % uid if n == -1 else ('tg%d' % uid if n == 0 else 'tg%d-k%d' % (uid, n)) def _row(con, uid, n, u, required=True): name = _name(uid, n, promo=True) rows = con.execute('SELECT * FROM tokens WHERE name=? AND deleted_at IS NULL ORDER BY id', (name,)).fetchall() if n == 0 and u.get('api_key'): raw = u['api_key'].removeprefix('sk-') canonical = [r for r in rows if r['key'] == raw] if len(canonical) == 1: return canonical[0] if len(rows) > 1: _fail('Найдены дубли ключа. Нужна проверка поддержки; баланс сохранён') if not rows and required: _fail('Ключ не найден') return rows[0] if rows else None def _rows(con, uid, u): out = [] for name in account_token_names(con, uid): match = re.fullmatch(r'tg%d-k([1-9][0-9]*)' % uid, name) if name == 'tg%d' % uid or match: n = int(match[1]) if match else 0 out.append((n, _row(con, uid, n, u))) return sorted(out, key=lambda item: item[0]) def _digest(action, params): return hashlib.sha256(json.dumps([action, params], sort_keys=True, allow_nan=False).encode()).hexdigest() def _request(request_id): if not isinstance(request_id, str) or not re.fullmatch(r'[A-Za-z0-9_-]{12,96}', request_id): _fail('Нужен уникальный идентификатор операции. Обнови Mini App') def _receipt(con, uid, request_id, digest): row = con.execute('SELECT digest,result FROM wa_key_operations WHERE uid=? AND request_id=?', (uid, request_id)).fetchone() if not row: return None if row['digest'] != digest: _fail('Этот номер уже использован другой операцией') result = json.loads(row['result']) if result.get('name') and account_uid(result['name']) != uid: _fail('Не удалось подтвердить владельца операции') if result.get('token_id') is not None: tid = result['token_id'] if type(tid) is not int or tid <= 0: _fail('Не удалось подтвердить ключ операции') token = con.execute('SELECT key,name FROM tokens WHERE id=? AND deleted_at IS NULL', (tid,)).fetchone() if token: if account_uid(token['name']) != uid or result.get('name', token['name']) != token['name']: _fail('Не удалось подтвердить владельца операции') result['key'] = 'sk-' + token['key'] return result async def _subscribed(uid): bot = g.Bot(token=g.CFG['bot_token']) try: return await g.is_subscribed(bot, uid) finally: await bot.session.close() def _owned_history(con, uid): terms, args = [], [] for prefix in ('tg', 'pm', 'sol'): name = prefix + str(uid) terms.extend(('name=?', 'name GLOB ?')) args.extend((name, name + '-k[0-9]*')) rows = con.execute('SELECT * FROM tokens WHERE ' + ' OR '.join(terms), args).fetchall() return [row for row in rows if account_uid(row['name']) == uid] def _create(con, uid, u, now, issue_device=None): if not isinstance(issue_device, str) or not re.fullmatch(r'[a-f0-9]{64}', issue_device): _fail('Обнови Mini App и разреши хранение данных для выдачи ключа') main = _row(con, uid, 0, u, required=False) rows = _rows(con, uid, u) if not main: wait = int(u.get('created') or 0) + g.KEY_WAIT_SEC if wait > now and int(u.get('unlim_until') or 0) <= now: _fail('Основной ключ доступен через %s после регистрации' % ('24 часа' if g.KEY_WAIT_SEC == 86400 else '%d ч' % (g.KEY_WAIT_SEC // 3600))) if len(rows) >= g.MK_CAP.get(g.badge_of(uid), 2): _fail('Достигнут лимит ключей ранга (включая основной)') history = _owned_history(con, uid) recent = max((int(row['created_time'] or 0) for row in history), default=0) if recent and now - int(recent) < 45: _fail('Подожди минуту перед созданием следующего ключа') # [device issuance] Installation-wide cap on distinct accounts; checked inside the same # transaction and before allocation, so NAT/account gates stay untouched. try: key_issue_guard.check_device(con, uid, issue_device, now) except ValueError as error: _fail(str(error)) if main: n = 1 occupied = {item[0] for item in rows} while n in occupied: n += 1 quota, unlimited = 0, 0 else: n = 0 beneficiary_table = con.execute( "SELECT 1 FROM bot.sqlite_master WHERE type='table' AND name='wa_issue_beneficiaries'" ).fetchone() prior_grant = bool(beneficiary_table and con.execute( 'SELECT 1 FROM bot.wa_issue_beneficiaries WHERE uid=? LIMIT 1', (uid,)).fetchone()) prior_create = any(json.loads(row[0]).get('n') == 0 for row in con.execute( 'SELECT result FROM wa_key_operations WHERE uid=?', (uid,))) first = (not history and not u.get('api_key') and not u.get('token_name') and not prior_grant and not prior_create and not u.get('key_locked') and not u.get('chat_key_locked')) # All account families/history share one first issuance; never a new bucket. if first: try: key_issue_guard.bind_beneficiary(con, uid, issue_device, now) except ValueError as error: _fail(str(error)) quota = g.first_mint_bonus(uid, g.CFG['user_quota']) if first else 0 unlimited = int(bool(g.CFG['unlimited'])) if first else 0 name, raw = _name(uid, n), secrets.token_hex(24) previous_main = main status, expires = 1, -1 if previous_main is not None: status = int(previous_main['status']) expires = -1 if previous_main['expired_time'] is None else int(previous_main['expired_time']) if u.get('key_locked') or u.get('chat_key_locked'): status = 2 cursor = con.execute('INSERT INTO tokens (user_id,key,name,status,created_time,accessed_time,expired_time,' 'remain_quota,unlimited_quota,model_limits_enabled,model_limits,allow_ips,used_quota,"group",deleted_at) ' 'VALUES (?,?,?,?,?,?,?, ?,?,1,?,\'\',0,?,NULL)', (g.newapi_user_id(GW_DB), raw, name, status, now, now, expires, quota, unlimited, ','.join(g.rank_models(uid)), 't%d' % g.tier_of(uid))) if status == 2 and (u.get('key_locked') or u.get('chat_key_locked') or previous_main is not None and con.execute( 'SELECT 1 FROM wa_key_locks WHERE tid=? AND uid=? AND name=?', (previous_main['id'], uid, previous_main['name'])).fetchone()): con.execute('INSERT INTO wa_key_locks VALUES (?,?,?)', (cursor.lastrowid, uid, name)) if n == 0: con.execute('UPDATE bot.users SET token_name=?,api_key=? WHERE tg_id=?', (name, 'sk-' + raw, uid)) # [device issuance] Same transaction as the token insert: a rollback unbinds the name. try: key_issue_guard.record_device(con, uid, issue_device, name, now) except ValueError as error: _fail(str(error)) return {'ok': True, 'n': n, 'name': name, 'key': 'sk-' + raw, 'token_id': cursor.lastrowid} def _move(con, src, dst, amount=None): if int(src['unlimited_quota'] or 0) or int(dst['unlimited_quota'] or 0): _fail('Переводы безлимитных ключей не поддерживаются') available = max(0, int(src['remain_quota'] or 0)) amount = available if amount is None else amount if amount < 0 or amount > available: _fail('Недостаточно API-кредита') uid = account_uid(src['name']) if uid is None or account_uid(dst['name']) != uid: _fail('Ключ не принадлежит аккаунту. Баланс сохранён') user = _user(con, uid) if user.get('cap_paused') or user.get('key_locked'): _fail('Доступ к API приостановлен для аккаунта; баланс сохранён') now = int(time.time()) for row in (src, dst): status = int(row['status'] or 0) expired = row['expired_time'] is not None and 0 <= int(row['expired_time']) <= now if status not in (1, 4) or expired or row['deleted_at'] is not None: _fail('Ключ приостановлен или истёк; перевод недоступен, баланс сохранён') if status == 4: # Exhaustion is not an admin pause. Preserve even legacy lock evidence. locked = con.execute('SELECT 1 FROM wa_key_locks WHERE tid=?', (row['id'],)).fetchone() has_pauses = con.execute( "SELECT 1 FROM sqlite_master WHERE type='table' AND name='wa_daily_cap_pauses'" ).fetchone() paused = has_pauses and con.execute( 'SELECT 1 FROM wa_daily_cap_pauses WHERE tid=?', (row['id'],)).fetchone() if locked or paused: _fail('Не удалось подтвердить причину ограничения ключа; баланс сохранён') if amount: for row, sign in ((src, '-'), (dst, '+')): changed = con.execute( 'UPDATE tokens SET remain_quota=COALESCE(remain_quota,0)' + sign + '?,' 'status=CASE WHEN status=4 AND COALESCE(remain_quota,0)' + sign + '?>0 ' 'THEN 1 ELSE status END WHERE id=? AND deleted_at IS NULL AND status IN (1,4)', (amount, amount, row['id'])) if changed.rowcount != 1: _fail('Состояние ключа изменилось; баланс сохранён') return amount def mutate(action, uid, request_id, issue_device=None, **params): _request(request_id) digest = _digest(action, params) # External check happens outside the write transaction and follows existing bot policy. if action == 'create': with closing(_connect()) as con: _user(con, uid) previous = _receipt(con, uid, request_id, digest) if previous: return previous if not asyncio.run(_subscribed(uid)): _fail('Подпишись на канал бота, затем повтори получение ключа в Mini App') # [FIX-2410] чтение econ_cap_state.json ДО BEGIN IMMEDIATE — не держим write-lock ради файлового I/O pause_state = _read_pause_state() if action == 'lock' else None with closing(_connect()) as con: try: con.execute('BEGIN IMMEDIATE') u = _user(con, uid) previous = _receipt(con, uid, request_id, digest) if previous: con.rollback() return previous now = int(time.time()) if action == 'create': result = _create(con, uid, u, now, issue_device=issue_device) elif action == 'return_all': if params: _fail('Возврат всех остатков не принимает параметры ключа или суммы') main = _row(con, uid, 0, u) trusted, ambiguous = account_balances.owned_rows(con, uid, u) sources = [row for row in trusted if '-k' in row['name'] and not row['name'].startswith('pm')] trusted_ids = {row['id'] for row in trusted} if ambiguous or main['id'] not in trusted_ids or any(row['id'] not in trusted_ids for row in sources): _fail('Нельзя подтвердить владельца всех ключей. Баланс сохранён') moved = sum(_move(con, row, main) for row in sources) con.execute('INSERT INTO bot.econ_tx(src,dst,units,type,ts) VALUES(?,?,?,?,?)', (uid, uid, moved, 'web:key_return_all', now)) result = {'ok': True, 'moved_usd': moved / Q, 'returned_keys': len(sources), **account_balances.snapshot(con, uid, u, Q)} else: n = params.get('n') _name(uid, n) row = _row(con, uid, n, u) if action == 'lock': if _daily_pause_info(con, row, u, state=pause_state).get('daily_paused'): _fail('Достигнут дневной лимит API. Доступ возобновится после 00:00 МСК при следующей проверке; баланс сохранён') current = int(row['status']) own_lock = con.execute('SELECT 1 FROM wa_key_locks WHERE tid=? AND uid=? AND name=?', (row['id'], uid, row['name'])).fetchone() if current == 1: status = 2 con.execute('INSERT OR REPLACE INTO wa_key_locks VALUES (?,?,?)', (row['id'], uid, row['name'])) elif current == 2 and (own_lock or n == 0 and u.get('key_locked')): status = 1 con.execute('DELETE FROM wa_key_locks WHERE tid=?', (row['id'],)) else: _fail('Ключ ограничен администратором или истёк; самостоятельная разблокировка недоступна') con.execute('UPDATE tokens SET status=? WHERE id=?', (status, row['id'])) if n == 0: con.execute('UPDATE bot.users SET key_locked=? WHERE tg_id=?', (int(status == 2), uid)) result = {'ok': True, 'status': status} elif action in ('transfer', 'del'): if n < 1: _fail('Эта операция доступна только для дополнительного ключа') main = _row(con, uid, 0, u) if action == 'del': moved = _move(con, row, main) con.execute('UPDATE tokens SET status=2,deleted_at=? WHERE id=?', (now, row['id'])) else: usd, direction = params.get('usd'), params.get('direction') if type(usd) not in (int, float) or not math.isfinite(usd) or direction not in ('to', 'from'): _fail('Проверь сумму и направление перевода') if not (1 <= usd <= 1000 or usd == 0 and direction == 'from'): _fail('Сумма перевода: от 1 до 1000; возврат всего остатка: 0') units = int(round(usd * Q)) if usd else None moved = _move(con, row if direction == 'from' else main, main if direction == 'from' else row, units) con.execute('INSERT INTO bot.econ_tx(src,dst,units,type,ts) VALUES (?,?,?,?,?)', (uid, uid, moved, 'web:key_' + action, now)) result = {'ok': True, 'moved_usd': moved / Q} else: _fail('Неизвестная операция') receipt = {k: v for k, v in result.items() if k != 'key'} con.execute('INSERT INTO wa_key_operations VALUES (?,?,?,?)', (uid, request_id, digest, json.dumps(receipt))) con.commit() return result except BaseException: con.rollback() raise def cmd_replay(uid, action, request_id, **params): _request(request_id) with closing(_connect()) as con: _user(con, uid) result = _receipt(con, uid, request_id, _digest(action, params)) return result if result is not None else {'ok': True, 'found': False} def cmd_reveal(uid, n): with closing(_connect()) as con: u = _user(con, uid) r = _row(con, uid, n, u) return {'ok': True, 'key': 'sk-' + r['key'], 'name': r['name']} def _state_path(state_path=None): return state_path or econ_state_path() def _read_pause_state(state_path=None): # [FIX-2410] чтение JSON-состояния вынесено из BEGIN IMMEDIATE-транзакции try: with open(_state_path(state_path), encoding='utf-8') as fh: state = json.load(fh) return state if isinstance(state, dict) else {} except (OSError, ValueError): return {} def _daily_pause_info(con, row, user, state=None, state_path=None): if int(row['status']) != 2 or user.get('key_locked'): return {} try: durable = con.execute( "SELECT 1 FROM sqlite_master WHERE type='table' AND name='wa_daily_cap_pauses'" ).fetchone() if durable: record = con.execute( 'SELECT tid,name,ts,prev_status FROM wa_daily_cap_pauses WHERE tid=? AND name=?', (row['id'], row['name'])).fetchone() pause = dict(record) if record else None else: # [FIX-2410] файл читается вызывающей стороной до BEGIN IMMEDIATE; ленивое чтение — только fallback if state is None: state = _read_pause_state(state_path) pause = state.get('paused', {}).get(row['name']) if state and state.get('v', 2) == 2 else None if not isinstance(pause, dict) or pause.get('tid') != row['id']: return {} if pause.get('flag_only'): return {} if pause.get('prev_status') != 1: return {} stamp = int(pause['ts']) if stamp <= 0: return {} retry_at = stamp - ((stamp + 3 * 3600) % 86400) + 86400 return {'daily_paused': True, 'retry_at': retry_at, 'status_reason': 'Дневной лимит API; баланс сохранён'} except (OSError, ValueError, TypeError, KeyError, AttributeError, sqlite3.Error): # Unknown or invalid ownership evidence remains unclassified. return {} def cmd_list(uid): with closing(_connect()) as con: u = _user(con, uid) rows = _rows(con, uid, u) # Recover a lost bot pointer from an unambiguous existing main, never mint a duplicate. main = next((r for n, r in rows if n == 0), None) if main is not None and (u.get('api_key') != 'sk-' + main['key'] or u.get('token_name') != main['name']): con.execute('UPDATE bot.users SET token_name=?,api_key=? WHERE tg_id=?', (main['name'], 'sk-' + main['key'], uid)) promo = _row(con, uid, -1, u, required=False) output = [] # [FIX-2410] состояние читаем один раз до цикла (не в каждой строке, не внутри write-контекста) pause_state = _read_pause_state() for n, r in rows + ([(-1, promo)] if promo else []): raw = r['key'] output.append({'n': n, 'main': n == 0, 'promo': n == -1, 'name': r['name'], 'masked': raw[:6] + '…' + raw[-4:], 'status': r['status'], 'remain_usd': (r['remain_quota'] or 0) / Q, 'used_usd': (r['used_quota'] or 0) / Q, 'unlimited': r['unlimited_quota'], 'models_n': len((r['model_limits'] or '').split(',')), 'group': r['group'], 'created': r['created_time']}) output[-1].update(_daily_pause_info(con, r, u, state=pause_state)) cap = g.MK_CAP.get(g.badge_of(uid), 2) now = time.time() wait_until = int(u.get('created') or 0) + g.KEY_WAIT_SEC if not main and int(u.get('unlim_until') or 0) <= now else 0 can_create = len(rows) < cap and wait_until <= now return {'ok': True, 'uid': uid, 'keys': output, 'cap': cap, 'has_main': main is not None, 'can_create': can_create, 'wait_until': wait_until, 'wait_seconds': g.KEY_WAIT_SEC, 'server_now': now, 'create_reason': ('Ключ доступен через %s после регистрации' % ('24 часа' if g.KEY_WAIT_SEC == 86400 else '%d ч' % (g.KEY_WAIT_SEC // 3600))) if wait_until > now else 'Лимит ключей ранга', 'extras': sum(n > 0 for n, _ in rows), **account_balances.snapshot(con, uid, u, Q)} def dispatch(req): try: if not isinstance(req, dict): _fail('Ожидается JSON-объект') req = dict(req) cmd = req.pop('cmd', '') if cmd == 'ping': return {'ok': True, 'v': 4} if cmd == 'list': return cmd_list(**req) if cmd == 'replay': return cmd_replay(**req) if cmd == 'reveal': return cmd_reveal(**req) return mutate(cmd, **req) except KeyErrorSafe as error: return {'ok': False, 'err': str(error), 'operation_rejected': True} except Exception as error: sys.stderr.write('key operation failed: %s\n' % type(error).__name__) return {'ok': False, 'err': 'Статус операции не подтверждён. Повтори проверку с тем же номером', 'uncertain': True} def main(): for line in sys.stdin: try: response = dispatch(json.loads(line)) except (ValueError, TypeError): response = {'ok': False, 'err': 'Некорректный JSON', 'operation_rejected': True} _so.write(json.dumps(response, ensure_ascii=False) + '\n') _so.flush() if __name__ == '__main__': main()