"""Public API boundary: authentication aliases and safe, actionable errors.""" import json import re import logging _log = logging.getLogger("gwerr") import os as _os import sqlite3 as _sq _NEWAPI_DB = _os.environ.get("GW_NEWAPI_DB", "/opt/grok-gateway/new-api/one-api.db") # [POLICYMSG 2810] Вердикт модерации апстрима детерминирован: тот же текст на том же # OpenAI «content_filter»). Прежняя формулировка «Повтори попытку или выбери другую # модель» обещала то, чего повтор дать не может, и за 24 ч 2026-10-28 ушла юзерам # Единственный источник текста — здесь; бот импортирует константу, чтобы не дрейфовать. CONTENT_POLICY_USERMSG = ( "Провайдер этой модели отклонил запрос своим контент-фильтром. " "Повтор тем же текстом не поможет: переформулируй запрос " "или выбери модель другого семейства." ) def key_from_headers(headers): raw = "" try: for name, value in (headers or {}).items(): if str(name).lower() in ("authorization", "x-api-key", "api-key"): raw = str(value or "").strip() if raw: break except Exception: return "" if raw[:7].lower() == "bearer ": raw = raw[7:].strip() if raw.lower().startswith("sk-"): raw = raw[3:] return raw def token_state(api_key): if not api_key: return None try: con = _sq.connect("file:" + _NEWAPI_DB + "?mode=ro", uri=True, timeout=3) try: row = con.execute( 'SELECT status, COALESCE(remain_quota,0), COALESCE(unlimited_quota,0) ' 'FROM tokens WHERE "key"=? AND deleted_at IS NULL ORDER BY id DESC LIMIT 1', (api_key,)).fetchone() finally: con.close() except Exception: return None return (int(row[0] or 0), int(row[1] or 0), int(row[2] or 0)) if row else None HOP_HEADERS = frozenset({"host", "connection", "proxy-connection", "keep-alive", "transfer-encoding", "upgrade", "te", "trailer", "content-length"}) def _bearer(value): parts = value.split() return "Bearer " + parts[1] if len(parts) == 2 and parts[0].casefold() == "bearer" else value.strip() _QUOTA_CUR_RE = re.compile(r"(?:当前额度|用户剩余额度|剩余额度)[::\s]*[$$]?\s*(-?[0-9]+(?:\.[0-9]+)?)") _QUOTA_NEED_RE = re.compile(r"(?:需要额度|需要预扣费额度)[::\s]*[$$]?\s*([0-9]+(?:\.[0-9]+)?)") def _parse_quota_amounts(text): """(current, needed) в USD из «用户额度不足,当前额度: $X,需要额度: $Y»; None если формата нет.""" m_cur, m_need = _QUOTA_CUR_RE.search(text), _QUOTA_NEED_RE.search(text) if not (m_cur and m_need): return None try: return float(m_cur.group(1)), float(m_need.group(1)) except ValueError: return None def normalize_auth_headers(headers): aliases = {"authorization", "x-api-key", "api-key"} credentials = { _bearer(value) if name.lower() == "authorization" else "Bearer " + value.strip() for name, value in headers.items() if name.lower() in aliases and value.strip() } if len(credentials) > 1: raise ValueError("conflicting authentication headers") lower = {k.lower(): v for k, v in headers.items()} connection = {v.strip().lower() for v in lower.get("connection", "").split(",")} excluded = HOP_HEADERS | connection | aliases result = {k: v for k, v in headers.items() if k.lower() not in excluded} if credentials: result["Authorization"] = credentials.pop() return result _MAX_ERROR_TEXT = 65536 _ESCAPED_OBJECT = re.compile(r'^\{\s*\\+"') _PUBLIC_ID = re.compile(r"[A-Za-z0-9_-]{1,128}") _PRIVATE_ID = re.compile( r"^(?:sk[-_]|sess[-_]|gh[pousr]_|github_pat_|xox[baprs]-|AIza|AKIA|ASIA|eyJ|bearer$|basic$)" r"|(?:localhost|internal)(?:$|[-_])", re.IGNORECASE) _REQUEST_ID = re.compile( r"""\brequest[ _-]id\s*:\s*([^\s)\]}"',;]+)(?=\s*(?:[)\]}"',;]|$))""", re.IGNORECASE) def _decode_error_value(value): """Decode bounded, complete JSON layers only; never unicode_escape UTF-8 prose.""" if isinstance(value, (bytes, bytearray)): if len(value) > _MAX_ERROR_TEXT: return None value = value.decode("utf-8-sig", errors="replace") for _ in range(6): if not isinstance(value, str): return value if len(value) > _MAX_ERROR_TEXT: return None text = value.strip().lstrip("\ufeff") if not text or text[0] not in ('{', '[', '"'): return text try: value = json.loads(text) except (ValueError, RecursionError): # Some relays remove the outer quotes of a JSON-encoded object. # Unwrap only if the whole string is itself valid escaped JSON. if not (_ESCAPED_OBJECT.match(text) and text.endswith("}")): return text try: value = json.loads('"' + text + '"') except (ValueError, RecursionError): return text return value def _error_details(raw): """Walk only error/message envelopes, not arbitrary upstream data or credentials.""" source, request_ids, gateway_ids, seen, codes = [], [], [], [], [] error_code = None node = raw for _ in range(8): node = _decode_error_value(node) if isinstance(node, dict): if any(node is previous for previous in seen): break seen.append(node) for field in ("code", "type"): value = node.get(field) if isinstance(value, str) and len(value) <= 256: source.append(value) codes.append(value.strip().lower()) code = node.get("code") if isinstance(code, str) and code.strip() and len(code) <= 128: error_code = code.strip().lower() request_ids.insert(0, node.get("request_id")) gateway_ids.insert(0, node.get("gateway_request_id")) child = node.get("error") if not isinstance(child, (dict, str, bytes, bytearray)) or not child: child = node.get("message") node = child elif isinstance(node, str): source.append(node) break else: break return " ".join(source), error_code, request_ids, gateway_ids, codes def _public_id(value): return (isinstance(value, str) and _PUBLIC_ID.fullmatch(value) and not _PRIVATE_ID.search(value)) def public_json_dumps(value): """UTF-8 presentation for normalized error JSON; successful replies stay byte-exact.""" return json.dumps(value, ensure_ascii=False) # content_policy_violation. Структурное поле code/type — сильное доказательство (проверяется # до billing-прозы); упоминание «content_filter» как имени параметра (unsupported_parameter, # перечисление supported-параметров с reasoning_effort) политикой не является. _POLICY_CODE_RE = re.compile( r"^(?:(?:input|output)[_-]?)?data[_-]?inspection[_-]?failed$" r"|^content[_-]?filter$|^content[_-]?policy[_-]?violation$", re.IGNORECASE) _POLICY_TOKEN = (r"(?:(?:input|output)[_-]?)?data[_-]?inspection[_-]?failed" r"|content[_-]?policy[_-]?violation|content[_-]?filter") _POLICY_STANDALONE_RE = re.compile(r"^(?:" + _POLICY_TOKEN + r")$", re.IGNORECASE) _POLICY_PREFIX_RE = re.compile(r"(?:^|[^0-9a-z_-])(?:" + _POLICY_TOKEN + r")\s*[::]", re.IGNORECASE) _POLICY_LABELED_RE = re.compile( r"""(?:^|[\s"'({\[,;])(?:error[\s_-]*(?:code|type)|code|type|finish[\s_-]*reason|reason|status)""" r"""["'\s]*[=:]["'\s]*(?:""" + _POLICY_TOKEN + r""")(?:$|[\s"'()\]},;:.!])""", re.IGNORECASE) _POLICY_WEAK_RE = re.compile(r"(?:^|[^0-9a-z_-])content[_-]?filter(?:$|[^0-9a-z_-])", re.IGNORECASE) _POLICY_PARAM_PROSE_RE = re.compile( r"support\w*|invalid|unknown|unexpected|unrecogni[sz]ed|parameter\w*|allowed\s+values|deprecat\w*", re.IGNORECASE) def _policy_code_hit(value): """True only for an exact vendor moderation code/type, never for prose mentioning it.""" return isinstance(value, str) and bool(_POLICY_CODE_RE.match(value.strip())) def _legacy_policy_text(text, error_code): """Узкая legacy-поддержка текста: standalone-точный код, вендорный префикс «Code: …», лейбл «code/type/finish_reason: X», либо слабый «content_filter» без структурного кода и без параметрной прозы в окне вокруг упоминания.""" if not text: return False if _POLICY_STANDALONE_RE.match(text.strip().strip('"\'')): return True if _POLICY_PREFIX_RE.search(text) or _POLICY_LABELED_RE.search(text): return True if error_code: return False for match in _POLICY_WEAK_RE.finditer(text): window = text[max(0, match.start() - 40):match.end() + 40] if not _POLICY_PARAM_PROSE_RE.search(window): return True return False def _category(status, text, path, user_balance=None, from_upstream=False, error_code=None, api_key=None, codes=None): if (status == 503 and error_code == "upstream_auth_error") or (status == 401 and ( "channel error" in text or re.search(r"channel #\d+", text) or "incorrect api key provided" in text)): return 503, "upstream_auth_error", ( "Выбранная модель временно недоступна. Ваш API-ключ не отозван. " "Повторите запрос позже."), True # [POLICYCODE 2810] Структурный код/тип модерации провайдера сильнее billing-прозы в if _policy_code_hit(error_code) or any(_policy_code_hit(value) for value in codes or ()): return 400, "content_policy_violation", CONTENT_POLICY_USERMSG, False billing = ("arrearage", "good standing", "余额不足", "无可用资源包", "请充值", "insufficient balance", "credit balance", "exceeded your current quota", "free quota exhausted", "out of credits") if (status == 503 and error_code == "upstream_billing_error") or any(marker in text for marker in billing): return 503, "upstream_billing_error", "Выбранная модель временно недоступна. Это не означает обнуление вашего баланса. Повторите позже.", True # [NOPOLICY 2810] Legacy-текст сужен до реальных форм кода вендора: standalone-код, # префикс «DataInspectionFailed: …», лейбл «code/type/finish_reason: X», либо слабый # «content_filter» без структурного кода и вне параметрной прозы. Произвольная проза # с упоминанием параметра (unsupported_parameter, reasoning_effort) вердиктом не является. if _legacy_policy_text(text, error_code): return 400, "content_policy_violation", CONTENT_POLICY_USERMSG, False if "unsupported model" in text and any(m in text for m in ("qwen-image", "wanx", "t2i")) and path.endswith("/chat/completions"): return 400, "model_endpoint_mismatch", "Это модель изображений, а не чата. Используйте POST /v1/images/generations или выберите чат-модель.", False # Local new-api pre-consume rejection names the caller token explicitly. if error_code == "pre_consume_token_quota_failed": return 402, "quota_precharge_insufficient", ( "Недостаточно API-кредита для предоплаты этого запроса. " "Пополните баланс или сократите историю/контекст."), False if any(marker in text for marker in ( "insufficient_quota", "insufficient_user_quota", "user quota", "user balance", "token quota", "用户额度不足", "预扣费额度失败", "用户剩余额度")): # [ERRCLASS-20261020] «用户额度不足,当前额度: $X,需要额度: $Y» идентичен от самого new-api # это upstream, не юзер. q = _parse_quota_amounts(text) if q and user_balance is not None: cur, need = q if abs(cur - user_balance) > max(0.01, need * 0.02): _log.warning("quota_classification code=upstream_billing_error reason=balance_mismatch") return 503, "upstream_billing_error", "Выбранная модель временно недоступна. Это не означает обнуление вашего баланса. Повторите позже.", True if "channel error" in text or re.search(r"channel #\d+", text): _log.warning("quota_classification code=upstream_billing_error reason=channel") return 503, "upstream_billing_error", "Выбранная модель временно недоступна. Это не означает обнуление вашего баланса. Повторите позже.", True # неизвестна даже при отсутствии числовых сумм: не обвиняем кошелёк. if user_balance is None and not (status == 402 and error_code == "insufficient_quota"): _log.warning("quota_classification code=quota_precharge_insufficient reason=no_balance_hint") return 402, "quota_precharge_insufficient", ( "Недостаточно квоты для этого запроса. Сначала проверьте баланс, " "затем попробуйте другую модель или сократите контекст; " "если не помогло — обратитесь в поддержку @iishkogatewaybot."), False if q is None and user_balance is not None and user_balance > 0.0: _log.warning("quota_classification code=upstream_billing_error reason=positive_balance") return 503, "upstream_billing_error", "Выбранная модель временно недоступна. Это не означает обнуление вашего баланса. Повторите позже.", True _log.warning("quota_classification code=insufficient_quota") return 402, "insufficient_quota", "Для предоплаты этого запроса недостаточно API-кредита. Проверьте баланс в Mini App или сократите историю; это не означает обнуление баланса.", False # ошибка падала в generic invalid_request "Проверьте название модели" — ложь + клиент не ретраил. if (error_code in ("wallet_debt_outstanding", "wallet_debt", "wallet_suspended", "account_arrears") or "未结清消费" in text or "钱包调用暂时暂停" in text or "wallet_debt" in text): _log.warning("wallet_debt code=upstream_billing_error") return 503, "upstream_billing_error", "Выбранная модель временно недоступна. Это не означает обнуление вашего баланса. Повторите позже.", True if (error_code in ("insufficient_credits", "credit_limit_exceeded", "payment_required", "openrouter_credits", "credits_exhausted") or "never purchased credits" in text or "insufficient credits" in text or "openrouter_credits" in text or "credit_limit_exceeded" in text): _log.warning("upstream_credits code=upstream_billing_error") return 503, "upstream_billing_error", "Выбранная модель временно недоступна. Это не означает обнуление вашего баланса. Повторите позже.", True # neutral, non-retryable — attribution not proven (own token vs reseller) if ((status == 402 and error_code == "quota_precharge_insufficient") or "need quota" in text or "token remain quota" in text or "当前额度已用尽" in text or ("额度不足" in text and "用户额度不足" not in text)): return 402, "quota_precharge_insufficient", ( "Недостаточно квоты для этого запроса. Сначала проверьте баланс, " "затем попробуйте другую модель или сократите контекст; " "если не помогло — обратитесь в поддержку @iishkogatewaybot."), False if "maximum context length" in text or "context_length_exceeded" in text or "context window" in text: return 400, "context_overflow", "Запрос превышает контекст модели. Начните новый диалог, сократите историю или выберите модель с большим контекстом.", False if status == 413: if from_upstream: return 413, "upstream_request_too_large", ( "Выбранная модель отклонила размер запроса. " "Сократите историю или крупный вывод инструментов. Контекст модели измеряется в токенах; " "эта ошибка не означает лимит контекста 40 МБ."), False return 413, "request_too_large", "Запрос слишком большой. Сократите контекст или размер вложения; максимальный размер запроса — 40 MB.", False if status == 401: # [AUTHTRUTH 2410] new-api отдаёт один и тот же "Invalid token" и для чужого/удалённого _ts = token_state(api_key) if api_key else None if _ts is not None: _tstatus, _remain, _unlim = _ts if _tstatus == 4 or (not _unlim and _remain <= 0): _log.warning("auth_truth code=api_key_empty status=%s remain=%s", _tstatus, _remain) return 402, "api_key_empty", ( "Ключ живой, но на нём нулевой баланс. Переведи кредит с основного ключа " "в Mini App -> «Ключи» (или возьми новый ключ в @iishkogatewaybot)."), False if _tstatus in (2, 3): _log.warning("auth_truth code=api_key_disabled status=%s", _tstatus) return 403, "api_key_disabled", ( "Ключ отключён или истёк его срок. Открой Mini App -> «Ключи» и включи его " "или выпусти новый в @iishkogatewaybot."), False return 401, "invalid_api_key", "API-ключ недействителен или отозван. Получите актуальный ключ в @iishkogatewaybot.", False if status == 503 and error_code == "upstream_busy": return 503, "upstream_busy", "Выбранная модель сейчас занята. Повторите немного позже.", True if status == 429: if from_upstream: # Preserve overload semantics so SDKs apply Retry-After/backoff instead of # treating a healthy gateway as unavailable. return 429, "upstream_busy", "Выбранная модель сейчас занята. Повторите немного позже.", True return 429, "rate_limit_exceeded", "Достигнут временный лимит ключа. Повторите запрос позже.", True if status in (408, 504): return 504, "upstream_timeout", "Выбранная модель не ответила вовремя. Повторите запрос позже.", True if (status == 503 and error_code == "upstream_pool_empty") or "no available accounts" in text or "no available account" in text: return 503, "upstream_pool_empty", "Выбранная модель сейчас недоступна. Повторите позже.", True if status == 404 and (path.endswith(("/chat/completions", "/completions", "/embeddings", "/images/generations")) or "/v1beta/" in path): # >5000×404 за 2ч, 0 успехов; glm-5.3 сессии клиентов ломались «Запрос отклонён»). # Реально отсутствующая модель отдаётся new-api как 503 model_not_found, так что 404 на return 503, "upstream_route_dead", ( "Маршрут выбранной модели временно недоступен. " "Это проблема шлюза, а не вашего запроса. Повторите позже."), True channel = "channel error" in text or re.search(r"channel #\d+", text) permission = (error_code in ("model_not_allowed", "model_forbidden", "model_access_denied") or "this token has no access to model" in text or "not allowed for this key" in text or "model access denied" in text) if (status == 503 and error_code == "upstream_model_denied") or (status == 403 and ( (channel and permission) or ("not allowed for this key" in text and "allowed:" in text))): return 503, "upstream_model_denied", ( "Маршрут не разрешает выбранную модель. Это не означает недостаточный ранг " "вашего ключа. Повторите позже."), True # from_upstream denotes the local new-api hop too, not proven provider origin. if status == 403 and (error_code in ("model_not_allowed", "model_forbidden", "model_access_denied") or "this token has no access to model" in text): code = error_code if error_code in ("model_not_allowed", "model_forbidden") else "model_access_denied" return 403, code, ( "Запрошенная модель не разрешена этим API-ключом. Проверьте точное имя " "в актуальном Mini App → «Модели»: старые имена могли быть сняты с обслуживания. " "Если модель должна быть доступна, откройте /profile в @iishkogatewaybot " "для синхронизации прав ключа."), False if status == 403 and "address is blocked" in text and "authentication" in text: return 503, "upstream_ip_blocked", ( "Маршрут выбранной модели временно заблокирован. Ваш API-ключ не отозван; " "повторите запрос позже."), True if status == 503 and ("failed to get available channel" in text or "no available channel" in text): # This is a catalog/route absence, not a gateway outage. A 404 stops blind # retries and tells clients to refresh /v1/models. return 404, "model_unavailable", ( "У модели сейчас нет живого маршрута. Обновите список через /v1/models " "и выберите доступную модель."), False if status >= 500 or (status == 403 and channel): return 503, "upstream_unavailable", "Выбранная модель временно недоступна. Повторите запрос позже.", True if status == 403: return 403, "request_forbidden", ( "Запрос запрещён. Причина не подтверждена: " "это не обязательно ранг или баланс вашего ключа. " "Передайте request_id в поддержку @iishkogatewaybot."), False if "allowed values: ['text']" in text: # «contents.parts.type is invalid, allowed values: ['text']». Старый fallback врал # «проверьте название модели» — агент-клиенты ретраили и ломали сессию. return 400, "vision_not_supported", ( "Выбранная модель не принимает изображения: её маршрут текстовый (allowed: text). " "Уберите картинку из запроса и из истории сессии или выберите vision-модель. " "В этом запросе другая модель не подставлялась."), False return status, "invalid_request", "Запрос отклонён. Проверьте название модели (/v1/models), параметры запроса и маршрут. Если модель точно есть в списке — повторите через минуту или напишите в @iishkogatewaybot.", False def public_error(status, raw, path, user_balance=None, from_upstream=False, api_key=None): """Safe error JSON from bytes/text or parsed envelopes; never echo upstream prose.""" if type(status) is not int or not 400 <= status <= 599: status = 502 source, error_code, request_ids, gateway_ids, codes = _error_details(raw) status, code, message, retryable = _category( status, source.lower(), path if isinstance(path, str) else "", user_balance=user_balance, from_upstream=from_upstream, error_code=error_code, api_key=api_key, codes=codes) category = "invalid_request_error" if status < 500 else "upstream_error" result = {"error": {"message": message, "type": category, "code": code, "retryable": retryable}} match = _REQUEST_ID.search(source) if match: request_ids.append(match.group(1)) for field, candidates in (("request_id", request_ids), ("gateway_request_id", gateway_ids)): for value in candidates: if _public_id(value): result["error"][field] = value break return status, result