ccdeck 1.43.0 → 1.45.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/README.md +210 -12
- package/bin/agent-dag.js +505 -0
- package/bin/deck.js +1051 -0
- package/dist/web/assets/index-Bdl1LX0-.css +1 -0
- package/dist/web/assets/index-jXBjwwZC.js +89 -0
- package/dist/web/index.html +49 -0
- package/hook/hook.js +496 -0
- package/package.json +42 -9
- package/src/server/args.mjs +156 -0
- package/src/server/brand.mjs +16 -0
- package/src/server/ccusage.mjs +1052 -0
- package/src/server/claude-accounts.mjs +653 -0
- package/src/server/claude-dir.mjs +213 -0
- package/src/server/codex-auth.mjs +388 -0
- package/src/server/codex-dir.mjs +171 -0
- package/src/server/codex-quota.mjs +445 -0
- package/src/server/codex-usage.mjs +411 -0
- package/src/server/cswap-admin.mjs +1034 -0
- package/src/server/cswap-auto.mjs +595 -0
- package/src/server/cswap-install.mjs +583 -0
- package/src/server/exec.mjs +938 -0
- package/src/server/index.mjs +5109 -0
- package/src/server/installer.mjs +763 -0
- package/src/server/invoked-as.mjs +144 -0
- package/src/server/log-writer.mjs +283 -0
- package/src/server/npx.mjs +259 -0
- package/src/server/quota.mjs +684 -0
- package/src/server/reset-label.mjs +78 -0
- package/src/server/retire-sound-hook.mjs +315 -0
- package/src/server/self-update.mjs +1331 -0
- package/src/server/supervisor.mjs +302 -0
- package/src/server/system-metrics.mjs +619 -0
- package/src/server/term.mjs +570 -0
- package/src/server/uv-bootstrap.mjs +301 -0
- package/bin/ccdeck.js +0 -194
|
@@ -0,0 +1,1034 @@
|
|
|
1
|
+
// Everything the accounts panel does that CHANGES the claude-swap store.
|
|
2
|
+
//
|
|
3
|
+
// Reading it lives in claude-accounts.mjs. This is the other half: signing a
|
|
4
|
+
// new account in, sharing one to another machine, and the small edits —
|
|
5
|
+
// rename, reorder, remove.
|
|
6
|
+
//
|
|
7
|
+
// Two constraints from claude-swap's own source shape all of it.
|
|
8
|
+
//
|
|
9
|
+
// `cswap add` does not sign anyone in. It captures whatever is already live —
|
|
10
|
+
// identity from ~/.claude.json, credentials from the macOS Keychain item
|
|
11
|
+
// "Claude Code-credentials". So a browser login has to land in Claude Code's
|
|
12
|
+
// own store first, which is exactly what `claude auth login` does, and the
|
|
13
|
+
// panel's job is to drive that conversation rather than to invent one.
|
|
14
|
+
//
|
|
15
|
+
// And `cswap add` takes no lock while assigning the next slot as max+1. Two
|
|
16
|
+
// concurrent adds pick the same number and the second write silently drops the
|
|
17
|
+
// first account's record. Nothing upstream prevents it, so every mutation here
|
|
18
|
+
// goes through one mutex.
|
|
19
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
20
|
+
import { existsSync } from "node:fs";
|
|
21
|
+
import { readFile } from "node:fs/promises";
|
|
22
|
+
import { homedir } from "node:os";
|
|
23
|
+
import { join } from "node:path";
|
|
24
|
+
import { looksMissing, pathLookup, run, runDetached, runInteractive } from "./exec.mjs";
|
|
25
|
+
import { backupRoot, invalidateClaudeAccountsCache } from "./claude-accounts.mjs";
|
|
26
|
+
import { claudeCliCandidates } from "./claude-dir.mjs";
|
|
27
|
+
import { cswapBin } from "./cswap-install.mjs";
|
|
28
|
+
import { PRODUCT } from "./brand.mjs";
|
|
29
|
+
|
|
30
|
+
// An OAuth code is short-lived at the source; there is no point holding a child
|
|
31
|
+
// open longer than a user would plausibly take to fetch one.
|
|
32
|
+
const LOGIN_TIMEOUT_MS = 5 * 60_000;
|
|
33
|
+
const CSWAP_TIMEOUT_MS = 60_000;
|
|
34
|
+
// How long to wait for the CLI's verdict on a pasted code before saying so.
|
|
35
|
+
// Exchanging a code is one HTTPS round trip; a minute is generous.
|
|
36
|
+
const CODE_VERDICT_MS = 60_000;
|
|
37
|
+
// How long a shared account stays importable. Long enough to walk to the other
|
|
38
|
+
// machine, short enough that a copy left in clipboard history goes stale.
|
|
39
|
+
export const SHARE_TTL_MS = 10 * 60_000;
|
|
40
|
+
const SHARE_PREFIX = "ccdeck1:";
|
|
41
|
+
|
|
42
|
+
// ── serialization ────────────────────────────────────────────────────────────
|
|
43
|
+
|
|
44
|
+
let _chain = Promise.resolve();
|
|
45
|
+
|
|
46
|
+
// Whether the code running right now is itself the mutation holding the lock.
|
|
47
|
+
// Async context rather than a plain boolean, which could not tell that apart
|
|
48
|
+
// from another request that merely arrived while the lock was held — and would
|
|
49
|
+
// wave that one through, which is the opposite of a mutex.
|
|
50
|
+
const _holder = new AsyncLocalStorage();
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* One store mutation at a time.
|
|
54
|
+
*
|
|
55
|
+
* Not defence against another process — that would need claude-swap's own file
|
|
56
|
+
* lock, which `add` does not take either. This is defence against ourselves:
|
|
57
|
+
* two browser tabs, or a double-click, are enough to race a slot assignment.
|
|
58
|
+
*
|
|
59
|
+
* Re-entrant, because a mutation that reaches for the lock from inside one
|
|
60
|
+
* would otherwise wait for itself forever: the chain cannot advance past the
|
|
61
|
+
* outer link until it settles, and the outer link is blocked on this call. It
|
|
62
|
+
* already has exclusive access, so it simply runs.
|
|
63
|
+
*/
|
|
64
|
+
export function withStoreLock(fn) {
|
|
65
|
+
if (_holder.getStore()) return Promise.resolve().then(fn);
|
|
66
|
+
const held = () => _holder.run(true, fn);
|
|
67
|
+
const next = _chain.then(held, held);
|
|
68
|
+
// Keep the chain alive even when a link rejects, or every later mutation
|
|
69
|
+
// inherits the failure.
|
|
70
|
+
_chain = next.then(() => {}, () => {});
|
|
71
|
+
return next;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// ── shared helpers ───────────────────────────────────────────────────────────
|
|
75
|
+
|
|
76
|
+
// cswapBin comes from cswap-install.mjs, which searches the places uv and pipx
|
|
77
|
+
// actually install to. This module used to answer the bare name "cswap"
|
|
78
|
+
// instead, which is fine on a Mac where ~/.local/bin is usually on PATH and
|
|
79
|
+
// wrong on Windows where it is usually not: every mutation here — share,
|
|
80
|
+
// import, remove, rename, reorder — failed with cmd.exe's "is not recognized",
|
|
81
|
+
// while the read-only half of the panel worked, because it was already using
|
|
82
|
+
// the resolver. Reported from Windows on 2026-08-14.
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Which `claude` the account surface runs: the configured one, else the first
|
|
86
|
+
* candidate this machine actually has, else the bare name.
|
|
87
|
+
*
|
|
88
|
+
* WHY THIS IS NOT `AGENTS_DECK_CLAUDE ?? "claude"` ANY MORE (#570). That was
|
|
89
|
+
* the whole of this module's resolution, and it feeds every child the accounts
|
|
90
|
+
* panel starts — `claude auth status --json` for `currentIdentity`, and the
|
|
91
|
+
* `claude auth login` whose output the sign-in dialog reads a link out of. On a
|
|
92
|
+
* machine whose `claude` is at `~/.local/bin/claude` but whose deck was started
|
|
93
|
+
* from something that never sourced a shell rc — a LaunchAgent, a systemd user
|
|
94
|
+
* unit, pm2, a desktop shortcut — the bare name is an ENOENT, so the login
|
|
95
|
+
* child is dead within milliseconds, the flow reports `no_url`, and the dialog
|
|
96
|
+
* shows "the claude CLI could not be run: not on PATH. Set AGENTS_DECK_CLAUDE
|
|
97
|
+
* to its full path." That sentence is a real remedy and it is why this was a
|
|
98
|
+
* smaller bug than #553; it is still a request to spell out a path the deck had
|
|
99
|
+
* already found for itself, because `hasClaudeInstalled()` stat'ed that exact
|
|
100
|
+
* file at boot to decide this was a Claude machine, and since #553 the quota
|
|
101
|
+
* panel beside this one runs the same binary without being told anything.
|
|
102
|
+
*
|
|
103
|
+
* SO IT READS THE SAME LIST, ON THE SAME TERMS #553 SETTLED ON. The list is
|
|
104
|
+
* `claudeCliCandidates` in claude-dir.mjs, whose other two readers are
|
|
105
|
+
* `hasClaudeInstalled()` — the boot question this module's whole surface hangs
|
|
106
|
+
* off — and `quotaClaudeBin` in quota.mjs. This is the same question at a third
|
|
107
|
+
* site, so nothing here is decided again:
|
|
108
|
+
*
|
|
109
|
+
* - AGENTS_DECK_CLAUDE first, and it is the one thing that skips the list
|
|
110
|
+
* entirely. It is documented in the README as "full path to the `claude`
|
|
111
|
+
* CLI", it is what the failure message above tells people to set, and
|
|
112
|
+
* someone who set it has already been through this once — second-guessing
|
|
113
|
+
* them with a stat would be answering a question they have closed. An empty
|
|
114
|
+
* value reads as unset, the way `AGENTS_DECK_CSWAP` does in cswapBin.
|
|
115
|
+
* - Then the candidate list's own order, unchanged: PATH first on POSIX, the
|
|
116
|
+
* two known install directories first on Windows. Preferring a different
|
|
117
|
+
* copy would silently change which binary signs somebody in on every
|
|
118
|
+
* machine that has two, and a `claude auth login` that suddenly runs a
|
|
119
|
+
* different binary is a credential path, not a detail.
|
|
120
|
+
* - The bare name is only answered with when PATH actually holds it, and
|
|
121
|
+
* `pathLookup` is a yes/no gate rather than the path it found, so spawn's
|
|
122
|
+
* own resolution — and, on Windows, exec.mjs's PATHEXT walk, since `claude`
|
|
123
|
+
* there is `claude.exe` or `claude.cmd` and never the bare word — stays in
|
|
124
|
+
* charge of the PATH case exactly as before.
|
|
125
|
+
* - The absolute candidates are stat'ed only once PATH has come up empty, so
|
|
126
|
+
* the common case costs one stat rather than a directory walk. Against what
|
|
127
|
+
* follows it — a whole Claude Code process, and a browser sign-in a human
|
|
128
|
+
* is walking through — that is not a cost worth naming.
|
|
129
|
+
*
|
|
130
|
+
* Pure, with the platform, environment, home directory and existence check all
|
|
131
|
+
* parameters, so the Windows branch is checkable from the platforms this repo
|
|
132
|
+
* is actually developed on. Exported for that test rather than for a caller
|
|
133
|
+
* (#383): `claudeBin` below is the only one, and it hands back the real
|
|
134
|
+
* machine's answer.
|
|
135
|
+
*/
|
|
136
|
+
export function adminClaudeBin(platform = process.platform, env = process.env,
|
|
137
|
+
home = homedir(), exists = existsSync) {
|
|
138
|
+
if (env.AGENTS_DECK_CLAUDE) return env.AGENTS_DECK_CLAUDE;
|
|
139
|
+
const sep = platform === "win32" ? "\\" : "/";
|
|
140
|
+
// process.env is case-insensitive on Windows; an injected plain object in a
|
|
141
|
+
// test is not, and %Path% is how the variable is actually spelled there.
|
|
142
|
+
const pathEnv = env.PATH ?? env.Path ?? env.path ?? "";
|
|
143
|
+
for (const c of claudeCliCandidates(platform, env, home)) {
|
|
144
|
+
if (c.includes(sep)) { if (exists(c)) return c; }
|
|
145
|
+
else if (pathLookup(c, platform, { pathEnv, exists })) return c;
|
|
146
|
+
}
|
|
147
|
+
// Nothing on PATH and nothing at any known install directory. The bare name
|
|
148
|
+
// is still the right last resort — POSIX `execvp` and cmd.exe's own search
|
|
149
|
+
// both deserve their turn at a layout no list here knows — and the ENOENT it
|
|
150
|
+
// produces is what failureText turns into the AGENTS_DECK_CLAUDE sentence.
|
|
151
|
+
return "claude";
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
async function claudeBin() {
|
|
155
|
+
return adminClaudeBin();
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Slot → email for everything currently in the store, plus the active slot. */
|
|
159
|
+
export async function readStore() {
|
|
160
|
+
try {
|
|
161
|
+
const seq = JSON.parse(await readFile(join(backupRoot(), "sequence.json"), "utf8"));
|
|
162
|
+
const accounts = seq?.accounts ?? {};
|
|
163
|
+
return {
|
|
164
|
+
slots: Object.keys(accounts),
|
|
165
|
+
emails: Object.fromEntries(Object.entries(accounts).map(([k, v]) => [k, v?.email ?? ""])),
|
|
166
|
+
activeNum: seq?.activeAccountNumber ?? null,
|
|
167
|
+
};
|
|
168
|
+
} catch {
|
|
169
|
+
return { slots: [], emails: {}, activeNum: null };
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Which slot appeared between two store reads.
|
|
175
|
+
*
|
|
176
|
+
* `cswap add --json` is rejected by argparse (exit 2), so its human output is
|
|
177
|
+
* the only thing it offers and parsing that would break on any wording change.
|
|
178
|
+
* The store is the fact. `null` means nothing new — which is not a failure: an
|
|
179
|
+
* account already present is refreshed in place, on its existing slot.
|
|
180
|
+
*/
|
|
181
|
+
export function newSlot(before, after) {
|
|
182
|
+
const had = new Set(before.slots);
|
|
183
|
+
const fresh = after.slots.filter(s => !had.has(s));
|
|
184
|
+
return fresh.length === 1 ? fresh[0] : null;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Anthropic's own view of who is signed in. Null when it cannot be read.
|
|
189
|
+
*
|
|
190
|
+
* Exported for its test rather than for a caller (#383). Both callers are inside
|
|
191
|
+
* the login flow and neither can show what was parsed: `spawnLogin` keeps only
|
|
192
|
+
* `identity?.email` as the address to restore to, and `submitLoginCode` turns
|
|
193
|
+
* the whole thing into a pass/fail — a null there is the difference between a
|
|
194
|
+
* sign-in the deck accepts and one it reports as "signed in, but the claude CLI
|
|
195
|
+
* still reports nobody logged in". The success path, where the email read here
|
|
196
|
+
* is what matches the new credential to a cswap slot, is reachable only with a
|
|
197
|
+
* real signed-in CLI on the machine running the suite. See
|
|
198
|
+
* cswap-identity.test.ts.
|
|
199
|
+
*/
|
|
200
|
+
export async function currentIdentity() {
|
|
201
|
+
const r = await run(await claudeBin(), ["auth", "status", "--json"], { timeout: 20_000 });
|
|
202
|
+
if (!r.ok) return null;
|
|
203
|
+
try {
|
|
204
|
+
const j = JSON.parse(r.stdout);
|
|
205
|
+
return j?.loggedIn ? { email: j.email ?? "", orgId: j.orgId ?? "" } : null;
|
|
206
|
+
} catch {
|
|
207
|
+
return null;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// ── login ────────────────────────────────────────────────────────────────────
|
|
212
|
+
|
|
213
|
+
// `claude auth login` prints the link as an OSC-8 hyperlink: ESC ] 8 ; ; <url>
|
|
214
|
+
// BEL, then the visible text — which is the same url again — then an empty
|
|
215
|
+
// closer. Verified byte for byte against real output: two `\x1b]8;;`, both
|
|
216
|
+
// terminated by BEL, never the ESC-backslash form.
|
|
217
|
+
//
|
|
218
|
+
// So the url appears TWICE, back to back, and a naive /https:\/\/\S+/ captures
|
|
219
|
+
// them joined into one unusable string. Stripping the escape sequences takes
|
|
220
|
+
// the link target away with them and leaves the visible copy, once.
|
|
221
|
+
const OSC8 = /\x1b\]8;;[^\x07\x1b]*(?:\x07|\x1b\\)/g;
|
|
222
|
+
const ANSI = /\x1b\[[0-9;?]*[ -/]*[@-~]/g;
|
|
223
|
+
|
|
224
|
+
export function stripTerminalEscapes(text) {
|
|
225
|
+
return String(text ?? "").replace(OSC8, "").replace(ANSI, "");
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** The sign-in URL out of `claude auth login`'s output, or null. */
|
|
229
|
+
export function extractLoginUrl(text) {
|
|
230
|
+
const clean = stripTerminalEscapes(text);
|
|
231
|
+
const m = clean.match(/https:\/\/[^\s'"]*\/oauth\/authorize\?[^\s'"]+/);
|
|
232
|
+
return m ? m[0] : null;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// The prompt the CLI blocks on. Matched rather than assumed: writing a code
|
|
236
|
+
// into a child that is not asking for one would send it somewhere unknown.
|
|
237
|
+
const CODE_PROMPT = /paste code here/gi;
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* How many times one line of output asks for the code.
|
|
241
|
+
*
|
|
242
|
+
* Per LINE, not per delivery. The prompt ends without a newline, so exec.mjs
|
|
243
|
+
* re-offers the same unterminated line on every chunk as it grows — and both
|
|
244
|
+
* streams share that buffer, so a progress dot, a `\r` spinner frame on stderr,
|
|
245
|
+
* or simply the prompt split across two writes all arrive as the ask again,
|
|
246
|
+
* a few characters longer. Counting an ask whenever the text merely CHANGED, as
|
|
247
|
+
* this used to, turned any of those into a phantom second prompt, and a second
|
|
248
|
+
* prompt is exactly how submitLoginCode hears "that code was rejected": a
|
|
249
|
+
* login the CLI was busy completing came back as `code_rejected`, with the
|
|
250
|
+
* account unregistered and the live credentials left switched.
|
|
251
|
+
*
|
|
252
|
+
* A real re-ask writes the prompt again — on a fresh line, or after a `\r`
|
|
253
|
+
* redraw of this one — so it shows up as another match, not as a longer tail.
|
|
254
|
+
*/
|
|
255
|
+
export function countCodePrompts(line) {
|
|
256
|
+
return (stripTerminalEscapes(line).match(CODE_PROMPT) ?? []).length;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* The whole login, as one object, because the browser talks to it twice: once
|
|
261
|
+
* to start and get a URL, once to hand back the code.
|
|
262
|
+
*
|
|
263
|
+
* `previousActive` is captured before anything happens. `cswap add` sets
|
|
264
|
+
* activeAccountNumber to whatever it just added, so without this the machine
|
|
265
|
+
* silently changes account underneath every running session.
|
|
266
|
+
*/
|
|
267
|
+
let _login = null;
|
|
268
|
+
|
|
269
|
+
// A start that has not published its flow yet.
|
|
270
|
+
//
|
|
271
|
+
// `_login` is only assigned once the child exists, and everything before that
|
|
272
|
+
// awaits — a store read, then `claude auth status`, which shells out and takes
|
|
273
|
+
// hundreds of milliseconds. Two requests overlapping inside that window (two
|
|
274
|
+
// tabs, or a double-submitted POST) therefore both read `_login` as null, both
|
|
275
|
+
// walked past the guards below, and both spawned `claude auth login`. Only the
|
|
276
|
+
// later assignment stayed reachable, so the other child — holding an open OAuth
|
|
277
|
+
// flow and an open stdin — was beyond cancelLogin and beyond the dialog's
|
|
278
|
+
// Escape, and ran on invisibly until its five-minute timeout. Concurrent starts
|
|
279
|
+
// share the one spawn instead, the promise guard ccusage.mjs uses to share an
|
|
280
|
+
// install.
|
|
281
|
+
let _starting = null;
|
|
282
|
+
|
|
283
|
+
export function loginState() {
|
|
284
|
+
if (!_login) return { state: "idle" };
|
|
285
|
+
const { state, url, error, account, expiresAt } = _login;
|
|
286
|
+
return { state, url: url ?? null, error: error ?? null, account: account ?? null, expiresAt: expiresAt ?? null };
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* What an address may be made of before it becomes an argv element.
|
|
291
|
+
*
|
|
292
|
+
* NOT AN RFC 5322 PARSER, and it should not be read as one. RFC 5322 permits
|
|
293
|
+
* quoted local parts, spaces inside them, comments in parentheses and bracketed
|
|
294
|
+
* address literals; a regex that accepted all of that would accept precisely the
|
|
295
|
+
* shapes this exists to keep out. The job here is narrower and worth stating
|
|
296
|
+
* plainly: keep a FLAG-SHAPED or WHITESPACE-BEARING string out of a spawn's
|
|
297
|
+
* argument vector. Anything it wrongly refuses is an address nobody has ever
|
|
298
|
+
* typed into this dialog; anything it wrongly accepts is inert as an argument,
|
|
299
|
+
* which is the only property being defended. Whether the address exists is
|
|
300
|
+
* Anthropic's question, asked a moment later by the CLI itself.
|
|
301
|
+
*
|
|
302
|
+
* `--email` was the field the alias allowlist below missed. `email.includes("@")`
|
|
303
|
+
* was the whole of its validation and the value came straight off the request
|
|
304
|
+
* body, so the two residuals exec.mjs documents were both reachable through it
|
|
305
|
+
* on Windows, where `claude` is a `.cmd` shim and the vector goes through
|
|
306
|
+
* `cmd.exe /d /s /c`: an interior newline is a command separator inside that one
|
|
307
|
+
* quoted line, and `%USERPROFILE%` expands inside quotes with no escape
|
|
308
|
+
* available. `"a@b\ncalc.exe"` and `"%USERPROFILE%@x"` both satisfy
|
|
309
|
+
* `includes("@")`, and both are payloads alias-charset.test.ts already pins as
|
|
310
|
+
* refused for the other field.
|
|
311
|
+
*
|
|
312
|
+
* The leading-character rule is the same argv-position rule ALIAS_OK now carries.
|
|
313
|
+
* `-x@y.z` starts with a dash, so a child parser reads it as an option rather
|
|
314
|
+
* than as the value of `--email`, and what happens next depends entirely on
|
|
315
|
+
* which options that CLI happens to define.
|
|
316
|
+
*/
|
|
317
|
+
const EMAIL_OK =
|
|
318
|
+
/^[A-Za-z0-9][A-Za-z0-9._%+-]{0,63}@[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)+$/;
|
|
319
|
+
|
|
320
|
+
// The SMTP forward-path limit. The pattern above bounds each PIECE — 64 for the
|
|
321
|
+
// local part, 63 per label — and a domain may carry any number of labels, so
|
|
322
|
+
// without this the whole is unbounded. A bound belongs here for the reason
|
|
323
|
+
// ALIAS_OK has one: on Windows the value ends up inside a single cmd.exe command
|
|
324
|
+
// line, which has a hard length limit of its own.
|
|
325
|
+
const EMAIL_MAX_LENGTH = 254;
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* The `--email` value `claude auth login` should be given, or a refusal.
|
|
329
|
+
*
|
|
330
|
+
* Three answers rather than two, and the third is the one that matters: `null`
|
|
331
|
+
* means NO ADDRESS WAS OFFERED, which is the only shape the deck's own dialog
|
|
332
|
+
* sends (`AddAccountDialog` posts a bare `{action:"login"}`) and which must stay
|
|
333
|
+
* an ordinary sign-in with no flag appended. A value that is present and
|
|
334
|
+
* unusable is refused outright instead of being quietly dropped: dropping it
|
|
335
|
+
* would run a DIFFERENT sign-in from the one that was asked for and call it a
|
|
336
|
+
* success, and this route is reachable by anything holding the deck token.
|
|
337
|
+
*/
|
|
338
|
+
function loginEmailArg(email) {
|
|
339
|
+
if (email == null) return { ok: true, email: null };
|
|
340
|
+
if (typeof email !== "string") return { ok: false };
|
|
341
|
+
const clean = email.trim();
|
|
342
|
+
if (!clean) return { ok: true, email: null };
|
|
343
|
+
if (clean.length > EMAIL_MAX_LENGTH || !EMAIL_OK.test(clean)) return { ok: false };
|
|
344
|
+
return { ok: true, email: clean };
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
export async function startLogin({ email } = {}) {
|
|
348
|
+
// Argv position is settled first, before any state moves. A refusal here must
|
|
349
|
+
// not cancel a sign-in that is already running — the caller asked for
|
|
350
|
+
// something the deck will not do, and the flow already in flight is not part
|
|
351
|
+
// of that bargain.
|
|
352
|
+
const wanted = loginEmailArg(email);
|
|
353
|
+
if (!wanted.ok) return { ok: false, reason: "bad_email", ...loginState() };
|
|
354
|
+
// Registering is the half that writes to the store; interrupting it would
|
|
355
|
+
// leave an account half-recorded, so that one is refused. A flow merely
|
|
356
|
+
// waiting for a code is not precious — it is most often the one abandoned by
|
|
357
|
+
// the page reload that just happened — and it yields to the new request
|
|
358
|
+
// rather than blocking it for the rest of its five minutes.
|
|
359
|
+
if (_login?.state === "registering") {
|
|
360
|
+
return { ok: false, reason: "already_running", ...loginState() };
|
|
361
|
+
}
|
|
362
|
+
if (_login?.state === "awaiting_url" || _login?.state === "awaiting_code") {
|
|
363
|
+
await cancelLogin();
|
|
364
|
+
}
|
|
365
|
+
if (!_starting) {
|
|
366
|
+
_starting = spawnLogin(wanted.email).finally(() => { _starting = null; });
|
|
367
|
+
}
|
|
368
|
+
const flow = await _starting;
|
|
369
|
+
|
|
370
|
+
// The URL arrives on the child's first write, typically within a second — and
|
|
371
|
+
// the child's death ends the wait just as conclusively, which is why the state
|
|
372
|
+
// is polled beside it. A `claude` that cannot be run at all is gone in
|
|
373
|
+
// milliseconds and the done handler below has already written down why, but
|
|
374
|
+
// waiting only for a url meant this POST sat open for the whole fifteen
|
|
375
|
+
// seconds afterwards: a spinner in front of a user whose answer was ready
|
|
376
|
+
// almost immediately.
|
|
377
|
+
await waitFor(() => flow.url || flow.state === "failed" || flow.state === "done", 15_000);
|
|
378
|
+
// A sign-in that got somewhere without a link this could read is still a
|
|
379
|
+
// sign-in, and since #708 the done handler can carry one all the way to
|
|
380
|
+
// `done` on its own. Saying "no url" over that would throw a completed login
|
|
381
|
+
// away at the last step, which is the whole of the bug being fixed.
|
|
382
|
+
if (!flow.url && (flow.state === "registering" || flow.state === "done")) {
|
|
383
|
+
return { ok: true, ...loginState() };
|
|
384
|
+
}
|
|
385
|
+
if (!flow.url) {
|
|
386
|
+
flow.child.kill();
|
|
387
|
+
// Same identity check as the done handler below, and for a sharper reason:
|
|
388
|
+
// a second startLogin cancels this one's child (the yield path above), so
|
|
389
|
+
// this url can never arrive and this wait always runs its full fifteen
|
|
390
|
+
// seconds. Overwriting _login then would erase a live flow — the dialog
|
|
391
|
+
// would flip to "failed" while the newer child is still waiting for a code
|
|
392
|
+
// that can no longer be delivered, and with its handle gone not even
|
|
393
|
+
// cancelLogin could reach it.
|
|
394
|
+
//
|
|
395
|
+
// A flow the child's own death already explained keeps that explanation:
|
|
396
|
+
// failureText turns an unrunnable CLI into "not on PATH. Set
|
|
397
|
+
// AGENTS_DECK_CLAUDE to its full path.", the only sentence in the whole flow
|
|
398
|
+
// that names a fix, and publishing a guess about the missing link over it
|
|
399
|
+
// destroyed it on the server.
|
|
400
|
+
const died = flow === _login && flow.state === "failed" ? flow.error : null;
|
|
401
|
+
if (flow === _login && !died) {
|
|
402
|
+
_login = { state: "failed", error: "the claude CLI did not print a sign-in link" };
|
|
403
|
+
}
|
|
404
|
+
// Carried as `detail` because that is the only field that outranks the
|
|
405
|
+
// reason in the dialog's say(): REASONS["no_url"] asks "is it installed?",
|
|
406
|
+
// which is exactly the question the sentence above has already answered, and
|
|
407
|
+
// it would win over `error`.
|
|
408
|
+
return { ok: false, reason: "no_url", ...(died ? { detail: died } : {}), ...loginState() };
|
|
409
|
+
}
|
|
410
|
+
return { ok: true, ...loginState() };
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/**
|
|
414
|
+
* Start the child and publish it, as one indivisible step.
|
|
415
|
+
*
|
|
416
|
+
* Separate from startLogin so `_starting` can dedupe it: everything here runs
|
|
417
|
+
* before `_login` exists, and a caller that reaches it a second time
|
|
418
|
+
* concurrently would spawn a sign-in nothing can cancel.
|
|
419
|
+
*/
|
|
420
|
+
async function spawnLogin(email) {
|
|
421
|
+
const before = await readStore();
|
|
422
|
+
const identity = await currentIdentity();
|
|
423
|
+
|
|
424
|
+
const args = ["auth", "login"];
|
|
425
|
+
// Already through loginEmailArg, which is the only caller's boundary: this is
|
|
426
|
+
// either an address that cannot be read as a flag or null, and null is the
|
|
427
|
+
// ordinary case.
|
|
428
|
+
if (email) args.push("--email", email);
|
|
429
|
+
|
|
430
|
+
const child = runInteractive(await claudeBin(), args, { timeout: LOGIN_TIMEOUT_MS });
|
|
431
|
+
// A sign-in outlives the request that started it, so it can also outlive the
|
|
432
|
+
// deck. Nothing else would ever reap it: it is waiting on a stdin that no
|
|
433
|
+
// longer has a writer, and it holds the user's next attempt hostage for five
|
|
434
|
+
// minutes. Killed on the way out, and unregistered as soon as it settles so
|
|
435
|
+
// the handler list cannot grow.
|
|
436
|
+
const onExit = () => { try { child.kill(); } catch { /* already gone */ } };
|
|
437
|
+
process.on("exit", onExit);
|
|
438
|
+
child.done.then(() => process.off("exit", onExit), () => process.off("exit", onExit));
|
|
439
|
+
|
|
440
|
+
_login = {
|
|
441
|
+
state: "awaiting_url",
|
|
442
|
+
child,
|
|
443
|
+
previousActive: before.activeNum,
|
|
444
|
+
previousEmail: identity?.email ?? null,
|
|
445
|
+
before,
|
|
446
|
+
url: null,
|
|
447
|
+
error: null,
|
|
448
|
+
account: null,
|
|
449
|
+
expiresAt: Date.now() + LOGIN_TIMEOUT_MS,
|
|
450
|
+
// How many times the CLI has asked for a code. A second ask after we
|
|
451
|
+
// answered is how a rejected code announces itself — the process does not
|
|
452
|
+
// exit, it just asks again, so waiting for exit would hang for the whole
|
|
453
|
+
// five-minute window on a typo.
|
|
454
|
+
prompts: 0,
|
|
455
|
+
};
|
|
456
|
+
const flow = _login;
|
|
457
|
+
|
|
458
|
+
// How many asks the line currently being written has already contributed.
|
|
459
|
+
// The prompt is an unterminated line, re-delivered as it grows, so the same
|
|
460
|
+
// ask arrives over and over — and once more, whole, when something else
|
|
461
|
+
// finally ends the line.
|
|
462
|
+
let countedOnLine = 0;
|
|
463
|
+
|
|
464
|
+
child.onLine((line, partial) => {
|
|
465
|
+
if (!flow.url) {
|
|
466
|
+
const url = extractLoginUrl(line);
|
|
467
|
+
if (url) { flow.url = url; flow.state = "awaiting_code"; }
|
|
468
|
+
}
|
|
469
|
+
const asks = countCodePrompts(line);
|
|
470
|
+
if (asks > countedOnLine) {
|
|
471
|
+
flow.prompts += asks - countedOnLine;
|
|
472
|
+
countedOnLine = asks;
|
|
473
|
+
}
|
|
474
|
+
// A newline ended that line; whatever comes next is a new one.
|
|
475
|
+
if (!partial) countedOnLine = 0;
|
|
476
|
+
});
|
|
477
|
+
// The child ending before a code was pasted USED to be read as a failure, and
|
|
478
|
+
// on this CLI that is the ordinary end of a sign-in that worked (#708).
|
|
479
|
+
//
|
|
480
|
+
// `claude auth login` 2.1.246 does two things at once: it prints
|
|
481
|
+
// "Paste code here if prompted > " and blocks on stdin, AND it listens on a
|
|
482
|
+
// loopback port for the OAuth callback. Which half finishes the exchange is
|
|
483
|
+
// not decided by the CLI's version — it is decided by whether the browser
|
|
484
|
+
// that opened can reach this machine's loopback. On the deck's own machine it
|
|
485
|
+
// can, so the CLI takes the code itself, prints "Login successful." and exits
|
|
486
|
+
// 0 while the deck is still sitting in `awaiting_code`; the page that
|
|
487
|
+
// authorised says "You're all set up" and never shows a code to paste. On a
|
|
488
|
+
// deck reached from another machine it cannot, the page shows the code, and
|
|
489
|
+
// the paste path below is the one that runs.
|
|
490
|
+
//
|
|
491
|
+
// So the exit alone is not the verdict. The verdict is the identity, and
|
|
492
|
+
// `claude auth status --json` is the oracle this module already trusts for
|
|
493
|
+
// it — asked here against the identity recorded before the flow started.
|
|
494
|
+
child.done.then(async (r) => {
|
|
495
|
+
if (flow !== _login) return;
|
|
496
|
+
if (flow.state !== "awaiting_url" && flow.state !== "awaiting_code") return;
|
|
497
|
+
// Answered before any await, so that a `claude` which cannot be run at all
|
|
498
|
+
// is still reported within milliseconds: startLogin waits on this state to
|
|
499
|
+
// decide whether to keep holding its POST open, and the sentence naming
|
|
500
|
+
// AGENTS_DECK_CLAUDE is the only one in the flow that names a fix. Nothing
|
|
501
|
+
// was signed in either way, so there is nothing to ask about.
|
|
502
|
+
if (r.timedOut || cannotRun(r)) {
|
|
503
|
+
flow.state = "failed";
|
|
504
|
+
flow.error = loginFailureText(r);
|
|
505
|
+
return;
|
|
506
|
+
}
|
|
507
|
+
// Claimed before asking, for the same reason submitLoginCode claims it: a
|
|
508
|
+
// code posted while the question is out would otherwise register the same
|
|
509
|
+
// login a second time, with a second `cswap add` racing this one.
|
|
510
|
+
flow.state = "registering";
|
|
511
|
+
const identity = await currentIdentity();
|
|
512
|
+
if (flow !== _login) return;
|
|
513
|
+
// A clean exit with somebody logged in is a completed sign-in, including
|
|
514
|
+
// the re-sign-in of an account the deck already holds — an identity that
|
|
515
|
+
// did not CHANGE is not an identity that did not arrive. A dirty exit
|
|
516
|
+
// counts only when the identity moved, which is a login that landed in
|
|
517
|
+
// spite of whatever the CLI complained about on its way out.
|
|
518
|
+
if (identity && (r.ok || identity.email !== flow.previousEmail)) {
|
|
519
|
+
await registerSignedIn(flow, identity);
|
|
520
|
+
return;
|
|
521
|
+
}
|
|
522
|
+
flow.state = "failed";
|
|
523
|
+
flow.error = loginFailureText(r);
|
|
524
|
+
}).catch((err) => {
|
|
525
|
+
// This handler answers nobody's request — its promise is dropped — so a
|
|
526
|
+
// throw anywhere in it would be an unhandled rejection AND a dialog left
|
|
527
|
+
// spinning on `registering` until the poll gave up. It was three lines of
|
|
528
|
+
// synchronous assignment before; it now shells out twice.
|
|
529
|
+
console.error(`${PRODUCT} sign-in: the sign-in could not be finished:`, err?.message ?? err);
|
|
530
|
+
if (flow !== _login) return;
|
|
531
|
+
flow.state = "failed";
|
|
532
|
+
flow.error = "the sign-in could not be finished — see the deck's log";
|
|
533
|
+
});
|
|
534
|
+
return flow;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
/** A run that never reached the CLI at all — nothing can have been signed in. */
|
|
538
|
+
function cannotRun(r) {
|
|
539
|
+
return r?.code === "ENOENT" || looksMissing(`${r?.stderr ?? ""}\n${r?.stdout ?? ""}`, "", r?.code);
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
/**
|
|
543
|
+
* Why a sign-in failed, in words meant for the person who pressed the button.
|
|
544
|
+
*
|
|
545
|
+
* The child's own output is offered only when it is a diagnosis — see
|
|
546
|
+
* failureText, which since #708 refuses a line that announces success or is
|
|
547
|
+
* merely the prompt the CLI was still sitting on. What it printed is not thrown
|
|
548
|
+
* away; it goes to the deck's log, where an operator can read it, rather than
|
|
549
|
+
* onto a dialog as the reason.
|
|
550
|
+
*/
|
|
551
|
+
function loginFailureText(r) {
|
|
552
|
+
// One line, the way ccusage's `note` says everything it says: an operator
|
|
553
|
+
// watching the terminal is reading it beside the deck's own repainted status
|
|
554
|
+
// rows, and the escapes in it are a login link's OSC-8 wrapper.
|
|
555
|
+
//
|
|
556
|
+
// stderr goes LAST because the line is cut from the front. What should be
|
|
557
|
+
// lost to the bound is the CLI's chatter — the greeting and a sign-in link
|
|
558
|
+
// that is 400 characters by itself — never its complaint.
|
|
559
|
+
const tail = stripTerminalEscapes(`${r?.stdout ?? ""}\n${r?.stderr ?? ""}`).replace(/\s+/g, " ").trim();
|
|
560
|
+
if (tail) console.error(`${PRODUCT} sign-in: claude auth login did not complete:`, tail.slice(-300));
|
|
561
|
+
if (r?.timedOut) return "the sign-in window expired";
|
|
562
|
+
return failureText(r, "claude auth login", "the sign-in did not complete — nothing new was signed in");
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
/**
|
|
566
|
+
* Everything after the sign-in itself: confirm who we are now, record it with
|
|
567
|
+
* claude-swap, and put the previously-active account back in front.
|
|
568
|
+
*
|
|
569
|
+
* Shared by the two ways a sign-in can end (#708) — a code pasted into the
|
|
570
|
+
* prompt, and the CLI finishing the exchange through its own loopback callback
|
|
571
|
+
* — because the steps after it are identical and have to stay identical. An
|
|
572
|
+
* account the deck skipped `cswap add` for is signed in at the CLI level and
|
|
573
|
+
* invisible to the panel, with the account the user was on left switched away
|
|
574
|
+
* from.
|
|
575
|
+
*
|
|
576
|
+
* Returns the same `{ok, ...loginState()}` both callers answer their request
|
|
577
|
+
* with; the done handler simply drops it.
|
|
578
|
+
*/
|
|
579
|
+
async function registerSignedIn(flow, identity) {
|
|
580
|
+
return withStoreLock(async () => {
|
|
581
|
+
const add = await run(await cswapBin(), ["add"], { timeout: CSWAP_TIMEOUT_MS });
|
|
582
|
+
if (!add.ok) {
|
|
583
|
+
flow.state = "failed";
|
|
584
|
+
flow.error = addFailureText(add);
|
|
585
|
+
await restoreActive(flow.previousActive);
|
|
586
|
+
return { ok: false, reason: "add_failed", ...loginState() };
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
const after = await readStore();
|
|
590
|
+
const slot = newSlot(flow.before, after);
|
|
591
|
+
// No new slot means the account was already managed and cswap refreshed its
|
|
592
|
+
// credentials in place. That is a success with a different sentence.
|
|
593
|
+
const num = slot ?? Object.keys(after.emails).find(k => after.emails[k] === identity.email) ?? null;
|
|
594
|
+
|
|
595
|
+
await restoreActive(flow.previousActive);
|
|
596
|
+
invalidateClaudeAccountsCache();
|
|
597
|
+
// Collect straight away, so the new row shows numbers instead of "never
|
|
598
|
+
// collected" until the next poll — the same nudge seedFirstAccount uses.
|
|
599
|
+
runDetached(await cswapBin(), ["list"]);
|
|
600
|
+
|
|
601
|
+
flow.state = "done";
|
|
602
|
+
flow.account = { num, email: identity.email, added: slot != null };
|
|
603
|
+
return { ok: true, ...loginState() };
|
|
604
|
+
});
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
/**
|
|
608
|
+
* Hand the code back, then register whatever it signed us in as.
|
|
609
|
+
*
|
|
610
|
+
* Every step after the code is verification, not optimism: the CLI can exit 0
|
|
611
|
+
* having changed nothing, so the identity is re-read and compared before the
|
|
612
|
+
* store is touched at all.
|
|
613
|
+
*/
|
|
614
|
+
export async function submitLoginCode(code) {
|
|
615
|
+
const flow = _login;
|
|
616
|
+
if (!flow || flow.state !== "awaiting_code") return { ok: false, reason: "not_waiting", ...loginState() };
|
|
617
|
+
if (typeof code !== "string" || !code.trim()) return { ok: false, reason: "empty_code", ...loginState() };
|
|
618
|
+
if (flow.prompts === 0) return { ok: false, reason: "not_prompted", ...loginState() };
|
|
619
|
+
|
|
620
|
+
const askedBefore = flow.prompts;
|
|
621
|
+
flow.state = "registering";
|
|
622
|
+
flow.child.write(code.trim() + "\n");
|
|
623
|
+
|
|
624
|
+
// Whichever comes first: the CLI finishing, or it asking again. A wrong code
|
|
625
|
+
// produces the second, and the flow stays usable so the user can retype
|
|
626
|
+
// rather than starting the whole sign-in over.
|
|
627
|
+
const r = await Promise.race([
|
|
628
|
+
flow.child.done,
|
|
629
|
+
waitFor(() => flow.prompts > askedBefore, CODE_VERDICT_MS, 200).then(again => (again ? "rejected" : "slow")),
|
|
630
|
+
]);
|
|
631
|
+
if (r === "rejected") {
|
|
632
|
+
flow.state = "awaiting_code";
|
|
633
|
+
flow.error = "that code was not accepted — copy it again from the browser";
|
|
634
|
+
return { ok: false, reason: "code_rejected", ...loginState() };
|
|
635
|
+
}
|
|
636
|
+
if (r === "slow") {
|
|
637
|
+
flow.state = "awaiting_code";
|
|
638
|
+
flow.error = "the claude CLI has not answered — try the code again";
|
|
639
|
+
return { ok: false, reason: "no_verdict", ...loginState() };
|
|
640
|
+
}
|
|
641
|
+
if (!r.ok) {
|
|
642
|
+
flow.state = "failed";
|
|
643
|
+
// The `|| "the code was not accepted"` this used to end with could never
|
|
644
|
+
// run: failureText always answered with something, if only an exit status.
|
|
645
|
+
// The sentence is where it can be reached now — as the fallback failureText
|
|
646
|
+
// reaches for when the CLI printed nothing worth repeating.
|
|
647
|
+
flow.error = r.timedOut ? "the sign-in window expired" : failureText(r, "claude auth login", "the code was not accepted");
|
|
648
|
+
return { ok: false, reason: "login_failed", ...loginState() };
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
const identity = await currentIdentity();
|
|
652
|
+
if (!identity) {
|
|
653
|
+
flow.state = "failed";
|
|
654
|
+
flow.error = "signed in, but the claude CLI still reports nobody logged in";
|
|
655
|
+
return { ok: false, reason: "no_identity", ...loginState() };
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
return registerSignedIn(flow, identity);
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
export async function cancelLogin() {
|
|
662
|
+
const flow = _login;
|
|
663
|
+
if (!flow) return { ok: true, ...loginState() };
|
|
664
|
+
// Stopping the child touches no file, so it happens straight away: a cancel
|
|
665
|
+
// that waited its turn first would leave `claude auth login` sitting on the
|
|
666
|
+
// user's next attempt for the rest of its five minutes.
|
|
667
|
+
try { flow.child?.kill(); } catch { /* already gone */ }
|
|
668
|
+
// Switching back does touch the store, so it is queued like every other
|
|
669
|
+
// mutation. Cancel is reachable while submitLoginCode holds the lock — the
|
|
670
|
+
// dialog fires it on Escape, mid-registration — and running `cswap switch`
|
|
671
|
+
// beside an in-flight `cswap add` is precisely the unlocked read-modify-write
|
|
672
|
+
// of sequence.json the mutex exists to prevent: claude-swap takes no file lock
|
|
673
|
+
// around `add`, so whichever write lands second drops the other's record.
|
|
674
|
+
return withStoreLock(async () => {
|
|
675
|
+
// The login may have completed before the cancel arrived, in which case the
|
|
676
|
+
// live credentials already moved and putting them back is the point.
|
|
677
|
+
await restoreActive(flow.previousActive);
|
|
678
|
+
invalidateClaudeAccountsCache();
|
|
679
|
+
// A newer sign-in can have started while this waited its turn; clearing the
|
|
680
|
+
// slot then would drop a live flow's handle instead of this dead one's.
|
|
681
|
+
if (flow === _login) _login = null;
|
|
682
|
+
return { ok: true, ...loginState() };
|
|
683
|
+
});
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
/** Put the account that was active before the login back in front. */
|
|
687
|
+
async function restoreActive(num) {
|
|
688
|
+
if (num == null) return;
|
|
689
|
+
const after = await readStore();
|
|
690
|
+
if (String(after.activeNum) === String(num)) return;
|
|
691
|
+
await run(await cswapBin(), ["switch", String(num)], { timeout: 30_000 }).catch(() => {});
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
// ── share / import ───────────────────────────────────────────────────────────
|
|
695
|
+
|
|
696
|
+
/**
|
|
697
|
+
* One account, packaged for another deck.
|
|
698
|
+
*
|
|
699
|
+
* claude-swap's envelope carries the account's OAuth token in the clear — its
|
|
700
|
+
* own module header says so ("No encryption is built in"). The wrapper adds an
|
|
701
|
+
* expiry so a copy left behind in clipboard history stops working, and nothing
|
|
702
|
+
* more: it is not encryption and is not presented as any.
|
|
703
|
+
*
|
|
704
|
+
* Say the limit of that out loud, because the UI used to imply the opposite.
|
|
705
|
+
* `exp` is a plain number inside plain base64'd JSON with NO key, MAC or
|
|
706
|
+
* signature over it, so anyone holding the text can decode it, write a later
|
|
707
|
+
* `exp`, re-encode, and import it. unwrapShare's check is therefore a check
|
|
708
|
+
* against staleness, not against an adversary — and it cannot be made into one
|
|
709
|
+
* here. A MAC needs a secret both decks hold, and two decks that already shared
|
|
710
|
+
* a secret would not need this function; and even a perfect signature would
|
|
711
|
+
* only stop THIS import path, since the payload it wraps is the credential
|
|
712
|
+
* itself and `cswap import` accepts it unwrapped. The honest fix for a share
|
|
713
|
+
* that got away is to sign the account out and back in. See share-expiry-
|
|
714
|
+
* forgeable.test.ts, which pins the forgery rather than leaving it implied.
|
|
715
|
+
*
|
|
716
|
+
* The default export shape is used deliberately, never --full, which would
|
|
717
|
+
* embed the entire ~/.claude.json including every project and MCP server.
|
|
718
|
+
*/
|
|
719
|
+
export function wrapShare(payload, now = Date.now(), ttlMs = SHARE_TTL_MS) {
|
|
720
|
+
const body = JSON.stringify({ v: 1, exp: now + ttlMs, payload });
|
|
721
|
+
return SHARE_PREFIX + Buffer.from(body, "utf8").toString("base64");
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
/** The inverse. Returns `{ok:true, payload}` or `{ok:false, reason}`. */
|
|
725
|
+
export function unwrapShare(blob, now = Date.now()) {
|
|
726
|
+
const text = String(blob ?? "").trim();
|
|
727
|
+
if (!text.startsWith(SHARE_PREFIX)) return { ok: false, reason: "not_a_share" };
|
|
728
|
+
let env;
|
|
729
|
+
try {
|
|
730
|
+
env = JSON.parse(Buffer.from(text.slice(SHARE_PREFIX.length), "base64").toString("utf8"));
|
|
731
|
+
} catch {
|
|
732
|
+
return { ok: false, reason: "corrupt" };
|
|
733
|
+
}
|
|
734
|
+
if (env?.v !== 1) return { ok: false, reason: "wrong_version" };
|
|
735
|
+
// Checked before the payload is looked at, let alone handed to cswap.
|
|
736
|
+
if (typeof env.exp !== "number" || env.exp < now) return { ok: false, reason: "expired" };
|
|
737
|
+
if (typeof env.payload !== "string" || !env.payload) return { ok: false, reason: "corrupt" };
|
|
738
|
+
return { ok: true, payload: env.payload };
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
export async function shareAccount(num) {
|
|
742
|
+
const n = Number(num);
|
|
743
|
+
if (!Number.isInteger(n) || n < 1 || n > 999) return { ok: false, reason: "bad_account" };
|
|
744
|
+
const r = await run(await cswapBin(), ["export", "-", "--account", String(n)], { timeout: CSWAP_TIMEOUT_MS });
|
|
745
|
+
if (!r.ok || !r.stdout.trim()) {
|
|
746
|
+
// The failure sentence is built from stderr ALONE for this one command,
|
|
747
|
+
// because its stdout is the credential. `failureText` concatenates
|
|
748
|
+
// `${stderr}\n${stdout}` and `firstUseful` takes the LAST non-empty line —
|
|
749
|
+
// right for every other cswap command, and here it means any stdout at all
|
|
750
|
+
// outranks the real error. claude-swap writes its diagnostics to stderr
|
|
751
|
+
// specifically so stdout stays pure JSON in pipe mode, and it writes the
|
|
752
|
+
// envelope as its last act; a non-zero exit after a partial write would
|
|
753
|
+
// therefore put the tail of `json.dumps(envelope, indent=2)` in front of the
|
|
754
|
+
// user, and one of those lines is the refresh token on its own.
|
|
755
|
+
//
|
|
756
|
+
// Nothing is lost by dropping it: the ENOENT branch keys off `r.code`, which
|
|
757
|
+
// `run` sets, and cmd.exe's "is not recognized" is stderr's.
|
|
758
|
+
return { ok: false, reason: "export_failed", detail: failureText({ ...r, stdout: "" }, "cswap export") };
|
|
759
|
+
}
|
|
760
|
+
return { ok: true, blob: wrapShare(r.stdout), expiresAt: Date.now() + SHARE_TTL_MS };
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
export async function importAccount(blob) {
|
|
764
|
+
const un = unwrapShare(blob);
|
|
765
|
+
if (!un.ok) return { ok: false, reason: un.reason };
|
|
766
|
+
|
|
767
|
+
return withStoreLock(async () => {
|
|
768
|
+
const before = await readStore();
|
|
769
|
+
const child = runInteractive(await cswapBin(), ["import", "-"], { timeout: CSWAP_TIMEOUT_MS });
|
|
770
|
+
child.write(un.payload);
|
|
771
|
+
// cswap reads stdin to EOF, so the pipe has to close for it to proceed.
|
|
772
|
+
//
|
|
773
|
+
// This used to write a raw EOT byte and then call `endStdin(child)` — a
|
|
774
|
+
// helper that was never written. EOT only means end-of-file on a TTY, so
|
|
775
|
+
// the byte did nothing to a pipe, and the call threw ReferenceError before
|
|
776
|
+
// cswap ever saw the payload: the route answered 500 and the dialog fell
|
|
777
|
+
// back to "the import failed", which is exactly what a genuinely refused
|
|
778
|
+
// import says. Reported 2026-08-14.
|
|
779
|
+
child.end();
|
|
780
|
+
|
|
781
|
+
const r = await child.done;
|
|
782
|
+
if (!r.ok) return { ok: false, reason: "import_failed", detail: failureText(r, "cswap import") };
|
|
783
|
+
|
|
784
|
+
const after = await readStore();
|
|
785
|
+
const slot = newSlot(before, after);
|
|
786
|
+
invalidateClaudeAccountsCache();
|
|
787
|
+
if (slot != null) runDetached(await cswapBin(), ["list"]);
|
|
788
|
+
// Who arrived, so the dialog can name them instead of saying "an account".
|
|
789
|
+
const email = slot != null ? (after.emails[slot] || null) : null;
|
|
790
|
+
// No new slot is not an error: without --force, cswap skips an account it
|
|
791
|
+
// already holds. Saying which happened is the difference between "it
|
|
792
|
+
// worked" and "why is nothing different".
|
|
793
|
+
return { ok: true, added: slot != null, num: slot, email, output: firstUseful(r.stdout) };
|
|
794
|
+
});
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
// ── the small edits ──────────────────────────────────────────────────────────
|
|
798
|
+
|
|
799
|
+
// The exact question `cswap remove` asks. There is no --yes flag: assume_yes is
|
|
800
|
+
// a Python parameter its TUI passes in-process, so the only way through from a
|
|
801
|
+
// CLI is to answer. Matched, never assumed — an unrecognised prompt gets the
|
|
802
|
+
// child killed instead of a blind "y".
|
|
803
|
+
const REMOVE_PROMPT = /are you sure you want to permanently remove account-(\d+)/i;
|
|
804
|
+
|
|
805
|
+
export function removePromptMatches(line, num) {
|
|
806
|
+
const m = REMOVE_PROMPT.exec(stripTerminalEscapes(line));
|
|
807
|
+
return Boolean(m) && m[1] === String(num);
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
export async function removeAccount(num) {
|
|
811
|
+
const n = Number(num);
|
|
812
|
+
if (!Number.isInteger(n) || n < 1 || n > 999) return { ok: false, reason: "bad_account" };
|
|
813
|
+
|
|
814
|
+
return withStoreLock(async () => {
|
|
815
|
+
const child = runInteractive(await cswapBin(), ["remove", String(n)], { timeout: CSWAP_TIMEOUT_MS });
|
|
816
|
+
let answered = false;
|
|
817
|
+
child.onLine((line) => {
|
|
818
|
+
if (answered) return;
|
|
819
|
+
if (removePromptMatches(line, n)) { answered = true; child.write("y\n"); }
|
|
820
|
+
});
|
|
821
|
+
const r = await child.done;
|
|
822
|
+
invalidateClaudeAccountsCache();
|
|
823
|
+
if (!r.ok) return { ok: false, reason: "remove_failed", detail: failureText(r, "cswap remove") };
|
|
824
|
+
// Exit 0 without the prompt means cswap declined for its own reason — a
|
|
825
|
+
// live session on that account, most often — and printed why.
|
|
826
|
+
if (!answered) return { ok: false, reason: "not_confirmed", detail: firstUseful(r.stdout || r.stderr) };
|
|
827
|
+
return { ok: true, output: firstUseful(r.stdout) };
|
|
828
|
+
});
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
/**
|
|
832
|
+
* What an alias may be made of.
|
|
833
|
+
*
|
|
834
|
+
* Every other argument this module sends to cswap is an integer bounded to
|
|
835
|
+
* 1..999; the alias was the one free-text field, and `.trim()` was the whole of
|
|
836
|
+
* its validation. That is fine on POSIX, where `run` spawns the argument vector
|
|
837
|
+
* untouched, and not fine on Windows: cswap is a `.cmd` shim there, so the
|
|
838
|
+
* vector goes through `cmd.exe /d /s /c` (see viaCmd). Quote-doubling handles
|
|
839
|
+
* `"` and every other metacharacter, which leaves exactly the residual exec.mjs
|
|
840
|
+
* documents — `%VAR%` expands inside quotes and a command line has no escape for
|
|
841
|
+
* it — so `%USERPROFILE%` in an alias stored the user's home path, and an alias
|
|
842
|
+
* carrying an unbalanced quote plus an `&` could end the quoted region early.
|
|
843
|
+
* An interior newline survived `.trim()` untouched as well.
|
|
844
|
+
*
|
|
845
|
+
* The same allowlist discipline cswap-auto.mjs already applies to its model
|
|
846
|
+
* list, and it closes the unbounded-length half too: an alias is a short name
|
|
847
|
+
* shown instead of an email, so 64 characters is not a constraint anyone meets
|
|
848
|
+
* by accident.
|
|
849
|
+
*
|
|
850
|
+
* The leading `(?!-)` is the half that allowlist missed, and it is not about
|
|
851
|
+
* quoting at all — it is about ARGV POSITION, which no amount of quoting fixes
|
|
852
|
+
* because the value arrives intact and is then read as syntax by the CHILD.
|
|
853
|
+
* `-` is in the character class, so `--unset` matched, and
|
|
854
|
+
* `setAlias(3, "--unset")` built ["alias", "3", "--unset"] — character for
|
|
855
|
+
* character claude-swap's own command for CLEARING an alias. Its `_alias_command`
|
|
856
|
+
* hands that vector to argparse, which sets `unset=True` and leaves `alias_name`
|
|
857
|
+
* as None; the store dropped the name, cswap printed "Removed alias for
|
|
858
|
+
* Account 3", exited 0, and the deck reported the rename as a success. Any other
|
|
859
|
+
* `-x` spelling is consumed the same way — `-h` prints help and exits 0, which
|
|
860
|
+
* also arrives here as a rename that worked.
|
|
861
|
+
*
|
|
862
|
+
* argparse does honour `--` as an end-of-options separator, so
|
|
863
|
+
* ["alias", "3", "--", "--unset"] would reach `set_alias` as data. It is
|
|
864
|
+
* deliberately not used: the separator only helps for the one child whose parser
|
|
865
|
+
* we can read, `claude auth login` is the other spawn on this route and its
|
|
866
|
+
* parser is not ours to verify, and a value the deck refuses outright cannot be
|
|
867
|
+
* mangled by a CLI that changes its mind later. The validator is the guard.
|
|
868
|
+
*
|
|
869
|
+
* Refusing a leading dash rather than requiring a leading alphanumeric is the
|
|
870
|
+
* narrower rule, and it is the one the hazard actually describes: `.env` and
|
|
871
|
+
* `_work` are ordinary positional arguments to every parser involved, while
|
|
872
|
+
* `acme-corp` — the one dash-bearing name in alias-charset.test.ts's list of
|
|
873
|
+
* names people use — keeps working because only the FIRST character is
|
|
874
|
+
* constrained.
|
|
875
|
+
*/
|
|
876
|
+
const ALIAS_OK = /^(?!-)[A-Za-z0-9 ._-]{1,64}$/;
|
|
877
|
+
|
|
878
|
+
export async function setAlias(num, alias) {
|
|
879
|
+
const n = Number(num);
|
|
880
|
+
if (!Number.isInteger(n) || n < 1 || n > 999) return { ok: false, reason: "bad_account" };
|
|
881
|
+
const clean = typeof alias === "string" ? alias.trim() : "";
|
|
882
|
+
if (clean && !ALIAS_OK.test(clean)) return { ok: false, reason: "bad_value" };
|
|
883
|
+
const args = clean ? ["alias", String(n), clean] : ["alias", String(n), "--unset"];
|
|
884
|
+
return withStoreLock(async () => {
|
|
885
|
+
const r = await run(await cswapBin(), args, { timeout: CSWAP_TIMEOUT_MS });
|
|
886
|
+
invalidateClaudeAccountsCache();
|
|
887
|
+
return r.ok
|
|
888
|
+
? { ok: true, output: firstUseful(r.stdout) }
|
|
889
|
+
: { ok: false, reason: "alias_failed", detail: failureText(r, "cswap alias") };
|
|
890
|
+
});
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
/**
|
|
894
|
+
* What a `cswap move` actually did, read out of the store rather than its words.
|
|
895
|
+
*
|
|
896
|
+
* The panel needs two facts to keep its manage block pointed at the account
|
|
897
|
+
* the user opened it on: which slot that account ended up in, and whether a
|
|
898
|
+
* second account was displaced to make room. `cswap move` does carry both, but
|
|
899
|
+
* not in a line this code can take: a swap prints "Swapped Account 2 and
|
|
900
|
+
* Account 3:" and then one indented roster line per account, and `firstUseful`
|
|
901
|
+
* takes the LAST line of a command's output — right for every other cswap
|
|
902
|
+
* command, and here it hands back "3: someone@example.com" instead of the
|
|
903
|
+
* verdict. The store is the fact, for the same reason `newSlot` reads it after
|
|
904
|
+
* an add rather than parsing what add printed.
|
|
905
|
+
*
|
|
906
|
+
* Claude-swap has three cases — the account is already there, the target slot
|
|
907
|
+
* is free and it relocates, the target is occupied and the two trade places —
|
|
908
|
+
* and all three are legible in what settled: the mover holds the target, and
|
|
909
|
+
* on a swap the occupant holds the slot the mover left. `to` is null when the
|
|
910
|
+
* account is not where it was sent, which is not a case that should happen and
|
|
911
|
+
* is exactly why it is reported rather than assumed.
|
|
912
|
+
*/
|
|
913
|
+
export function moveOutcome(before, after, num, slot) {
|
|
914
|
+
const from = String(num), to = String(slot);
|
|
915
|
+
const mover = before.emails[from] || "";
|
|
916
|
+
const occupant = before.slots.includes(to) ? (before.emails[to] || "") : null;
|
|
917
|
+
// Identity by email wherever the store has one, occupancy alone where it
|
|
918
|
+
// does not: a blank email cannot tell two accounts apart, and refusing to
|
|
919
|
+
// answer on that account would be worse than answering from the slot.
|
|
920
|
+
const landed = after.slots.includes(to) && (!mover || after.emails[to] === mover);
|
|
921
|
+
const swapped = landed && from !== to && occupant !== null
|
|
922
|
+
&& after.slots.includes(from) && (!occupant || after.emails[from] === occupant);
|
|
923
|
+
return { from: Number(num), to: landed ? Number(slot) : null, swapped };
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
export async function moveAccount(num, slot) {
|
|
927
|
+
const n = Number(num), s = Number(slot);
|
|
928
|
+
if (!Number.isInteger(n) || n < 1 || n > 999) return { ok: false, reason: "bad_account" };
|
|
929
|
+
if (!Number.isInteger(s) || s < 1 || s > 999) return { ok: false, reason: "bad_slot" };
|
|
930
|
+
return withStoreLock(async () => {
|
|
931
|
+
// Read first: which slots were taken before the move is the only way to
|
|
932
|
+
// know afterwards whether anyone was standing in the destination.
|
|
933
|
+
const before = await readStore();
|
|
934
|
+
const r = await run(await cswapBin(), ["move", String(n), String(s)], { timeout: CSWAP_TIMEOUT_MS });
|
|
935
|
+
invalidateClaudeAccountsCache();
|
|
936
|
+
if (!r.ok) return { ok: false, reason: "move_failed", detail: failureText(r, "cswap move") };
|
|
937
|
+
return { ok: true, output: firstUseful(r.stdout), ...moveOutcome(before, await readStore(), n, s) };
|
|
938
|
+
});
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
// ── text ─────────────────────────────────────────────────────────────────────
|
|
942
|
+
|
|
943
|
+
/**
|
|
944
|
+
* What went wrong, in a sentence the user can act on.
|
|
945
|
+
*
|
|
946
|
+
* The missing-tool case is singled out because its own output is useless: on
|
|
947
|
+
* Windows it is cmd.exe's two-line "is not recognized …/operable program or
|
|
948
|
+
* batch file.", and `firstUseful` — which takes the LAST line, correctly for
|
|
949
|
+
* every other CLI — leaves the second half on screen by itself.
|
|
950
|
+
*
|
|
951
|
+
* The exit status goes to looksMissing beside the text (#552). This is the one
|
|
952
|
+
* caller with no candidate spelling to compare against, so the shape rules alone
|
|
953
|
+
* are all the TEXT can offer it — and on a non-English Windows the text says
|
|
954
|
+
* nothing this recognises. The status does: 9009 is cmd.exe's "no such command"
|
|
955
|
+
* in every language. Without it, a German user pressing "share…" got the last
|
|
956
|
+
* line of a translated sentence instead of the sentence about PATH.
|
|
957
|
+
*/
|
|
958
|
+
export function failureText(r, what = "cswap", fallback = "") {
|
|
959
|
+
const out = `${r?.stderr ?? ""}\n${r?.stdout ?? ""}`;
|
|
960
|
+
const tool = String(what).split(" ")[0];
|
|
961
|
+
if (r?.code === "ENOENT" || looksMissing(out, "", r?.code)) {
|
|
962
|
+
return tool === "claude"
|
|
963
|
+
? "the claude CLI could not be run: not on PATH. Set AGENTS_DECK_CLAUDE to its full path."
|
|
964
|
+
: "cswap could not be run: not on PATH, and not in the places uv and pipx install to. Set AGENTS_DECK_CSWAP to its full path.";
|
|
965
|
+
}
|
|
966
|
+
// A run its deadline stopped has no exit status worth quoting and no last
|
|
967
|
+
// line worth quoting either — whatever it had printed, it had not finished.
|
|
968
|
+
// Asked for one anyway, this said "cswap export exited 0", a success code for
|
|
969
|
+
// a command that never completed.
|
|
970
|
+
if (r?.timedOut || r?.code === "ETIMEDOUT") return `${what} took too long and was stopped`;
|
|
971
|
+
return diagnosis(r?.stderr) || diagnosis(r?.stdout) || fallback || `${what} exited ${r?.code}`;
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
/**
|
|
975
|
+
* A line that is NOT a diagnosis, however it reached us.
|
|
976
|
+
*
|
|
977
|
+
* Two shapes were being shown to users as the reason something failed (#708),
|
|
978
|
+
* both out of `claude auth login`: the CLI's own "Login successful." — a
|
|
979
|
+
* failure reason containing the word "successful" is not a diagnosis, it is a
|
|
980
|
+
* dump — and "Paste code here if prompted >", the unterminated prompt it was
|
|
981
|
+
* still sitting on, which says that something was ASKED and nothing about
|
|
982
|
+
* anything going wrong.
|
|
983
|
+
*/
|
|
984
|
+
const NOT_A_DIAGNOSIS = /\bsuccess(?:ful|fully)?\b|[>?]\s*$/i;
|
|
985
|
+
|
|
986
|
+
/**
|
|
987
|
+
* One stream's last useful line, if it is worth showing a person.
|
|
988
|
+
*
|
|
989
|
+
* Split per stream because the two are not equal: a CLI's diagnosis goes to
|
|
990
|
+
* stderr and its ordinary progress chatter goes to stdout. Reading the LAST
|
|
991
|
+
* line of the two concatenated — which is what this module did — handed stdout
|
|
992
|
+
* the answer whenever it had written anything at all, so `claude auth login`
|
|
993
|
+
* explained itself with the prompt it had printed rather than with the "Login
|
|
994
|
+
* failed: …" it had put on stderr.
|
|
995
|
+
*/
|
|
996
|
+
function diagnosis(text) {
|
|
997
|
+
const line = firstUseful(text);
|
|
998
|
+
return line && !NOT_A_DIAGNOSIS.test(line) ? line : "";
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
/** The line worth showing a user out of a CLI's output. */
|
|
1002
|
+
export function firstUseful(text) {
|
|
1003
|
+
const lines = stripTerminalEscapes(text)
|
|
1004
|
+
.split(/\r?\n/)
|
|
1005
|
+
.map(l => l.replace(/^Error:\s*/i, "").trim())
|
|
1006
|
+
.filter(l => l && !/^-+$/.test(l));
|
|
1007
|
+
return lines.length ? lines[lines.length - 1].slice(0, 300) : "";
|
|
1008
|
+
}
|
|
1009
|
+
|
|
1010
|
+
/**
|
|
1011
|
+
* `cswap add`'s failure, in the words most likely to be actionable.
|
|
1012
|
+
*
|
|
1013
|
+
* The Keychain case is singled out because it is the one a server hits and a
|
|
1014
|
+
* terminal does not: a process without a GUI session cannot read the login
|
|
1015
|
+
* keychain, so the credential read times out and the message alone
|
|
1016
|
+
* ("unreadable right now") does not say what to do.
|
|
1017
|
+
*/
|
|
1018
|
+
export function addFailureText(r) {
|
|
1019
|
+
const text = firstUseful(r.stderr || r.stdout);
|
|
1020
|
+
if (/keychain/i.test(text)) {
|
|
1021
|
+
return `${text} — start ${PRODUCT} from a Terminal window rather than a background service.`;
|
|
1022
|
+
}
|
|
1023
|
+
return failureText(r, "cswap add");
|
|
1024
|
+
}
|
|
1025
|
+
|
|
1026
|
+
async function waitFor(get, timeoutMs, stepMs = 100) {
|
|
1027
|
+
const until = Date.now() + timeoutMs;
|
|
1028
|
+
for (;;) {
|
|
1029
|
+
const v = get();
|
|
1030
|
+
if (v) return v;
|
|
1031
|
+
if (Date.now() >= until) return null;
|
|
1032
|
+
await new Promise(r => setTimeout(r, stepMs));
|
|
1033
|
+
}
|
|
1034
|
+
}
|