maxpool 1.24.52 → 1.24.54

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.52",
3
+ "version": "1.24.54",
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",
@@ -4762,6 +4762,28 @@ export class AccountManager {
4762
4762
  this.applyPoolLinks();
4763
4763
  }
4764
4764
 
4765
+ /** Boot-time single-writer guard: seed each link's persisted identity map
4766
+ * (state.json) so a boot during a link outage keeps local copies benched
4767
+ * until the first successful poll (red-team 2026-10-31). */
4768
+ seedPoolLinks(saved, savedAt) {
4769
+ if (!saved || typeof saved !== 'object') return;
4770
+ for (const l of this.poolLinks) {
4771
+ const byName = saved[l.name];
4772
+ if (byName) l.seedPoolIdentities?.(byName, savedAt);
4773
+ }
4774
+ this.applyPoolLinks();
4775
+ }
4776
+
4777
+ /** Per-link identity maps for state.json (keyed by link name). */
4778
+ exportPoolIdentities() {
4779
+ const out = {};
4780
+ for (const l of this.poolLinks) {
4781
+ const ids = l.exportPoolIdentities?.();
4782
+ if (ids) out[l.name] = ids;
4783
+ }
4784
+ return Object.keys(out).length ? out : null;
4785
+ }
4786
+
4765
4787
  /** Apply duplicate benching + link health from the links' last polls. Idempotent. */
4766
4788
  applyPoolLinks() {
4767
4789
  const ids = new Map();
@@ -4774,6 +4796,19 @@ export class AccountManager {
4774
4796
  for (const a of this.accounts) {
4775
4797
  const wasBenched = Boolean(a.poolBenchedBy);
4776
4798
  const d = dups.find(x => x.index === a.index);
4799
+ // Token-divergence alarm (red-team 2026-10-31): the cloud row for this
4800
+ // identity is refreshDead while the local copy holds a healthy credential —
4801
+ // both sides went dark in the boot-outage scenario. Name it loudly instead
4802
+ // of silently benching the only working copy.
4803
+ if (d) {
4804
+ const remoteRow = (this.poolLinks || [])
4805
+ .flatMap(l => (l.status?.accounts || []).filter(r => r.name === d.remoteName))[0];
4806
+ if (remoteRow?.refreshDead && !a.refreshDead && a.refreshToken) {
4807
+ const msg = `[Maxpool] Token divergence: team pool's "${d.remoteName}" is refreshDead but local "${a.name}" holds a live token — run /login on the local row to re-auth the team pool (one keystroke), or the account stays dark on both sides`;
4808
+ console.log(msg);
4809
+ appendEventLog(msg);
4810
+ }
4811
+ }
4777
4812
  a.poolBenchedBy = d ? (d.remoteName || 'team pool') : null;
4778
4813
  if (d && !wasBenched) {
4779
4814
  console.log(`[Maxpool] Duplicate guard: local account "${a.name}" also lives in team pool (${a.poolBenchedBy}) — benched locally, no routing, no token refresh`);
package/src/index.js CHANGED
@@ -648,6 +648,12 @@ async function serverWorkerCommand() {
648
648
  // final flush and restores fully (the reported zero-request case).
649
649
  if (savedState?.runtimeProviders) accountManager.restoreRuntimeProviders(savedState.runtimeProviders);
650
650
  if (savedState?.callerStats) accountManager.restoreCallerStats?.(savedState.callerStats);
651
+ // Boot-time single-writer guard: seed each link's identity map from the last
652
+ // persisted run so a boot during a link outage doesn't un-bench local copies
653
+ // (red-team 2026-10-31). Replaced by the first successful poll.
654
+ if (savedState?.poolIdentities) {
655
+ accountManager.seedPoolLinks?.(savedState.poolIdentities, savedState.poolIdentitiesAt);
656
+ }
651
657
 
652
658
  // ── config-sourced providers (GCP Secret Manager) ──────────────────────────
653
659
  // Provider keys (GLM, Kimi) defined in the config's `providers` section, each
@@ -747,6 +753,10 @@ async function serverWorkerCommand() {
747
753
  // SC22 per-person analytics — same generation-guarded payload, survives
748
754
  // restarts and seamless reloads.
749
755
  callerStats: accountManager.exportCallerStats?.() || {},
756
+ // Last-good remote identity maps — the boot-time single-writer guard reads
757
+ // these (see restore above). Rides the same generation-guarded payload.
758
+ poolIdentities: accountManager.exportPoolIdentities?.() || null,
759
+ poolIdentitiesAt: Date.now(),
750
760
  },
751
761
  { expectedGeneration },
752
762
  )
package/src/pool-link.js CHANGED
@@ -129,6 +129,45 @@ export function summarizeRemote(status) {
129
129
  }
130
130
 
131
131
  /** Test seam holder for PoolLink's timer (so tests don't leak handles). */
132
+ /** Strip terminal control characters (ESC + C0/C1 except tab) from a string that
133
+ * came off-box. Remote pool/account/caller names are rendered raw into the owner's
134
+ * terminal; an OSC 52 / CSI sequence there can rewrite the clipboard or blank the
135
+ * screen (security review 2026-10-31). Sanitized at INGRESS so no renderer has to. */
136
+ export function safeText(v) {
137
+ if (typeof v !== 'string') return v;
138
+ return v.replace(/[\u0000-\u0008\u000A-\u001F\u007F-\u009F]/g, '');
139
+ }
140
+
141
+ function sanitizeRemoteStatus(json) {
142
+ if (!json || typeof json !== 'object') return json;
143
+ for (const a of Array.isArray(json.accounts) ? json.accounts : []) {
144
+ if (a && typeof a === 'object') { a.name = safeText(a.name); a.provider = safeText(a.provider); a.lastError = safeText(a.lastError); }
145
+ }
146
+ for (const p of Array.isArray(json.pools) ? json.pools : []) {
147
+ if (p && typeof p === 'object') {
148
+ p.name = safeText(p.name);
149
+ for (const a of Array.isArray(p.accounts) ? p.accounts : []) if (a && typeof a === 'object') a.name = safeText(a.name);
150
+ }
151
+ }
152
+ if (json.callers && typeof json.callers === 'object') {
153
+ const clean = {};
154
+ for (const [k, v] of Object.entries(json.callers)) clean[safeText(k)] = v;
155
+ json.callers = clean;
156
+ }
157
+ return json;
158
+ }
159
+
160
+ /**
161
+ * Boot-time single-writer guard (red-team 2026-10-31, blocking): a fresh PoolLink
162
+ * starts with EMPTY identities, so a boot during a link outage saw ids={} and the
163
+ * duplicate guard RELEASED every local copy — which then served and rotated tokens
164
+ * the cloud still held (invalid_grant on the cloud row when the link returned; the
165
+ * healthy local copy re-benched → account dark on BOTH sides). The last good
166
+ * identity map is persisted in state.json; seedPoolIdentities() restores it at boot
167
+ * so a link that hasn't polled yet still benches what it benched last run.
168
+ */
169
+ const BOOT_IDS_TTL_MS = 14 * 24 * 3600 * 1000; // stale beyond this → trust a fresh boot instead
170
+
132
171
  export class PoolLink {
133
172
  constructor(def, deps = {}) {
134
173
  this.name = def.name;
@@ -148,13 +187,32 @@ export class PoolLink {
148
187
  this.summary = null;
149
188
  }
150
189
 
190
+ /** Seed identities persisted from a previous run (state.json). Used until the
191
+ * first successful poll replaces them; old seeds (>14d) are ignored. */
192
+ seedPoolIdentities(saved, savedAt) {
193
+ if (!saved || typeof saved !== 'object') return;
194
+ if (savedAt != null && Date.now() - savedAt > BOOT_IDS_TTL_MS) return;
195
+ if (this.identities && this.identities.size > 0) return; // a real poll already ran
196
+ const m = new Map(Object.entries(saved).map(([k, v]) => [k, v]));
197
+ if (m.size > 0) {
198
+ this.identities = m;
199
+ this._bootSeeded = true;
200
+ }
201
+ }
202
+
203
+ /** Identity map for persistence (plain object). */
204
+ exportPoolIdentities() {
205
+ return this.identities && this.identities.size > 0
206
+ ? Object.fromEntries(this.identities) : null;
207
+ }
208
+
151
209
  async poll() {
152
210
  if (this._polling) return; // never stack polls
153
211
  this._polling = true;
154
212
  try {
155
213
  const r = await this._fetchRemoteStatus(this.url, this.key);
156
214
  if (r.ok) {
157
- this.status = r.json;
215
+ this.status = sanitizeRemoteStatus(r.json);
158
216
  this.lastOkAt = r.at;
159
217
  this.lastError = null;
160
218
  this.identities = remoteIdentities(r.json);
package/src/prober.js CHANGED
@@ -333,7 +333,9 @@ export class Prober {
333
333
  // Claude banked resets (cedar_ember) piggyback on the oauth poll — same
334
334
  // OWNER GATE as z.ai cards: a DISABLED account is never listed or claimed.
335
335
  try {
336
- if (account.enabled !== false && account.credential && this.am.applyResetGrants) {
336
+ // A pool-benched duplicate never claims a grant: the cloud owns this account
337
+ // (mirror of the z.ai card guard above; red-team 2026-10-31).
338
+ if (account.enabled !== false && account.credential && !account.poolBenchedBy && this.am.applyResetGrants) {
337
339
  const listing = await this._withTimeout(this.grantsFn(account.credential));
338
340
  if (listing) {
339
341
  this.am.applyResetGrants(account.index, listing);
@@ -60,9 +60,7 @@ export function decideZai(account, cards, now = Date.now()) {
60
60
  if (!cards || cards.error) return null;
61
61
  if (account?.outsideUsage?.outside) return null; // R7: key used by someone else — a card would feed the leak
62
62
  const q = account.quota || {};
63
- const ses = q.providerSes ?? null;
64
- const wk = q.weeklyAbsent ? null : (q.providerWk ?? null);
65
- const wkUtil = wk; const sesUtil = ses;
63
+ const wkUtil = q.weeklyAbsent ? null : (q.providerWk ?? null);
66
64
 
67
65
  const weeklyCards = (cards.weekly || []).filter(c => !c.expired && c.recordId != null);
68
66
  // R4: soonest expiry first inside each class.
@@ -72,10 +70,12 @@ export function decideZai(account, cards, now = Date.now()) {
72
70
 
73
71
  // --- weekly card: clears BOTH windows (z.ai docs; measured: glm1 100%->0% both)
74
72
  if (weeklyCard) {
75
- const worst = Math.max(wkUtil ?? 0, sesUtil ?? 0);
76
73
  const atWall = wkUtil != null && wkUtil >= POLICY.wallWeekly;
74
+ // Dying gate reads the WEEKLY window alone (owner 2026-10-30: resets are never
75
+ // spent on session limits). The old Math.max(wk,ses) let a 96% 5h window redeem
76
+ // a scarce weekly card — the exact trade the owner banned.
77
77
  const dying = msLeft(weeklyCard.expiresAt, now) < POLICY.dyingWindowMs
78
- && worst >= POLICY.dyingMinUtilWeekly;
78
+ && wkUtil != null && wkUtil >= POLICY.dyingMinUtilWeekly;
79
79
  if (atWall || dying) {
80
80
  // R6: a wall redeem waits when the FREE weekly refill is imminent and the
81
81
  // account isn't critically full (dying-value redeems stay exempt above).
@@ -111,7 +111,6 @@ export function decideClaude(account, listing, now = Date.now()) {
111
111
 
112
112
  const q = account.quota || {};
113
113
  const wkUtil = q.unified7d ?? null;
114
- const sesUtil = q.unified5h ?? null;
115
114
  const clearsWk = chosen.clears?.includes('seven_day');
116
115
 
117
116
  // Owner, 2026-10-30: "never spend resets on session limits, only on weekly."
@@ -122,7 +121,7 @@ export function decideClaude(account, listing, now = Date.now()) {
122
121
 
123
122
  // use_requires_limit: some grants may only fire AT the wall (server-enforced).
124
123
  const dying = msLeft(chosen.endsAt, now) < POLICY.dyingWindowMs
125
- && Math.max(wkUtil ?? 0, sesUtil ?? 0) >= POLICY.dyingMinUtilWeekly;
124
+ && wkUtil != null && wkUtil >= POLICY.dyingMinUtilWeekly; // weekly window only (owner 2026-10-30)
126
125
  // A requires-limit grant cannot be redeemed pre-wall even for dying value.
127
126
  if (atWall || (dying && !chosen.requiresLimit)) {
128
127
  return { kind: 'grant', grant: chosen, reason: atWall ? 'at wall' : 'dying value' };
package/src/screen.html CHANGED
@@ -110,7 +110,9 @@ h1{font-size:22px;margin:0;letter-spacing:-.3px}
110
110
  function render(s) {
111
111
  // Live needs-login accounts first; switched-off accounts last.
112
112
  function rank(a) { return a.enabled === false ? 2 : (a.refreshDead ? 0 : 1); }
113
- var accts = (s.accounts || []).slice().sort(function (x, y) {
113
+ // Mirror rows (a.remote) render only under their pool chip below — keeping
114
+ // them in the main grid duplicated every cloud account on the linking machine.
115
+ var accts = (s.accounts || []).filter(function (a) { return !a.remote; }).sort(function (x, y) {
114
116
  return rank(x) - rank(y) || String(x.name).localeCompare(String(y.name));
115
117
  });
116
118
  var dead = accts.filter(function (a) { return a.refreshDead && a.enabled !== false; }).length;
@@ -134,7 +136,7 @@ h1{font-size:22px;margin:0;letter-spacing:-.3px}
134
136
  }).join('');
135
137
  var ver = (s.runningVersion || (s.version && s.version.current) || '');
136
138
  var cloud = (s.pools || []).reduce(function (n, p) { return n + (p.accounts || []).length; }, 0);
137
- app.innerHTML = '<header><h1>Maxpool accounts</h1><span class="meta">' + accts.length + ' local' + (cloud ? ' · ' + cloud + ' cloud' : '') + ' accounts' +
139
+ app.innerHTML = '<header><h1>Maxpool accounts</h1><span class="meta">' + accts.length + ' on this Mac' + (cloud ? ' · ' + cloud + ' cloud' : '') + ' accounts' +
138
140
  (dead ? ' · <b style="color:var(--bad)">' + dead + (dead === 1 ? ' needs login' : ' need login') + '</b>' : '') +
139
141
  (ver ? ' · v' + esc(ver) : '') + ' · updated ' + new Date().toLocaleTimeString() + '</span>' +
140
142
  '<button class="link" id="out">Forget key</button></header>' +
package/src/server.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import http from 'node:http';
2
2
  import { appendEventLog } from './event-log.js';
3
3
  import { atomicConfigUpdate } from './config.js';
4
- import { HOP_HEADER, nextHopCount } from './pool-link.js';
4
+ import { HOP_HEADER, nextHopCount, safeText } from './pool-link.js';
5
5
  import { ThreadOwners, readThreadIntent, threadRefusalBody, isThreadlessAccount } from './thread-gate.js';
6
6
  import { writeFile, mkdir } from 'node:fs/promises';
7
7
  import { readFileSync } from 'node:fs';
@@ -167,16 +167,23 @@ export function createProxyServer(accountManager, config, hooks = {}) {
167
167
  // A non-loopback listen host also forces strict even without clients (a shared
168
168
  // pool must never trust by address). Default local config (loopback host, no
169
169
  // clients) keeps today's behavior exactly.
170
- const clientList = Array.isArray(config.proxy?.clients)
171
- ? config.proxy.clients.filter(c => c && typeof c.key === 'string' && c.key)
172
- : [];
170
+ const rawClients = Array.isArray(config.proxy?.clients) ? config.proxy.clients : [];
171
+ const clientList = rawClients.filter(c => c && typeof c.key === 'string' && c.key);
172
+ // Fail CLOSED on intent: a non-empty `clients` list means the operator asked for
173
+ // per-person keys, even if every entry is malformed (hand-edited VM config, a key
174
+ // quoted as a number). Each dropped entry is logged so the typo is visible.
175
+ for (const c of rawClients) {
176
+ if (!(c && typeof c.key === 'string' && c.key)) {
177
+ console.error(`[Maxpool] proxy.clients entry ignored (missing/invalid key): name=${safeText(String(c?.name ?? '?'))}`);
178
+ }
179
+ }
173
180
  const clientByKey = new Map(clientList.map(c => [c.key, c.name]));
174
181
  // '0.0.0.0' stays in the trusted set for backward compatibility (a solo user who
175
182
  // binds every interface keeps keyless local use); it is warned about at startup
176
183
  // because it also exposes the pool to the network. Shared pools set `clients`.
177
184
  const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '::1', '0.0.0.0']);
178
185
  const hostIsLoopback = (config.proxy?.host == null) || LOOPBACK_HOSTS.has(String(config.proxy.host).toLowerCase());
179
- const strictClients = clientByKey.size > 0 || !hostIsLoopback;
186
+ const strictClients = rawClients.length > 0 || !hostIsLoopback;
180
187
  const resolveCaller = (key, isLocal) => {
181
188
  if (key != null && clientByKey.has(key)) return { name: clientByKey.get(key), ok: true };
182
189
  // Legacy single key still works — including strict mode, so a solo user can
@@ -295,11 +302,22 @@ export function createProxyServer(accountManager, config, hooks = {}) {
295
302
  rejectUnauthorized();
296
303
  return;
297
304
  }
298
- const chunks = [];
299
- for await (const c of req) chunks.push(c);
305
+ // An oauth payload is ~2 KB; cap well above that so a key holder can't grow the heap.
306
+ const chunks = []; let bodyBytes = 0;
307
+ for await (const c of req) {
308
+ bodyBytes += c.length;
309
+ if (bodyBytes > 256 * 1024) {
310
+ res.writeHead(413, { 'Content-Type': 'application/json' });
311
+ res.end(JSON.stringify({ ok: false, error: 'too_large' }));
312
+ req.destroy();
313
+ return;
314
+ }
315
+ chunks.push(c);
316
+ }
300
317
  let body;
301
318
  try { body = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { body = null; }
302
319
  const acct = body?.account;
320
+ if (acct && typeof acct.name === 'string') acct.name = safeText(acct.name);
303
321
  if (!acct || acct.type !== 'oauth' || typeof acct.accountUuid !== 'string' || !acct.accountUuid ||
304
322
  typeof acct.refreshToken !== 'string' || !acct.refreshToken || typeof acct.accessToken !== 'string' || !acct.accessToken) {
305
323
  res.writeHead(400, { 'Content-Type': 'application/json' });
package/src/tui.js CHANGED
@@ -52,7 +52,6 @@ function whereCell(a) {
52
52
  function providerLabel(a) {
53
53
  if (a.type === 'pool') return 'Team pool';
54
54
 
55
- if (a._cloud) return (PROVIDER_LABELS[a.provider] || a.provider || 'Cloud').slice(0, PROVIDER_W - 1) + '☁';
56
55
  const key = a.provider || (a.type === 'provider' ? 'provider' : 'anthropic');
57
56
  const label = PROVIDER_LABELS[key] || (key.charAt(0).toUpperCase() + key.slice(1));
58
57
  return label.slice(0, PROVIDER_W);
@@ -1507,7 +1506,6 @@ export class TUI {
1507
1506
  async _sendLoginToRemote(mirror, creds, profile) {
1508
1507
  const remote = mirror.remote;
1509
1508
  const name = remote.remoteName || mirror.name;
1510
- const replace = Boolean(mirror.refreshDead || mirror.status === 'error');
1511
1509
  process.stdout.write(`\n"${name}" lives in the team pool (${remote.linkName}) — sending the fresh login there…\n`);
1512
1510
  const ctl = new AbortController();
1513
1511
  const t = setTimeout(() => ctl.abort(), 20_000);
@@ -1524,14 +1522,11 @@ export class TUI {
1524
1522
  expiresAt: creds.expiresAt,
1525
1523
  source: 'remote-login',
1526
1524
  },
1527
- replace,
1528
1525
  }),
1529
1526
  signal: ctl.signal,
1530
1527
  });
1531
1528
  const json = await res.json().catch(() => ({}));
1532
- if (res.status === 409) {
1533
- process.stdout.write(`\nTeam pool says "${name}" is already healthy — nothing to do. Nothing was saved on this laptop.\n`);
1534
- } else if (res.ok && json.ok) {
1529
+ if (res.ok && json.ok) {
1535
1530
  process.stdout.write(`\nDone: "${name}" ${json.result === 'added' ? 'added to' : 're-authenticated in'} the team pool. Nothing was saved on this laptop.\n`);
1536
1531
  this._addLog(`Remote login: "${name}" → team pool ${remote.linkName} (${json.result})`);
1537
1532
  } else {
@@ -2211,6 +2206,17 @@ export class TUI {
2211
2206
  // A row benched by the duplicate guard renders the CLOUD's live copy (status,
2212
2207
  // bars, in-flight, request counts) — never the stale local snapshot. Identity
2213
2208
  // and name stay local so the row doesn't move.
2209
+ const live = a?.poolBenchedBy ? this.am.remoteRowFor?.(a) : null;
2210
+ if (live) {
2211
+ const r = live.row;
2212
+ a = Object.assign(Object.create(Object.getPrototypeOf(a)), a, {
2213
+ quota: { ...a.quota, ...(r.quota || {}) },
2214
+ inFlight: r.inFlight ?? 0,
2215
+ completedRequests: r.completedRequests ?? a.completedRequests,
2216
+ refreshDead: Boolean(r.refreshDead),
2217
+ rateLimitedUntil: r.rateLimitedUntil ? Date.parse(r.rateLimitedUntil) : null,
2218
+ });
2219
+ }
2214
2220
 
2215
2221
  // Highlight the ACTIVE account(s) — drives BOTH the ► marker and the green
2216
2222
  // "active" status color. In manual mode that's the single pinned account (all
@@ -2250,8 +2256,12 @@ export class TUI {
2250
2256
  // the one running the recovery probe as "probing" and the rest "waiting"
2251
2257
  // (the pool-wide throttle banner above conveys the cause).
2252
2258
  const upstreamBlocking = a.type !== 'provider' && this.am._isUpstreamThrottleBlocking?.();
2253
- let effectiveStatus = a._cloud
2254
- ? (a._cloudOk ? a.status : 'cloud-down')
2259
+ // A mirror row whose link is down/stale is benched by syncRemoteMirrors with
2260
+ // enabled=false — show it as cloud-unreachable, never as "disabled" (which reads
2261
+ // as "I switched this off"). _cloud/_cloudOk were never set; key on a.remote.
2262
+ const linkDown = a.remote && (a.remote.link?.lastError || a.remote.link?.lastOkAt == null);
2263
+ let effectiveStatus = a.remote && (linkDown || a.enabled === false)
2264
+ ? (linkDown ? 'cloud-down' : 'disabled')
2255
2265
  : (a.poolBenchedBy ? 'pool-benched' : (a.enabled === false ? 'disabled' : a.status));
2256
2266
  if (a.enabled !== false && upstreamBlocking && a.status === 'active') {
2257
2267
  effectiveStatus = a.inFlight > 0 ? 'probing' : 'waiting';
@@ -2652,7 +2662,7 @@ export class TUI {
2652
2662
  .map(c => lpadVis(String(c), CW)).join('')));
2653
2663
 
2654
2664
  const link = (this.am.poolLinks || []).find(l => l.lastOkAt);
2655
- out.push(dim(` data since boot${link ? ` · team pool synced ${new Date(link.lastOkAt).toLocaleTimeString()}` : ''}`));
2665
+ out.push(dim(` rolling windows · restarts included${link ? ` · team pool synced ${new Date(link.lastOkAt).toLocaleTimeString()}` : ''}`));
2656
2666
  return out;
2657
2667
  }
2658
2668