From fa41b48dd11960646e6ec1f49f56218fb11d3ab6 Mon Sep 17 00:00:00 2001 From: AmirS <74258437+amirshaker000@users.noreply.github.com> Date: Sat, 28 Nov 2026 06:04:43 +0330 Subject: [PATCH] fix(pool): enforce unique per-account device_mid to stop UNUSUAL_ACTIVITY flags Z.ai risk control correlates accounts that share a device fingerprint. Older generator batches wrote the same hardcoded device_mid into every snapshot, so 126/149 accounts presented an identical x-device-mid from one egress IP and the whole pool was flagged UNUSUAL_ACTIVITY (HTTP 405 from the edge WAF). Rewrite any missing or duplicated device_mid to a stable per-account uuid5 derived from the access token (identical derivation to generator/plan_check.per_account_device_mid, so gateway and generator agree). Unique mids are preserved. Applied at load for every account source. Also align the generated-config default balance_poll_seconds (60 -> 300) with the code default so a fresh config does not sweep the whole pool every minute. --- config.example.yaml | 2 +- tests/test_device_mid_uniqueness.py | 49 +++++++++++++++++++++++++++++ zcode_gateway/paths.py | 2 +- zcode_gateway/pool.py | 49 ++++++++++++++++++++++++----- 4 files changed, 93 insertions(+), 9 deletions(-) create mode 100644 tests/test_device_mid_uniqueness.py diff --git a/config.example.yaml b/config.example.yaml index b6b26a6..236f749 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -21,7 +21,7 @@ pool: cooldown_seconds: 30 max_in_flight_per_account: 4 acquire_wait_seconds: 5 - balance_poll_seconds: 60 + balance_poll_seconds: 300 blocked_model_cooldown_seconds: 900 accounts: source: accounts_dir diff --git a/tests/test_device_mid_uniqueness.py b/tests/test_device_mid_uniqueness.py new file mode 100644 index 0000000..babde02 --- /dev/null +++ b/tests/test_device_mid_uniqueness.py @@ -0,0 +1,49 @@ +"""Unique per-account device_mid: shared/absent mids get flagged UNUSUAL_ACTIVITY.""" + +import uuid + +from zcode_gateway.pool import Account, _ensure_unique_device_mids, _per_account_device_mid + + +def _acct(ident, token, mid): + return Account(id=ident, access_token=token, notes={"device_mid": mid}) + + +def test_shared_device_mid_is_replaced_for_every_account(): + shared = "234aefe2-3795-4cf2-95c6-7bd9291feb1f" + accounts = [_acct(str(i), f"tok{i}", shared) for i in range(5)] + + _ensure_unique_device_mids(accounts) + + mids = [a.notes["device_mid"] for a in accounts] + assert len(set(mids)) == 5 + assert shared not in mids + for account in accounts: + uuid.UUID(account.notes["device_mid"]) # still a valid uuid + + +def test_missing_device_mid_is_filled(): + accounts = [_acct("a", "tok-a", ""), _acct("b", "tok-b", None)] + + _ensure_unique_device_mids(accounts) + + assert all(a.notes["device_mid"] for a in accounts) + assert accounts[0].notes["device_mid"] != accounts[1].notes["device_mid"] + + +def test_unique_device_mid_is_preserved(): + accounts = [_acct("a", "tok-a", "kept-a"), _acct("b", "tok-b", "kept-b")] + + _ensure_unique_device_mids(accounts) + + assert accounts[0].notes["device_mid"] == "kept-a" + assert accounts[1].notes["device_mid"] == "kept-b" + + +def test_derivation_is_deterministic_and_generator_compatible(): + # Must match generator/plan_check.per_account_device_mid exactly so the + # gateway and generator agree on one stable id per account. + token = "eyJ.example.token" + expected = str(uuid.uuid5(uuid.NAMESPACE_URL, "zcode-device:" + token)) + assert _per_account_device_mid(token) == expected + assert _per_account_device_mid(token) == _per_account_device_mid(token) diff --git a/zcode_gateway/paths.py b/zcode_gateway/paths.py index 9ed5401..6c13fed 100644 --- a/zcode_gateway/paths.py +++ b/zcode_gateway/paths.py @@ -76,7 +76,7 @@ def find_accounts_dir() -> Path: # Written on first launch when no config.yaml is present. This is what lets # a lone binary work with nothing alongside it. Keys are per-install random, # never a shared hardcoded default. -DEFAULT_CONFIG_YAML = 'server:\n host: 127.0.0.1\n port: 8788\n require_client_key: true\n admin_key: gw-admin-local\n client_keys:\n - key: gw-local-1\n name: local\nupstream:\n base_url: https://zcode.z.ai/api/v1\n chat_path: /zcode-plan/anthropic/v1/messages\n timeout_connect: 15\n timeout_read: 600\n max_attempts: 3\npool:\n strategy: drain_first\n cooldown_seconds: 30\n max_in_flight_per_account: 4\n acquire_wait_seconds: 5\n conversation_affinity_seconds: 600\n balance_poll_seconds: 60\naccounts:\n source: accounts_dir\n providers_json: "~/.zcode/v2/credentials.json"\n dir: ./accounts\n pool_file: ./pool.json\nmodels:\n aliases:\n glm-5.4: GLM-5.4\n glm-5.3-flash: GLM-5.3-Flash\n default: GLM-5.3-Flash\n default_anthropic: GLM-5.4\n default_max_tokens: 128000\n default_effort: high\n pacing:\n enabled: true\n min_gap_ms: 150\n max_gap_ms: 400\n auto_free_fallback:\n enabled: false\n chain: [GLM-5.4, GLM-5.3-Flash]\nlogging:\n level: INFO\n capture: false\n capture_dir: ./logs\nstore:\n sqlite_path: ./gateway.db\nupdate:\n enabled: false\n repo: B3hnamR/AutoZcoder\ngenerator:\n enabled: false\n zcodeauto_dir: ""\n python_exe: ""\n captcha: "manual"\n headless: false\n claim: true\n invite_code: "MT9GNDQ8"\n captcha_tickets: 0\n captcha_ticket_ttl_seconds: 75\n socks_only: true\n proxy_types: "socks"\nclaims:\n daily_enabled: false\n daily_time: "19:02"\n daily_utc_offset_hours: 8\n daily_mode: direct\n campaign_utc_offset_hours: 8\n campaign_gate: true\n' +DEFAULT_CONFIG_YAML = 'server:\n host: 127.0.0.1\n port: 8788\n require_client_key: true\n admin_key: gw-admin-local\n client_keys:\n - key: gw-local-1\n name: local\nupstream:\n base_url: https://zcode.z.ai/api/v1\n chat_path: /zcode-plan/anthropic/v1/messages\n timeout_connect: 15\n timeout_read: 600\n max_attempts: 3\npool:\n strategy: drain_first\n cooldown_seconds: 30\n max_in_flight_per_account: 4\n acquire_wait_seconds: 5\n conversation_affinity_seconds: 600\n balance_poll_seconds: 300\naccounts:\n source: accounts_dir\n providers_json: "~/.zcode/v2/credentials.json"\n dir: ./accounts\n pool_file: ./pool.json\nmodels:\n aliases:\n glm-5.4: GLM-5.4\n glm-5.3-flash: GLM-5.3-Flash\n default: GLM-5.3-Flash\n default_anthropic: GLM-5.4\n default_max_tokens: 128000\n default_effort: high\n pacing:\n enabled: true\n min_gap_ms: 150\n max_gap_ms: 400\n auto_free_fallback:\n enabled: false\n chain: [GLM-5.4, GLM-5.3-Flash]\nlogging:\n level: INFO\n capture: false\n capture_dir: ./logs\nstore:\n sqlite_path: ./gateway.db\nupdate:\n enabled: false\n repo: B3hnamR/AutoZcoder\ngenerator:\n enabled: false\n zcodeauto_dir: ""\n python_exe: ""\n captcha: "manual"\n headless: false\n claim: true\n invite_code: "MT9GNDQ8"\n captcha_tickets: 0\n captcha_ticket_ttl_seconds: 75\n socks_only: true\n proxy_types: "socks"\nclaims:\n daily_enabled: false\n daily_time: "19:02"\n daily_utc_offset_hours: 8\n daily_mode: direct\n campaign_utc_offset_hours: 8\n campaign_gate: true\n' def default_config_yaml() -> str: diff --git a/zcode_gateway/pool.py b/zcode_gateway/pool.py index 053a97a..41fc421 100644 --- a/zcode_gateway/pool.py +++ b/zcode_gateway/pool.py @@ -8,7 +8,7 @@ import os import threading import time -from collections import deque +from collections import Counter, deque from dataclasses import dataclass, field from datetime import datetime, timezone from enum import Enum @@ -288,16 +288,51 @@ def load_from_pool_file(path: str) -> list[Account]: return out +def _per_account_device_mid(token: str) -> str: + """Deterministic per-account device id. + + Mirrors the generator's derivation exactly (uuid5 of the access token) so + the gateway and the generator agree on a single, stable id per account. + """ + import uuid as _uuid + return str(_uuid.uuid5(_uuid.NAMESPACE_URL, "zcode-device:" + (token or ""))) + + +def _ensure_unique_device_mids(accounts: list[Account]) -> list[Account]: + """Guarantee every account presents a distinct ``x-device-mid``. + + Z.ai risk control correlates accounts that share a device fingerprint: a + shared *or* empty ``device_mid`` across the pool is a direct cross-account + signal that gets the whole pool flagged ``UNUSUAL_ACTIVITY`` (HTTP 405 from + the edge WAF). Older generator batches wrote the same hardcoded mid into + every snapshot, so we rewrite any missing or duplicated mid to a stable + per-account uuid5 derived from the access token. Unique mids are preserved. + """ + counts = Counter((a.notes.get("device_mid") or "").strip() for a in accounts) + seen: set[str] = set() + for account in accounts: + mid = (account.notes.get("device_mid") or "").strip() + if not mid or counts[mid] > 1: + seed = account.access_token or account.id + mid = _per_account_device_mid(seed) + while mid in seen or (mid in counts and counts[mid] > 1): + mid = _per_account_device_mid(mid) + account.notes["device_mid"] = mid + seen.add(mid) + return accounts + + def load_accounts(cfg: AccountsConfig) -> list[Account]: if cfg.source == "pool_file": - return load_from_pool_file(cfg.pool_file) - if cfg.source == "providers_json": - return load_from_providers_json(cfg.providers_json) - if cfg.source == "accounts_dir": + accounts = load_from_pool_file(cfg.pool_file) + elif cfg.source == "providers_json": + accounts = load_from_providers_json(cfg.providers_json) + elif cfg.source == "accounts_dir": from .accounts_dir import load_from_accounts_dir accounts = load_from_accounts_dir(cfg.dir) - return accounts - raise ValueError(f"unknown accounts.source: {cfg.source}") + else: + raise ValueError(f"unknown accounts.source: {cfg.source}") + return _ensure_unique_device_mids(accounts) # --------------------------------------------------------------------------- #