"""Exact bot-account identity and read-only account-shared gateway usage.""" import os from contextlib import closing from pathlib import Path import re import sqlite3 DAILY_USD_CAP = {0: 100, 1: 100, 2: 200, 3: 500, 4: 1000} QUOTA_PER_USD = 500_000 _owner_uid_raw = os.environ.get("IISHKO_OWNER_UID", "0").strip() # Operator identity is configuration. 0 = nobody holds owner privileges. OWNER_UID = int(_owner_uid_raw) if _owner_uid_raw.isdigit() else 0 _ACCOUNT_NAME = re.compile(r"(?:tg|pm|sol)([1-9][0-9]*)(?:-k[1-9][0-9]*)?\Z") def account_uid(name: str) -> int | None: """Return the canonical Telegram UID, never a prefix/substring match.""" if not isinstance(name, str): return None match = _ACCOUNT_NAME.fullmatch(name) if match is None: return None try: uid = int(match[1]) except ValueError: return None return uid if uid <= 9223372036854775807 else None def _name_scope(column, uid): if type(uid) is not int or not 0 < uid <= 9223372036854775807: raise ValueError("invalid account uid") # GLOB is only an indexed candidate selection. Every returned name must also # pass account_uid: '-k1foreign', Unicode digits and '-k01' are not credentials. bases = [prefix + str(uid) for prefix in ("tg", "pm", "sol")] terms, args = [], [] for name in bases: terms.extend((column + "=?", column + " GLOB ?")) args.extend((name, name + "-k[0-9]*")) return "(" + " OR ".join(terms) + ")", args def account_token_names(con: sqlite3.Connection, uid: int) -> list[str]: """Exact live names for this account; do not hide query/schema failures.""" scope, args = _name_scope("name", uid) rows = con.execute("SELECT DISTINCT name FROM tokens WHERE deleted_at IS NULL AND " + scope, args).fetchall() return sorted(row[0] for row in rows if account_uid(row[0]) == uid) def daily_spent_units(gw_db, uid: int, day_start: int, day_end: int | None = None) -> int: scope, args = _name_scope("token_name", uid) if type(day_start) is not int or (day_end is not None and type(day_end) is not int): raise ValueError("invalid usage interval") if day_end is not None and day_end < day_start: raise ValueError("invalid usage interval") time_scope = "created_at>=?" times = [day_start] if day_end is not None: time_scope += " AND created_at