@kapybara/zerosub 1.0.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/LICENSE +21 -0
- package/README.md +152 -0
- package/client/accounts-surface.tsx +592 -0
- package/client/add-account.tsx +351 -0
- package/client/commands.ts +112 -0
- package/client/fork-confirm.tsx +57 -0
- package/client/pills.ts +251 -0
- package/client/reset-confirm.tsx +138 -0
- package/client/settings-screen.tsx +120 -0
- package/client/store.ts +139 -0
- package/client/switch-row.tsx +103 -0
- package/client/ui.tsx +231 -0
- package/index.client.tsx +39 -0
- package/index.server.ts +91 -0
- package/package.json +58 -0
- package/paseo-plugin.json +7 -0
- package/server/adapter.ts +126 -0
- package/server/binaries.ts +63 -0
- package/server/claude-resets.ts +192 -0
- package/server/claude.ts +478 -0
- package/server/codex.ts +459 -0
- package/server/families.ts +78 -0
- package/server/handoff.ts +175 -0
- package/server/homes.ts +352 -0
- package/server/json-file.ts +39 -0
- package/server/limits.ts +213 -0
- package/server/machine.ts +17 -0
- package/server/modes.ts +34 -0
- package/server/paths.ts +37 -0
- package/server/process.ts +66 -0
- package/server/reopen.ts +95 -0
- package/server/routing.ts +131 -0
- package/server/service.ts +1692 -0
- package/server/state.ts +177 -0
- package/server/switch-guard.ts +28 -0
- package/server/usage.ts +68 -0
- package/shared/format.ts +99 -0
- package/shared/model.ts +150 -0
- package/shared/preferences.ts +32 -0
- package/shared/rpc.ts +120 -0
- package/shared/timeline.ts +42 -0
package/server/claude.ts
ADDED
|
@@ -0,0 +1,478 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
3
|
+
import { readFile, rm } from "node:fs/promises";
|
|
4
|
+
import { homedir, tmpdir, userInfo } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import type { LoginMethod, Usage, UsageWindow } from "../shared/model";
|
|
7
|
+
import {
|
|
8
|
+
ProgressEmitter,
|
|
9
|
+
spawnEnv,
|
|
10
|
+
type EnvPatch,
|
|
11
|
+
type FamilyAdapter,
|
|
12
|
+
type Identity,
|
|
13
|
+
type LoginHandle,
|
|
14
|
+
type RedeemReply,
|
|
15
|
+
type UsageRead,
|
|
16
|
+
} from "./adapter";
|
|
17
|
+
import { browserCaptureScript, providerCommand } from "./binaries";
|
|
18
|
+
import { CLAUDE_RESET_PROGRAM, describeResetBlock, parseClaudeResets, readClaimReply } from "./claude-resets";
|
|
19
|
+
import { prepareClaudeHome } from "./homes";
|
|
20
|
+
import { detectClaudeLimit, detectClaudeSignOut } from "./limits";
|
|
21
|
+
import { mainClaudeGlobalConfig } from "./paths";
|
|
22
|
+
import { firstUrl, run, stripAnsi } from "./process";
|
|
23
|
+
import { retryDelayMs } from "./usage";
|
|
24
|
+
|
|
25
|
+
const API = "https://api.anthropic.com";
|
|
26
|
+
|
|
27
|
+
function apiHeaders(token: string): Record<string, string> {
|
|
28
|
+
return {
|
|
29
|
+
Authorization: `Bearer ${token}`,
|
|
30
|
+
"anthropic-beta": "oauth-2025-04-20",
|
|
31
|
+
Accept: "application/json",
|
|
32
|
+
"Content-Type": "application/json",
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function isFresh(credentials: Credentials | null): credentials is Credentials {
|
|
37
|
+
return Boolean(credentials?.accessToken) && (!credentials?.expiresAt || credentials.expiresAt > Date.now() + 60_000);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function statusFailure(status: number): RedeemReply {
|
|
41
|
+
if (status === 429) return { outcome: "error", message: "Too many attempts. Wait a minute and try again.", left: null };
|
|
42
|
+
if (status === 401 || status === 403) {
|
|
43
|
+
return { outcome: "error", message: "Claude rejected this account's sign-in. Sign it in again, then retry.", left: null };
|
|
44
|
+
}
|
|
45
|
+
return { outcome: "error", message: `Claude answered with HTTP ${status}. Try again later.`, left: null };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function describe(error: unknown): string {
|
|
49
|
+
return error instanceof Error ? error.message : String(error);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Variables that would make a routed session use something other than its account's own login. */
|
|
53
|
+
const OVERRIDING_AUTH = ["CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY"];
|
|
54
|
+
|
|
55
|
+
export class ClaudeAdapter implements FamilyAdapter {
|
|
56
|
+
readonly family = "claude" as const;
|
|
57
|
+
readonly portable = true;
|
|
58
|
+
/** Anthropic's usage endpoint answers 429 to rapid repeats. */
|
|
59
|
+
readonly usageSpacingMs = 90_000;
|
|
60
|
+
private readonly renewing = new Map<string, Promise<Credentials | null>>();
|
|
61
|
+
private readonly resetNotes = new Map<string, string>();
|
|
62
|
+
|
|
63
|
+
async env(home: string | null): Promise<EnvPatch> {
|
|
64
|
+
if (!home) return { CLAUDE_CONFIG_DIR: null, CLAUDE_SECURESTORAGE_CONFIG_DIR: null };
|
|
65
|
+
// Both point at the home so the keychain entry and refresh locks follow it even when the
|
|
66
|
+
// daemon itself runs with CLAUDE_SECURESTORAGE_CONFIG_DIR set.
|
|
67
|
+
const patch: EnvPatch = { CLAUDE_CONFIG_DIR: home, CLAUDE_SECURESTORAGE_CONFIG_DIR: home };
|
|
68
|
+
for (const key of OVERRIDING_AUTH) if (process.env[key]) patch[key] = "";
|
|
69
|
+
return patch;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async available(): Promise<{ ok: boolean; detail: string | null }> {
|
|
73
|
+
const { command, prefix } = await providerCommand("claude");
|
|
74
|
+
const result = await run(command, [...prefix, "--version"], { timeoutMs: 30_000 });
|
|
75
|
+
if (result.code === 0) return { ok: true, detail: null };
|
|
76
|
+
return { ok: false, detail: (result.stderr || result.stdout).trim().split("\n")[0] || `${command} not found` };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
prepareHome(home: string): Promise<void> {
|
|
80
|
+
return prepareClaudeHome(home);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async identity(home: string | null): Promise<Identity> {
|
|
84
|
+
const { command, prefix } = await providerCommand("claude");
|
|
85
|
+
const result = await run(command, [...prefix, "auth", "status", "--json"], {
|
|
86
|
+
env: spawnEnv(await this.env(home)),
|
|
87
|
+
timeoutMs: 30_000,
|
|
88
|
+
});
|
|
89
|
+
const status = parseJsonObject(result.stdout);
|
|
90
|
+
if (!status) throw new Error(result.stderr.trim() || "Could not read Claude sign-in status");
|
|
91
|
+
const signedIn = status.loggedIn === true;
|
|
92
|
+
const email = str(status.email);
|
|
93
|
+
const orgId = str(status.orgId);
|
|
94
|
+
return {
|
|
95
|
+
signedIn,
|
|
96
|
+
email,
|
|
97
|
+
plan: str(status.subscriptionType),
|
|
98
|
+
organization: str(status.orgName),
|
|
99
|
+
identity: email ? `${orgId ?? "personal"}|${email.toLowerCase()}` : null,
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async usage(home: string | null, options: { renewLogin?: boolean } = {}): Promise<UsageRead> {
|
|
104
|
+
const fetchedAt = new Date().toISOString();
|
|
105
|
+
let credentials = await readCredentials(home).catch(() => null);
|
|
106
|
+
if (!isFresh(credentials) && options.renewLogin) credentials = await this.renewLogin(home);
|
|
107
|
+
const profileScope = !credentials?.scopes || credentials.scopes.includes("user:profile");
|
|
108
|
+
if (credentials?.accessToken && isFresh(credentials) && profileScope) {
|
|
109
|
+
try {
|
|
110
|
+
// The `cedar_ember` read is the one Claude Code's /limit-reset makes: usage plus banked resets.
|
|
111
|
+
const response = await fetch(`${API}/api/oauth/usage?cedar_ember=1&skip_spend=1`, {
|
|
112
|
+
headers: apiHeaders(credentials.accessToken),
|
|
113
|
+
signal: AbortSignal.timeout(15_000),
|
|
114
|
+
});
|
|
115
|
+
if (response.ok) {
|
|
116
|
+
const body = (await response.json()) as { cedar_ember?: unknown };
|
|
117
|
+
const windows = parseUsage(body);
|
|
118
|
+
this.noteResetStatus(home, body.cedar_ember);
|
|
119
|
+
return { fetchedAt, windows, error: null, cached: false, resets: parseClaudeResets(body.cedar_ember).offer };
|
|
120
|
+
}
|
|
121
|
+
// Anthropic rate-limits this endpoint (Claude Code and Paseo read it too). Wait as long as it
|
|
122
|
+
// asks; meanwhile the last reading stays up, or Claude Code's own cached copy if it's newer.
|
|
123
|
+
if (response.status === 429) {
|
|
124
|
+
const retryAt = Date.now() + retryDelayMs(response.headers.get("retry-after"));
|
|
125
|
+
const cached = await cachedUsage(home);
|
|
126
|
+
return { ...(cached ?? { fetchedAt, windows: [], error: null, cached: false, resets: null }), retryAt };
|
|
127
|
+
}
|
|
128
|
+
if (response.status !== 401 && response.status !== 403) {
|
|
129
|
+
return { fetchedAt, windows: [], error: `Usage request failed (HTTP ${response.status})`, cached: false, resets: null };
|
|
130
|
+
}
|
|
131
|
+
} catch (error) {
|
|
132
|
+
return { fetchedAt, windows: [], error: error instanceof Error ? error.message : String(error), cached: false, resets: null };
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
// An idle account's token may have expired; Claude Code refreshes it on next use. Until then,
|
|
136
|
+
// show the last utilisation Claude Code itself cached for this account.
|
|
137
|
+
const cached = await cachedUsage(home);
|
|
138
|
+
if (cached) return cached;
|
|
139
|
+
return { fetchedAt, windows: [], error: "Usage shows up after this account is next used.", cached: false, resets: null };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Logs (only when it changes) why an account does or doesn't show a banked reset. */
|
|
143
|
+
private noteResetStatus(home: string | null, block: unknown): void {
|
|
144
|
+
const key = home ? (home.split(/[\\/]/).pop() ?? home) : "CLI login";
|
|
145
|
+
const note = describeResetBlock(block);
|
|
146
|
+
if (this.resetNotes.get(key) === note) return;
|
|
147
|
+
this.resetNotes.set(key, note);
|
|
148
|
+
console.log(`[ZeroSub] Claude limit resets for ${key}: ${note}`);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Has Claude Code itself refresh an expired sign-in: `claude -p /usage` runs locally (no model
|
|
153
|
+
* call, no cost) and fetches usage with Claude Code's own refresh-and-lock logic. ZeroSub never
|
|
154
|
+
* refreshes tokens itself, so two refreshers can't race and burn a single-use refresh token.
|
|
155
|
+
*/
|
|
156
|
+
private renewLogin(home: string | null): Promise<Credentials | null> {
|
|
157
|
+
const key = home ?? "";
|
|
158
|
+
let pending = this.renewing.get(key);
|
|
159
|
+
if (!pending) {
|
|
160
|
+
pending = (async () => {
|
|
161
|
+
const { command, prefix } = await providerCommand("claude");
|
|
162
|
+
await run(command, [...prefix, "-p", "/usage", "--no-session-persistence", "--output-format", "json"], {
|
|
163
|
+
env: spawnEnv(await this.env(home)),
|
|
164
|
+
cwd: tmpdir(),
|
|
165
|
+
timeoutMs: 90_000,
|
|
166
|
+
});
|
|
167
|
+
return readCredentials(home).catch(() => null);
|
|
168
|
+
})().finally(() => this.renewing.delete(key));
|
|
169
|
+
this.renewing.set(key, pending);
|
|
170
|
+
}
|
|
171
|
+
return pending;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
async redeemReset(home: string | null, options: { onlyAtLimit?: boolean } = {}): Promise<RedeemReply> {
|
|
175
|
+
let credentials = await readCredentials(home).catch(() => null);
|
|
176
|
+
if (!isFresh(credentials)) credentials = await this.renewLogin(home);
|
|
177
|
+
const token = credentials?.accessToken;
|
|
178
|
+
if (!token || !isFresh(credentials)) {
|
|
179
|
+
return { outcome: "error", message: "Couldn't use this account's sign-in. Sign it in again, then retry.", left: null };
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// Ask which grant is next: the server only accepts that one.
|
|
183
|
+
let status: ReturnType<typeof parseClaudeResets>;
|
|
184
|
+
try {
|
|
185
|
+
const response = await fetch(`${API}/api/oauth/usage?cedar_ember=1&skip_spend=1`, {
|
|
186
|
+
headers: apiHeaders(token),
|
|
187
|
+
signal: AbortSignal.timeout(15_000),
|
|
188
|
+
});
|
|
189
|
+
if (!response.ok) return statusFailure(response.status);
|
|
190
|
+
status = parseClaudeResets(((await response.json()) as { cedar_ember?: unknown }).cedar_ember);
|
|
191
|
+
} catch (error) {
|
|
192
|
+
return { outcome: "error", message: `Couldn't check the account's resets: ${describe(error)}`, left: null };
|
|
193
|
+
}
|
|
194
|
+
if (!status.offer || !status.nextGrantId) return { outcome: "none", message: "No banked resets left on this account.", left: 0 };
|
|
195
|
+
if (options.onlyAtLimit && !status.atLimit) {
|
|
196
|
+
// Something refilled the account since the limit hit, e.g. another host sharing it spent a reset.
|
|
197
|
+
return { outcome: "not_limited", message: "Claude says this account has room again, so the reset was kept.", left: status.offer.available };
|
|
198
|
+
}
|
|
199
|
+
if (!status.offer.usableNow) {
|
|
200
|
+
return {
|
|
201
|
+
outcome: "unavailable",
|
|
202
|
+
message: status.offer.blockedReason ?? "The reset can't be used right now.",
|
|
203
|
+
left: status.offer.available,
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const organization = await this.organizationId(home);
|
|
208
|
+
if (!organization) return { outcome: "error", message: "Couldn't tell which Claude organization this account belongs to.", left: null };
|
|
209
|
+
try {
|
|
210
|
+
const response = await fetch(`${API}/api/organizations/${organization}/reset_rate_limits`, {
|
|
211
|
+
method: "POST",
|
|
212
|
+
headers: apiHeaders(token),
|
|
213
|
+
body: JSON.stringify({ program: CLAUDE_RESET_PROGRAM, grant_id: status.nextGrantId, request_id: randomUUID() }),
|
|
214
|
+
signal: AbortSignal.timeout(25_000),
|
|
215
|
+
});
|
|
216
|
+
if (!response.ok) return statusFailure(response.status);
|
|
217
|
+
return readClaimReply(await response.json().catch(() => null));
|
|
218
|
+
} catch (error) {
|
|
219
|
+
return {
|
|
220
|
+
outcome: "error",
|
|
221
|
+
message: `The reset request didn't finish (${describe(error)}), so it may or may not have gone through. Refresh usage before trying again.`,
|
|
222
|
+
left: null,
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** The account's organization UUID, as Claude Code records it. */
|
|
228
|
+
private async organizationId(home: string | null): Promise<string | null> {
|
|
229
|
+
const config = parseJsonObject(await readFile(home ? join(home, ".claude.json") : mainClaudeGlobalConfig(), "utf8").catch(() => ""));
|
|
230
|
+
const account = config?.oauthAccount as { organizationUuid?: unknown } | undefined;
|
|
231
|
+
let id = typeof account?.organizationUuid === "string" ? account.organizationUuid : null;
|
|
232
|
+
if (!id) {
|
|
233
|
+
const { command, prefix } = await providerCommand("claude");
|
|
234
|
+
const result = await run(command, [...prefix, "auth", "status", "--json"], { env: spawnEnv(await this.env(home)), timeoutMs: 30_000 });
|
|
235
|
+
id = str(parseJsonObject(result.stdout)?.orgId);
|
|
236
|
+
}
|
|
237
|
+
return id && /^[0-9a-f-]{8,64}$/i.test(id) ? id : null;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
async login(home: string | null, _method: LoginMethod): Promise<LoginHandle> {
|
|
241
|
+
const { command, prefix } = await providerCommand("claude");
|
|
242
|
+
const shim = await browserCaptureScript();
|
|
243
|
+
const capture = join(tmpdir(), `zerosub-login-${randomBytes(6).toString("hex")}.url`);
|
|
244
|
+
const env = spawnEnv(await this.env(home));
|
|
245
|
+
if (shim) {
|
|
246
|
+
env.BROWSER = shim;
|
|
247
|
+
env.ZEROSUB_BROWSER_OUT = capture;
|
|
248
|
+
}
|
|
249
|
+
return new ClaudeLogin(command, [...prefix, "auth", "login", "--claudeai"], env, shim ? capture : null);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
async logout(home: string): Promise<void> {
|
|
253
|
+
const { command, prefix } = await providerCommand("claude");
|
|
254
|
+
const result = await run(command, [...prefix, "auth", "logout"], { env: spawnEnv(await this.env(home)), timeoutMs: 30_000 });
|
|
255
|
+
if (result.code === 0 || process.platform !== "darwin") return; // Elsewhere the login lives in the home itself.
|
|
256
|
+
// Don't leave a live refresh token behind in the keychain for a home that is about to be deleted.
|
|
257
|
+
await run("/usr/bin/security", ["delete-generic-password", "-a", keychainAccount(), "-s", keychainService(home)], {
|
|
258
|
+
timeoutMs: 10_000,
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
detectLimit = detectClaudeLimit;
|
|
263
|
+
detectSignOut = detectClaudeSignOut;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
class ClaudeLogin extends ProgressEmitter implements LoginHandle {
|
|
267
|
+
readonly finished: Promise<{ ok: boolean; message: string | null }>;
|
|
268
|
+
private readonly child;
|
|
269
|
+
private stdout = "";
|
|
270
|
+
private stderr = "";
|
|
271
|
+
private poll: ReturnType<typeof setInterval> | null = null;
|
|
272
|
+
private canceled = false;
|
|
273
|
+
private exited = false;
|
|
274
|
+
|
|
275
|
+
constructor(command: string, args: string[], env: NodeJS.ProcessEnv, private readonly capture: string | null) {
|
|
276
|
+
super();
|
|
277
|
+
this.child = spawn(command, args, { env, stdio: ["pipe", "pipe", "pipe"] });
|
|
278
|
+
this.child.stdin.on("error", () => undefined);
|
|
279
|
+
this.finished = new Promise((resolve) => {
|
|
280
|
+
this.child.on("error", (error) => {
|
|
281
|
+
this.stop();
|
|
282
|
+
resolve({ ok: false, message: `Could not start Claude Code: ${error.message}` });
|
|
283
|
+
});
|
|
284
|
+
this.child.on("close", (code) => {
|
|
285
|
+
this.exited = true;
|
|
286
|
+
this.stop();
|
|
287
|
+
if (this.canceled) return resolve({ ok: false, message: "Sign-in was canceled." });
|
|
288
|
+
if (code === 0) return resolve({ ok: true, message: null });
|
|
289
|
+
const failure = this.stderr
|
|
290
|
+
.split("\n")
|
|
291
|
+
.map((line) => line.trim())
|
|
292
|
+
.filter(Boolean)
|
|
293
|
+
.reverse()
|
|
294
|
+
.find((line) => /login failed|error/i.test(line));
|
|
295
|
+
resolve({ ok: false, message: friendlyFailure(failure ?? this.stderr.trim()) });
|
|
296
|
+
});
|
|
297
|
+
});
|
|
298
|
+
this.child.stdout.on("data", (chunk: Buffer) => {
|
|
299
|
+
this.stdout += stripAnsi(chunk.toString("utf8"));
|
|
300
|
+
const manual = firstUrl(this.stdout, /\/oauth\/authorize/);
|
|
301
|
+
if (manual && manual !== this.progress.codeUrl) this.update({ codeUrl: manual, step: "waiting" });
|
|
302
|
+
});
|
|
303
|
+
this.child.stderr.on("data", (chunk: Buffer) => {
|
|
304
|
+
const text = stripAnsi(chunk.toString("utf8"));
|
|
305
|
+
this.stderr += text;
|
|
306
|
+
if (/invalid code/i.test(text)) {
|
|
307
|
+
this.update({ message: "That code didn't work. Copy the whole code from the page and paste it again." });
|
|
308
|
+
}
|
|
309
|
+
});
|
|
310
|
+
if (capture) {
|
|
311
|
+
const startedAt = Date.now();
|
|
312
|
+
this.poll = setInterval(() => {
|
|
313
|
+
void readFile(capture, "utf8")
|
|
314
|
+
.then((value) => {
|
|
315
|
+
const url = value.trim();
|
|
316
|
+
if (url.startsWith("http") && url !== this.progress.url) this.update({ url });
|
|
317
|
+
})
|
|
318
|
+
.catch(() => undefined);
|
|
319
|
+
if (Date.now() - startedAt > 20_000 && this.poll) clearInterval(this.poll);
|
|
320
|
+
}, 250);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
async submitCode(code: string): Promise<void> {
|
|
325
|
+
let value = code.trim().replace(/\s+/g, "");
|
|
326
|
+
if (!value) throw new Error("Paste the code from the sign-in page.");
|
|
327
|
+
// The CLI only checks that a `#state` suffix is present; the exchange uses the flow's own state.
|
|
328
|
+
if (!value.includes("#")) value = `${value}#zerosub`;
|
|
329
|
+
if (this.exited) throw new Error("This sign-in has ended. Start again.");
|
|
330
|
+
this.update({ message: "Checking the code…" });
|
|
331
|
+
this.child.stdin.write(`${value}\n`);
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
cancel(): void {
|
|
335
|
+
this.canceled = true;
|
|
336
|
+
this.child.kill("SIGTERM");
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
private stop(): void {
|
|
340
|
+
if (this.poll) clearInterval(this.poll);
|
|
341
|
+
if (this.capture) void rm(this.capture, { force: true });
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function friendlyFailure(message: string): string {
|
|
346
|
+
if (!message) return "Sign-in did not finish.";
|
|
347
|
+
if (/status code 400/i.test(message)) return "That code was rejected. Start again and paste the newest code.";
|
|
348
|
+
return message.replace(/^Login failed:\s*/i, "Sign-in failed: ");
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
// --------------------------------------------------------------------------- credentials (read-only)
|
|
352
|
+
|
|
353
|
+
interface Credentials {
|
|
354
|
+
accessToken: string | null;
|
|
355
|
+
expiresAt: number | null;
|
|
356
|
+
scopes: string[] | null;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
function keychainAccount(): string {
|
|
360
|
+
let name: string;
|
|
361
|
+
try {
|
|
362
|
+
name = process.env.USER || userInfo().username;
|
|
363
|
+
} catch {
|
|
364
|
+
name = "claude-code-user";
|
|
365
|
+
}
|
|
366
|
+
return /^[a-zA-Z0-9._-]+$/.test(name) ? name : "claude-code-user";
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/** Directory that decides where Claude Code keeps credentials for a home. */
|
|
370
|
+
function storageDir(home: string | null): { path: string; hashed: boolean } {
|
|
371
|
+
if (home) return { path: home, hashed: true };
|
|
372
|
+
const secure = process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR;
|
|
373
|
+
if (secure !== undefined) return secure ? { path: secure, hashed: true } : { path: join(homedir(), ".claude"), hashed: false };
|
|
374
|
+
const config = process.env.CLAUDE_CONFIG_DIR;
|
|
375
|
+
return config ? { path: config, hashed: true } : { path: join(homedir(), ".claude"), hashed: false };
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/** Matches Claude Code: "Claude Code-credentials" plus the first 8 hex of sha256(NFC path) for custom dirs. */
|
|
379
|
+
export function keychainService(home: string | null): string {
|
|
380
|
+
const { path, hashed } = storageDir(home);
|
|
381
|
+
if (!hashed) return "Claude Code-credentials";
|
|
382
|
+
return `Claude Code-credentials-${createHash("sha256").update(path.normalize("NFC")).digest("hex").slice(0, 8)}`;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
function parseCredentials(raw: string): Credentials | null {
|
|
386
|
+
let text = raw.trim();
|
|
387
|
+
if (/^[0-9a-f]+$/i.test(text) && text.length % 2 === 0) text = Buffer.from(text, "hex").toString("utf8");
|
|
388
|
+
const parsed = parseJsonObject(text);
|
|
389
|
+
const oauth = parsed?.claudeAiOauth as Record<string, unknown> | undefined;
|
|
390
|
+
if (!oauth) return null;
|
|
391
|
+
return {
|
|
392
|
+
accessToken: str(oauth.accessToken),
|
|
393
|
+
expiresAt: typeof oauth.expiresAt === "number" ? oauth.expiresAt : null,
|
|
394
|
+
scopes: Array.isArray(oauth.scopes) ? oauth.scopes.filter((scope): scope is string => typeof scope === "string") : null,
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/** Reads the account's OAuth token only to ask Anthropic for its usage. Never logged or stored. */
|
|
399
|
+
async function readCredentials(home: string | null): Promise<Credentials | null> {
|
|
400
|
+
if (process.platform === "darwin") {
|
|
401
|
+
const result = await run(
|
|
402
|
+
"/usr/bin/security",
|
|
403
|
+
["find-generic-password", "-a", keychainAccount(), "-w", "-s", keychainService(home)],
|
|
404
|
+
{ timeoutMs: 10_000 },
|
|
405
|
+
);
|
|
406
|
+
if (result.code === 0) {
|
|
407
|
+
const credentials = parseCredentials(result.stdout);
|
|
408
|
+
if (credentials) return credentials;
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
const file = join(storageDir(home).path, ".credentials.json");
|
|
412
|
+
return parseCredentials(await readFile(file, "utf8"));
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
async function cachedUsage(home: string | null): Promise<Usage | null> {
|
|
416
|
+
const config = parseJsonObject(await readFile(home ? join(home, ".claude.json") : mainClaudeGlobalConfig(), "utf8").catch(() => ""));
|
|
417
|
+
const cache = config?.cachedUsageUtilization as { fetchedAtMs?: unknown; utilization?: unknown } | undefined;
|
|
418
|
+
if (!cache || typeof cache.fetchedAtMs !== "number") return null;
|
|
419
|
+
const windows = parseUsage(cache.utilization);
|
|
420
|
+
if (windows.length === 0) return null;
|
|
421
|
+
return { fetchedAt: new Date(cache.fetchedAtMs).toISOString(), windows, error: null, cached: true, resets: null };
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
const WINDOW_LABELS: Array<[key: string, label: string]> = [
|
|
425
|
+
["five_hour", "5-hour"],
|
|
426
|
+
["seven_day", "Weekly"],
|
|
427
|
+
["seven_day_opus", "Weekly · Opus"],
|
|
428
|
+
["seven_day_sonnet", "Weekly · Sonnet"],
|
|
429
|
+
];
|
|
430
|
+
|
|
431
|
+
export function parseUsage(body: unknown): UsageWindow[] {
|
|
432
|
+
if (!body || typeof body !== "object") return [];
|
|
433
|
+
const record = body as Record<string, unknown>;
|
|
434
|
+
const windows: UsageWindow[] = [];
|
|
435
|
+
for (const [key, label] of WINDOW_LABELS) {
|
|
436
|
+
const entry = record[key] as { utilization?: unknown; resets_at?: unknown } | null | undefined;
|
|
437
|
+
if (entry && typeof entry.utilization === "number") {
|
|
438
|
+
windows.push({ id: key, label, usedPercent: entry.utilization, resetsAt: isoDate(entry.resets_at) });
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
if (Array.isArray(record.limits)) {
|
|
442
|
+
for (const limit of record.limits as Array<Record<string, unknown>>) {
|
|
443
|
+
if (limit?.kind !== "weekly_scoped" || typeof limit.percent !== "number") continue;
|
|
444
|
+
const scope = limit.scope as { model?: { display_name?: unknown }; surface?: { display_name?: unknown } } | undefined;
|
|
445
|
+
const name = str(scope?.model?.display_name) ?? str(scope?.surface?.display_name);
|
|
446
|
+
if (!name || windows.some((window) => window.label === `Weekly · ${name}`)) continue;
|
|
447
|
+
windows.push({
|
|
448
|
+
id: `weekly_${name.toLowerCase().replace(/[^a-z0-9]+/g, "_")}`,
|
|
449
|
+
label: `Weekly · ${name}`,
|
|
450
|
+
usedPercent: limit.percent,
|
|
451
|
+
resetsAt: isoDate(limit.resets_at),
|
|
452
|
+
});
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
return windows;
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
function parseJsonObject(text: string): Record<string, unknown> | null {
|
|
459
|
+
const start = text.indexOf("{");
|
|
460
|
+
if (start < 0) return null;
|
|
461
|
+
try {
|
|
462
|
+
const value = JSON.parse(text.slice(start)) as unknown;
|
|
463
|
+
return value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : null;
|
|
464
|
+
} catch {
|
|
465
|
+
return null;
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
function isoDate(value: unknown): string | null {
|
|
470
|
+
const text = str(value);
|
|
471
|
+
if (!text) return null;
|
|
472
|
+
const at = Date.parse(text);
|
|
473
|
+
return Number.isFinite(at) ? new Date(at).toISOString() : null;
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
function str(value: unknown): string | null {
|
|
477
|
+
return typeof value === "string" && value.trim() ? value.trim() : null;
|
|
478
|
+
}
|