tokenmaxxing 1.73.0 → 1.75.0

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": "tokenmaxxing",
3
- "version": "1.73.0",
3
+ "version": "1.75.0",
4
4
  "description": "Automatic Claude Code account switching: pool multiple accounts, start each session on its own account, and resume a session on a fresher account when quota fills.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/cli/serve.ts CHANGED
@@ -130,12 +130,8 @@ async function apiCall(req: Request): Promise<Response> {
130
130
  const method = (call.method ?? "").trim().toUpperCase();
131
131
  if (method === "") return json({ error: "missing method" }, 400);
132
132
  if (!call.url) return json({ error: "missing url" }, 400);
133
- let target: URL;
134
- try {
135
- target = new URL(call.url);
136
- } catch {
137
- return json({ error: "invalid url" }, 400);
138
- }
133
+ const target = URL.parse(call.url);
134
+ if (!target) return json({ error: "invalid url" }, 400);
139
135
  const pool = POOLS.find((p) => p.usageUrl === `${target.origin}${target.pathname}`);
140
136
  if (method !== "GET" || !pool) {
141
137
  return json({ error: `unsupported request: this hub serves ${POOLS.map((p) => `GET ${p.usageUrl}`).join(" and ")} only` }, 400);
@@ -166,16 +162,20 @@ function keyMatches(presented: string, key: string): boolean {
166
162
  return a.length === b.length && timingSafeEqual(a, b);
167
163
  }
168
164
 
169
- async function handle(req: Request, key: string): Promise<Response> {
170
- const url = new URL(req.url);
171
- if (!url.pathname.startsWith(MANAGEMENT_PREFIX)) return json({ error: "not found" }, 404);
165
+ function unauthorized(req: Request, key: string): Response | null {
172
166
  const presented = presentedKey(req);
173
167
  if (presented === "") return json({ error: "missing management key" }, 401);
174
168
  if (!keyMatches(presented, key)) return json({ error: "invalid management key" }, 401);
175
- const route = url.pathname.slice(MANAGEMENT_PREFIX.length);
176
- if (route === "auth-files" && req.method === "GET") return json(authFiles(loadConfig(), Date.now()));
177
- if (route === "api-call" && req.method === "POST") return apiCall(req);
178
- return json({ error: "not found" }, 404);
169
+ return null;
170
+ }
171
+
172
+ function guarded(key: string, handler: (req: Request) => Response | Promise<Response>): (req: Request) => Response | Promise<Response> {
173
+ return (req) => unauthorized(req, key) ?? handler(req);
174
+ }
175
+
176
+ function notFound(req: Request, key: string): Response {
177
+ const url = new URL(req.url);
178
+ return (url.pathname.startsWith(MANAGEMENT_PREFIX) ? unauthorized(req, key) : null) ?? json({ error: "not found" }, 404);
179
179
  }
180
180
 
181
181
  function managementKey(): string {
@@ -204,7 +204,11 @@ export async function cmdServe(args: string[]): Promise<number> {
204
204
  server = Bun.serve({
205
205
  hostname: "localhost",
206
206
  port: cfg.hub.port,
207
- fetch: (req) => handle(req, key),
207
+ routes: {
208
+ [`${MANAGEMENT_PREFIX}auth-files`]: { GET: guarded(key, () => json(authFiles(loadConfig(), Date.now()))) },
209
+ [`${MANAGEMENT_PREFIX}api-call`]: { POST: guarded(key, apiCall) },
210
+ },
211
+ fetch: (req) => notFound(req, key),
208
212
  error: (e) => {
209
213
  log("hub.error", { err: errorMessage(e) });
210
214
  return json({ error: "internal error" }, 500);
@@ -1,5 +1,4 @@
1
1
  import { join } from "node:path";
2
- import { mkdirSync } from "node:fs";
3
2
  import type { z } from "zod";
4
3
  import { codexPaths, optionalEnv } from "../lib/paths.ts";
5
4
  import { writeFileAtomic } from "../lib/atomic.ts";
@@ -50,7 +49,6 @@ async function handleCodexStop(rawStdin: string): Promise<void> {
50
49
  await compactBeforeMove({ sessionId, now });
51
50
  const decision = await evaluateAndMaybeSwap(codex, now);
52
51
  if (decision.swapped && decision.account) {
53
- mkdirSync(codexPaths.respawnDir, { recursive: true });
54
52
  const payload: z.infer<typeof CodexRespawnMarkerSchema> = { accountId: decision.account.id, sessionId, ts: Date.now() };
55
53
  writeFileAtomic(join(codexPaths.respawnDir, supervisorId), JSON.stringify(payload));
56
54
  log("codexstop.marker", { supervisorId: supervisorId.slice(0, 8) });
package/src/lib/claude.ts CHANGED
@@ -3,7 +3,6 @@ import { join } from "node:path";
3
3
  import { z } from "zod";
4
4
  import { readItem, writeItem, deleteItem, isolatedTarget, readStore, storeTarget, claudeAiOauthOnly } from "./credstore.ts";
5
5
  import { resolveRealClaude, resolveVerifiedClaude } from "./claudebin.ts";
6
- import { withClaudeRefreshLock } from "./claudelock.ts";
7
6
  import { ensurePathInRc, hubActivationHint, installSupervisor, managedShellRcSkipLines, shellRcPath, timerActivationHint } from "./install.ts";
8
7
  import { withLock } from "./lock.ts";
9
8
  import { errorMessage, log } from "./log.ts";
@@ -177,7 +176,7 @@ async function login(): Promise<Harvest | null> {
177
176
  await onExit;
178
177
  restoreTermios(savedTermios);
179
178
 
180
- const blobRaw = await withClaudeRefreshLock(onboardDir, () => readItem(iso));
179
+ const blobRaw = await readItem(iso);
181
180
  if (!blobRaw || !identityReady(cjPath)) {
182
181
  console.error(c.red("no login detected in the isolated session - nothing changed."));
183
182
  return null;
@@ -1,4 +1,4 @@
1
- import { existsSync, mkdirSync, readFileSync, realpathSync, statSync } from "node:fs";
1
+ import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
2
2
  import { dirname, join } from "node:path";
3
3
  import { uniq } from "es-toolkit";
4
4
  import { z } from "zod";
@@ -30,7 +30,6 @@ export function wrapperEntryRateTripped(now: number): boolean {
30
30
  entries = entries.filter((t) => now - t < WRAP_RATE_WINDOW_MS);
31
31
  entries.push(now);
32
32
  try {
33
- mkdirSync(paths.home, { recursive: true });
34
33
  writeFileAtomic(file, JSON.stringify({ entries }));
35
34
  } catch { }
36
35
  return entries.length > WRAP_RATE_MAX;
package/src/lib/codex.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { existsSync, mkdirSync, readFileSync, rmSync } from "node:fs";
1
+ import { existsSync, readFileSync, rmSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { writeFileAtomic } from "./atomic.ts";
4
4
  import { MAX_WRAP_DEPTH, WRAP_DEPTH_ENV } from "./claudebin.ts";
@@ -116,7 +116,6 @@ async function login(): Promise<Harvest | null> {
116
116
  const real = resolveRealCodex();
117
117
  const onboardDir = codexPaths.onboardDir;
118
118
  rmSync(onboardDir, { recursive: true, force: true });
119
- mkdirSync(onboardDir, { recursive: true });
120
119
  writeFileAtomic(join(onboardDir, "config.toml"), 'cli_auth_credentials_store = "file"\n');
121
120
 
122
121
  const savedTermios = saveTermios();
@@ -32,7 +32,6 @@ export function codexStoreUsable(accountId: string): boolean {
32
32
  }
33
33
 
34
34
  export function writeCodexStoreAuth(accountId: string, auth: CodexAuthJson): void {
35
- mkdirSync(codexStoreDirFor(accountId), { recursive: true });
36
35
  writeFileAtomic(codexAuthJsonFor(accountId), JSON.stringify(CodexAuthJsonSchema.parse(auth), null, 2), 0o600);
37
36
  }
38
37
 
package/src/lib/grok.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { mkdirSync, readFileSync } from "node:fs";
1
+ import { readFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { z } from "zod";
4
4
  import { writeFileAtomic } from "./atomic.ts";
@@ -31,7 +31,6 @@ function harvestOf(id: string, key: string, entry: GrokAuthEntry): Harvest {
31
31
  tier: null,
32
32
  sample: null,
33
33
  park: async () => {
34
- mkdirSync(grokStoreDirFor(id), { recursive: true });
35
34
  writeFileAtomic(grokAuthJsonFor(id), JSON.stringify({ [key]: entry }, null, 2), 0o600);
36
35
  },
37
36
  };
@@ -1,4 +1,4 @@
1
- import { accessSync, appendFileSync, constants, existsSync, mkdirSync, readFileSync, realpathSync, rmSync, statSync } from "node:fs";
1
+ import { accessSync, appendFileSync, constants, existsSync, readFileSync, realpathSync, rmSync, statSync } from "node:fs";
2
2
  import { userInfo } from "node:os";
3
3
  import { basename, dirname, join, resolve } from "node:path";
4
4
  import { escape } from "es-toolkit";
@@ -89,7 +89,6 @@ exec ${JSON.stringify(bun)} --no-env-file run ${JSON.stringify(entry)} "$@"
89
89
  }
90
90
 
91
91
  export function installSupervisor(): InstallOutcome {
92
- mkdirSync(paths.binDir, { recursive: true });
93
92
  const target = installedBin();
94
93
  const entry = realpathSync(Bun.main);
95
94
  if (isNixPackaged()) {
@@ -147,7 +146,6 @@ export function installCodexStopHook(): void {
147
146
  ],
148
147
  },
149
148
  };
150
- mkdirSync(codexPaths.home, { recursive: true });
151
149
  writeFileAtomic(codexPaths.hooksJson, JSON.stringify(next, null, 2) + "\n");
152
150
  }
153
151
 
@@ -198,7 +196,6 @@ export function codexSupervisorLink(): string {
198
196
  }
199
197
 
200
198
  export function installCodexSupervisor(): void {
201
- mkdirSync(paths.binDir, { recursive: true });
202
199
  writeFileAtomic(codexSupervisorLink(), `#!/bin/sh\nexec ${JSON.stringify(installedBin())} __supervise-codex "$@"\n`, 0o755);
203
200
  installCodexStopHook();
204
201
  }
@@ -1,4 +1,4 @@
1
- import { mkdirSync, readFileSync } from "node:fs";
1
+ import { readFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { z } from "zod";
4
4
  import { writeFileAtomic } from "./atomic.ts";
@@ -29,7 +29,6 @@ function harvestOf(key: string): Harvest {
29
29
  tier: "go",
30
30
  sample: null,
31
31
  park: async () => {
32
- mkdirSync(opencodeGoStoreDirFor(id), { recursive: true });
33
32
  writeFileAtomic(opencodeGoAuthJsonFor(id), JSON.stringify({ "opencode-go": { type: "api", key } }, null, 2), 0o600);
34
33
  },
35
34
  };
package/src/lib/paths.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { homedir } from "node:os";
1
+ import { homedir, userInfo } from "node:os";
2
2
  import { join } from "node:path";
3
3
  import { z } from "zod";
4
4
 
@@ -123,8 +123,20 @@ export function opencodeGoAuthJsonFor(accountId: string): string {
123
123
  return join(opencodeGoStoreDirFor(accountId), "auth.json");
124
124
  }
125
125
 
126
+ const CLAUDE_KEYCHAIN_ACCOUNT_PATTERN = /^[a-zA-Z0-9._-]+$/;
127
+
128
+ function claudeKeychainAccount(): string {
129
+ let name: string;
130
+ try {
131
+ name = process.env.USER || userInfo().username;
132
+ } catch {
133
+ return "claude-code-user";
134
+ }
135
+ return CLAUDE_KEYCHAIN_ACCOUNT_PATTERN.test(name) ? name : "claude-code-user";
136
+ }
137
+
126
138
  export const keychain = {
127
- account: env("TOKENMAXXING_KEYCHAIN_ACCOUNT", process.env.USER ?? "unknown"),
139
+ account: optionalEnv("TOKENMAXXING_KEYCHAIN_ACCOUNT") ?? claudeKeychainAccount(),
128
140
  } as const;
129
141
 
130
142
  export function shortId(accountId: string): string {
@@ -1,4 +1,4 @@
1
- import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from "node:fs";
1
+ import { existsSync, readdirSync, readFileSync, rmSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { z } from "zod";
4
4
  import { writeFileAtomic } from "./atomic.ts";
@@ -14,7 +14,6 @@ const PresenceSchema = z.object({
14
14
  export function writePresence(input: { dir: string; id: string; accountId: string; pid: number }): void {
15
15
  const startedAt = pidStartTime(input.pid);
16
16
  if (startedAt == null) throw new Error(`could not read pid ${input.pid}'s start time (ps lstart) - refusing to write an unverifiable presence file`);
17
- mkdirSync(input.dir, { recursive: true });
18
17
  writeFileAtomic(join(input.dir, input.id), JSON.stringify(PresenceSchema.parse({ accountId: input.accountId, pid: input.pid, startedAt })));
19
18
  }
20
19
 
@@ -1,4 +1,4 @@
1
- import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, type Dirent } from "node:fs";
1
+ import { existsSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, type Dirent } from "node:fs";
2
2
  import { basename, join, sep } from "node:path";
3
3
  import { z } from "zod";
4
4
  import { errorMessage, log } from "./log.ts";
@@ -19,7 +19,6 @@ function sessionFile(sid: string): string {
19
19
  }
20
20
 
21
21
  export function saveSessionFlags(sid: string, flags: string[], cwd: string): void {
22
- mkdirSync(sessionsDir(), { recursive: true });
23
22
  writeFileAtomic(sessionFile(sid), JSON.stringify({ flags, cwd }));
24
23
  }
25
24
 
@@ -39,7 +38,6 @@ export function liveSessionId(sid: string): string {
39
38
 
40
39
  function recordLiveSession(sid: string, current: string): void {
41
40
  const session = loadSession(sid);
42
- mkdirSync(sessionsDir(), { recursive: true });
43
41
  writeFileAtomic(sessionFile(sid), JSON.stringify({ flags: session?.flags ?? [], cwd: session?.cwd ?? process.cwd(), current }));
44
42
  }
45
43
 
@@ -126,7 +124,6 @@ export function adoptLiveSession(session: SupervisedSession, stdinSid: string |
126
124
  }
127
125
 
128
126
  export function writeRespawnMarker(input: { session: SupervisedSession; accountId: string; waitUntil: number; compact: boolean }): void {
129
- mkdirSync(paths.respawnDir, { recursive: true });
130
127
  const payload: z.infer<typeof RespawnMarkerSchema> = {
131
128
  accountId: input.accountId,
132
129
  ts: Date.now(),
@@ -1,105 +0,0 @@
1
- import { mkdirSync, realpathSync, rmdirSync, statSync, utimesSync } from "node:fs";
2
- import { join } from "node:path";
3
- import { delay } from "es-toolkit";
4
- import { errorMessage, log } from "./log.ts";
5
- import { ErrnoSchema } from "./types.ts";
6
-
7
- const STALE_MS = 60_000;
8
- const HEARTBEAT_MS = 5_000;
9
- const ATTEMPTS = 5;
10
- const RETRY_MS = 1_000;
11
-
12
- function tryAcquire(lockDir: string): boolean {
13
- try {
14
- mkdirSync(lockDir);
15
- return true;
16
- } catch (e) {
17
- if (ErrnoSchema.safeParse(e).data?.code !== "EEXIST") throw e;
18
- }
19
- try {
20
- if (Date.now() - statSync(lockDir).mtimeMs > STALE_MS) {
21
- rmdirSync(lockDir);
22
- mkdirSync(lockDir);
23
- return true;
24
- }
25
- } catch { }
26
- return false;
27
- }
28
-
29
- export async function withClaudeRefreshLock<T>(
30
- dir: string,
31
- fn: (lock: { compromised: () => boolean }) => Promise<T> | T,
32
- opts: { attempts?: number; retryMs?: number; heartbeatMs?: number } = {},
33
- ): Promise<T> {
34
- const attempts = opts.attempts ?? ATTEMPTS;
35
- const retryMs = opts.retryMs ?? RETRY_MS;
36
- mkdirSync(dir, { recursive: true });
37
- const primary = join(dir, ".oauth_refresh.lock");
38
- let legacyRoot = dir;
39
- try { legacyRoot = realpathSync(dir); } catch { }
40
- const legacy = `${legacyRoot}.lock`;
41
-
42
- const held: string[] = [];
43
- for (let attempt = 1; held.length === 0; attempt++) {
44
- if (tryAcquire(primary)) {
45
- try {
46
- if (tryAcquire(legacy)) {
47
- held.push(legacy, primary);
48
- break;
49
- }
50
- } catch (e) {
51
- log("claudelock.legacy_error", { err: errorMessage(e) });
52
- held.push(primary);
53
- break;
54
- }
55
- rmdirSync(primary);
56
- }
57
- if (attempt >= attempts) {
58
- log("claudelock.contested", { attempts: attempt });
59
- throw new Error(
60
- "claude's credential-refresh lock is contested (a token refresh is likely mid-flight) - not touching the credential store; retry shortly",
61
- );
62
- }
63
- await delay(retryMs + Math.random() * retryMs);
64
- }
65
-
66
- const ours = new Map<string, number>();
67
- for (const d of held) ours.set(d, statSync(d).mtimeMs);
68
- let compromised = false;
69
- const markCompromised = () => {
70
- if (!compromised) {
71
- compromised = true;
72
- log("claudelock.compromised", {});
73
- }
74
- };
75
- const heartbeat = setInterval(() => {
76
- const now = new Date();
77
- for (const d of held) {
78
- try {
79
- if (statSync(d).mtimeMs !== ours.get(d)) {
80
- markCompromised();
81
- continue;
82
- }
83
- utimesSync(d, now, now);
84
- ours.set(d, statSync(d).mtimeMs);
85
- } catch {
86
- markCompromised();
87
- }
88
- }
89
- }, opts.heartbeatMs ?? HEARTBEAT_MS);
90
-
91
- try {
92
- const result = await fn({ compromised: () => compromised });
93
- if (compromised) {
94
- throw new Error("claude's credential-refresh lock was reclaimed while held (this process stalled past the 60s stale bar) - treat this critical section as failed");
95
- }
96
- return result;
97
- } finally {
98
- clearInterval(heartbeat);
99
- for (const d of held) {
100
- try {
101
- if (statSync(d).mtimeMs === ours.get(d)) rmdirSync(d);
102
- } catch { }
103
- }
104
- }
105
- }