maxpool 1.24.70 → 1.24.71

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "maxpool",
3
- "version": "1.24.70",
3
+ "version": "1.24.71",
4
4
  "description": "Multi-account Claude Code proxy with adaptive, rate-aware load balancing across Claude accounts",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
@@ -108,6 +108,10 @@ function emptyQuota() {
108
108
  }
109
109
 
110
110
  const DEFAULT_SCHEDULER = {
111
+ // Kept high on purpose. A cap of 3 was tried 2026-11-07 (to look like one person)
112
+ // and measured against the owner's real traffic first: peaks of 79 simultaneous
113
+ // requests from his many sessions, with only ~4 accounts usable that day, would
114
+ // have queued and failed. Spreading load is the router's job, not a hard cap's.
111
115
  safetyMaxActivePerAccount: 50,
112
116
  safetyMaxGlobalActive: 150,
113
117
  cooldownMs: 30_000,
@@ -0,0 +1,107 @@
1
+ // One fixed client identity per upstream account (owner 2026-11-07, after two z.ai
2
+ // "usage risk" notices). Claude Code stamps every request with a per-INSTALL id
3
+ // (metadata.user_id → device_id) and its machine/runtime details (x-stainless-*,
4
+ // user-agent). Forwarded verbatim, one pooled account shows several installs on
5
+ // different machines alternating within seconds. Here every request leaving for an
6
+ // account carries that account's own stable device id and one machine profile, so
7
+ // each account presents as one laptop whoever sent the request. Sessions stay as
8
+ // sent (one person legitimately runs many sessions), and anything that is not a
9
+ // Claude Code request passes through untouched.
10
+ import { createHash } from 'node:crypto';
11
+
12
+ const FIXED_MACHINE = { 'x-stainless-os': 'MacOS', 'x-stainless-arch': 'arm64' };
13
+ const CC_UA = /^claude-cli\/\d+(?:\.\d+)*.*$/;
14
+
15
+ /** Stable per-account seed: the Claude account uuid, else the row name (NOT the
16
+ * provider key — z.ai key rotation would silently change the identity; the name
17
+ * survives rotation). Same account on two pools → same identity. */
18
+ function accountSeed(account) {
19
+ if (account.accountUuid) return `uuid:${account.accountUuid}`;
20
+ return `name:${account.name}`;
21
+ }
22
+
23
+ export function virtualDeviceId(account) {
24
+ return createHash('sha256').update(`maxpool-device-v1:${accountSeed(account)}`).digest('hex');
25
+ }
26
+
27
+ // The metadata.user_id string Claude Code sends today is a JSON object as a STRING
28
+ // inside the outer JSON body: metadata.user_id = '{"device_id":"…","account_uuid":"…","session_id":"…"}'.
29
+ // We operate on the RAW body string, splicing only that inner string. The rest of
30
+ // the body is never parsed or re-serialized: JSON.parse→stringify corrupts integers
31
+ // above 2^53 (snowflake ids in tool results) and reformats exponents — byte drift
32
+ // the transcript does not forgive (red-team M1, 2026-11-07).
33
+
34
+ /** Find the escaped-string value of metadata.user_id in a raw JSON body.
35
+ * Returns { start, end, text } — the value's source range WITHOUT quotes and its
36
+ * unescaped text — or null. Scanning, not regex: real bodies vary spacing, and the
37
+ * value itself contains escapes a naive [^"]* would cut short. */
38
+ function scanMetadataUserId(bodyStr) {
39
+ const key = bodyStr.indexOf('"user_id"');
40
+ if (key === -1) return null;
41
+ let i = bodyStr.indexOf(':', key + 9);
42
+ if (i === -1) return null;
43
+ i++;
44
+ while (i < bodyStr.length && /\s/.test(bodyStr[i])) i++;
45
+ if (bodyStr[i] === '{') {
46
+ // Not a string (someone sent an object) — not ours to touch.
47
+ return null;
48
+ }
49
+ if (bodyStr[i] !== '"') return null;
50
+ i++;
51
+ const start = i;
52
+ while (i < bodyStr.length) {
53
+ const c = bodyStr[i];
54
+ if (c === '\\') { i += 2; continue; }
55
+ if (c === '"') break;
56
+ i++;
57
+ }
58
+ if (i >= bodyStr.length) return null;
59
+ let text;
60
+ try { text = JSON.parse(`"${bodyStr.slice(start, i)}"`); } catch { return null; }
61
+ return { start, end: i, text };
62
+ }
63
+
64
+ /** Build the account's replacement for the inner user_id string. */
65
+ function replacementUserId(account, originalText) {
66
+ const device = virtualDeviceId(account);
67
+ const acctUuid = account.type === 'oauth' && account.accountUuid ? account.accountUuid : '';
68
+ let o = null;
69
+ try { o = JSON.parse(originalText); } catch { return null; }
70
+ if (!o || typeof o !== 'object' || !('device_id' in o) || !('session_id' in o)) return null;
71
+ o.device_id = device;
72
+ if ('account_uuid' in o) o.account_uuid = acctUuid;
73
+ const next = JSON.stringify(o);
74
+ return next === originalText ? null : next;
75
+ }
76
+
77
+ /** Rewrite metadata.user_id in a RAW request-body string. Returns the new body
78
+ * string, or null when nothing applies (not Claude Code's shape → untouched). */
79
+ export function rewriteMetadataUserIdRaw(bodyStr, account) {
80
+ if (typeof bodyStr !== 'string' || !bodyStr.includes('"metadata"')) return null;
81
+ const hit = scanMetadataUserId(bodyStr);
82
+ if (!hit) return null;
83
+ // Legacy flat form first: it is not JSON, so replacementUserId would reject it.
84
+ const legacy = /^user_[0-9a-f]+_account_[^_]*_session_(.+)$/.exec(hit.text);
85
+ const acctUuid = account.type === 'oauth' && account.accountUuid ? account.accountUuid : '';
86
+ let next = legacy
87
+ ? `user_${virtualDeviceId(account)}_account_${acctUuid}_session_${legacy[1]}`
88
+ : replacementUserId(account, hit.text);
89
+ if (next == null) return null;
90
+ return bodyStr.slice(0, hit.start) + JSON.stringify(next).slice(1, -1) + bodyStr.slice(hit.end);
91
+ }
92
+
93
+ /** Normalize outgoing headers in place: one machine profile for every account (the
94
+ * per-account device id is what tells them apart). Client versions are left as
95
+ * sent: pinning to the "newest seen" made every account's version regress after a
96
+ * restart (red-team M2) and mid-retry UA flips — and several versions is what a
97
+ * normal auto-updating fleet of installs looks like anyway. Only touches requests
98
+ * that identify as Claude Code (user-agent claude-cli/…). */
99
+ export function normalizeClientHeaders(headers) {
100
+ const uaKey = Object.keys(headers).find(k => k.toLowerCase() === 'user-agent');
101
+ if (!uaKey || !CC_UA.test(String(headers[uaKey]))) return false;
102
+ const lower = new Map(Object.keys(headers).map(k => [k.toLowerCase(), k]));
103
+ for (const [h, v] of Object.entries(FIXED_MACHINE)) {
104
+ if (lower.has(h)) headers[lower.get(h)] = v;
105
+ }
106
+ return true;
107
+ }
package/src/config.js CHANGED
@@ -77,6 +77,10 @@ export function createDefaultConfig() {
77
77
  // cache prefix. Claude-account responses are NEVER scrubbed. Default OFF until the
78
78
  // E2E package is owner-approved.
79
79
  providerThinkingScrub: false,
80
+ // Each upstream account presents ONE fixed Claude Code identity (device id +
81
+ // machine profile) regardless of who sent the request — pooled accounts stop
82
+ // showing several installs alternating within seconds. On by default; false = verbatim.
83
+ accountIdentity: true,
80
84
  routing: {
81
85
  mode: 'automatic',
82
86
  preferredAccount: null,
package/src/server.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import http from 'node:http';
2
+ import { normalizeClientHeaders, rewriteMetadataUserIdRaw } from './client-identity.js';
2
3
  import { appendEventLog } from './event-log.js';
3
4
  import { atomicConfigUpdate } from './config.js';
4
5
  import { HOP_HEADER, nextHopCount, safeText } from './pool-link.js';
@@ -499,6 +500,8 @@ export function createProxyServer(accountManager, config, hooks = {}) {
499
500
  // Read per request (not captured at boot) so a config flip + seamless reload
500
501
  // takes effect on the next request with no restart.
501
502
  requestInfo.providerThinkingScrub = Boolean(config.providerThinkingScrub);
503
+ // On unless switched off: each account presents as one fixed Claude Code install.
504
+ requestInfo.accountIdentity = config.accountIdentity !== false;
502
505
  // The CLIENT tells us how long it will wait — the only source that is actually
503
506
  // true. A `cc` session exports CLAUDE_STREAM_IDLE_TIMEOUT_MS=3h and forwards it
504
507
  // here; a bare `claude` sends nothing and keeps the conservative 240s default,
@@ -857,6 +860,7 @@ async function forwardRequest(
857
860
  headers['x-api-key'] = account.credential;
858
861
  delete headers['authorization'];
859
862
  }
863
+ if (requestInfo.accountIdentity && !account.remote) normalizeClientHeaders(headers);
860
864
 
861
865
  // POOL LINK (owner D8): this "account" is another maxpool. Forward the raw
862
866
  // request to it with the person's key, a stepped hop header, and the client's
@@ -994,7 +998,7 @@ async function forwardRequest(
994
998
 
995
999
  const upstreamUrl = `${account.upstream || upstream}${req.url}`;
996
1000
  const method = req.method;
997
- const upstreamBody = rewriteBodyForAccount(body, account);
1001
+ const upstreamBody = rewriteBodyForAccount(body, account, { identity: requestInfo.accountIdentity });
998
1002
 
999
1003
  // A threaded follow-up routed to an account that does not hold the thread cannot be
1000
1004
  // served by it: a different Anthropic account 404s, a provider rejects the truncated
@@ -3657,8 +3661,18 @@ function describeBodyShape(buf) {
3657
3661
  const threadOwners = new ThreadOwners();
3658
3662
  const THREAD_GATE_ENABLED = process.env.MAXPOOL_THREAD_GATE !== '0';
3659
3663
 
3660
- function rewriteBodyForAccount(body, account) {
3664
+ function rewriteBodyForAccount(body, account, { identity = false } = {}) {
3661
3665
  const needsProviderSanitize = account.type === 'provider';
3666
+ // Identity first, on the RAW string: splicing only the metadata.user_id value keeps
3667
+ // every other byte identical (a parse→serialize round-trip corrupts >2^53 integers
3668
+ // in tool results — red-team M1, 2026-11-07).
3669
+ if (identity && body.length && body.includes('"metadata"')) {
3670
+ const rewritten = rewriteMetadataUserIdRaw(body.toString(), account);
3671
+ if (rewritten != null && (!account.model && !account.modelMap && !needsProviderSanitize)) {
3672
+ return Buffer.from(rewritten);
3673
+ }
3674
+ if (rewritten != null) body = Buffer.from(rewritten);
3675
+ }
3662
3676
  if (!body.length || (!account.model && !account.modelMap && !needsProviderSanitize)) return body;
3663
3677
 
3664
3678
  try {