Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion config.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
49 changes: 49 additions & 0 deletions tests/test_device_mid_uniqueness.py
Original file line number Diff line number Diff line change
@@ -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)]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This suite misses an order-dependent collision between a rewritten duplicate and a later preserved device_mid, so the claimed uniqueness guarantee can still fail while these tests pass. Add a regression fixture where the later preserved mid equals an earlier account’s derived ID.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At tests/test_device_mid_uniqueness.py, line 14:

<comment>This suite misses an order-dependent collision between a rewritten duplicate and a later preserved `device_mid`, so the claimed uniqueness guarantee can still fail while these tests pass. Add a regression fixture where the later preserved mid equals an earlier account’s derived ID.</comment>

<file context>
@@ -0,0 +1,49 @@
+
+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)
</file context>


_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))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This does not test generator compatibility because it duplicates the generator’s current formula. Compare _per_account_device_mid(token) directly with generator.plan_check.per_account_device_mid(token) so drift is detected.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At tests/test_device_mid_uniqueness.py, line 47:

<comment>This does not test generator compatibility because it duplicates the generator’s current formula. Compare `_per_account_device_mid(token)` directly with `generator.plan_check.per_account_device_mid(token)` so drift is detected.</comment>

<file context>
@@ -0,0 +1,49 @@
+    # 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)
</file context>

assert _per_account_device_mid(token) == expected
assert _per_account_device_mid(token) == _per_account_device_mid(token)
2 changes: 1 addition & 1 deletion zcode_gateway/paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This changes the standalone bootstrap only; the Linux installer still generates balance_poll_seconds: 60. Fresh VPS deployments therefore keep the old one-minute pool-wide sweep despite the new 300-second generated-config default. Update the Linux installer template to keep all generated configs aligned.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At zcode_gateway/paths.py, line 79:

<comment>This changes the standalone bootstrap only; the Linux installer still generates `balance_poll_seconds: 60`. Fresh VPS deployments therefore keep the old one-minute pool-wide sweep despite the new 300-second generated-config default. Update the Linux installer template to keep all generated configs aligned.</comment>

<file context>
@@ -76,7 +76,7 @@ def find_accounts_dir() -> Path:
 # 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'
 
 
</file context>



def default_config_yaml() -> str:
Expand Down
49 changes: 42 additions & 7 deletions zcode_gateway/pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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]:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: Applying this only during source loading leaves the live account-add path unprotected. A second dashboard login can still enter the pool with the shared fingerprint and trigger the same WAF before the next reload; enforce the per-account ID when registering or upserting an account as well.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At zcode_gateway/pool.py, line 301:

<comment>Applying this only during source loading leaves the live account-add path unprotected. A second dashboard login can still enter the pool with the shared fingerprint and trigger the same WAF before the next reload; enforce the per-account ID when registering or upserting an account as well.</comment>

<file context>
@@ -288,16 +288,51 @@ def load_from_pool_file(path: str) -> list[Account]:
+    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``.
+
</file context>

"""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()
Comment on lines +311 to +314

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: A non-string device_mid in pool.json now crashes the whole account load because .strip() is unconditional; the app then starts with an empty pool. Normalize only string values and treat other values as missing so one malformed metadata field cannot disable every account.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At zcode_gateway/pool.py, line 311:

<comment>A non-string `device_mid` in `pool.json` now crashes the whole account load because `.strip()` is unconditional; the app then starts with an empty pool. Normalize only string values and treat other values as missing so one malformed metadata field cannot disable every account.</comment>

<file context>
@@ -288,16 +288,51 @@ def load_from_pool_file(path: str) -> list[Account]:
+    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:
</file context>
Suggested change
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()
def _normalized_mid(account: Account) -> str:
value = account.notes.get("device_mid")
return value.strip() if isinstance(value, str) else ""
counts = Counter(_normalized_mid(a) for a in accounts)
seen: set[str] = set()
for account in accounts:
mid = _normalized_mid(account)

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):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: This does not guarantee uniqueness when a generated ID collides with a unique device_mid later in the input. Check generated IDs against every original value, not only duplicated values, before preserving the later account's ID.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At zcode_gateway/pool.py, line 318:

<comment>This does not guarantee uniqueness when a generated ID collides with a unique `device_mid` later in the input. Check generated IDs against every original value, not only duplicated values, before preserving the later account's ID.</comment>

<file context>
@@ -288,16 +288,51 @@ def load_from_pool_file(path: str) -> list[Account]:
+        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
</file context>
Suggested change
while mid in seen or (mid in counts and counts[mid] > 1):
while mid in seen or mid in counts:

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)


# --------------------------------------------------------------------------- #
Expand Down
Loading