@emesoft/tokenhub 0.8.14 → 0.9.1

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.
@@ -0,0 +1,611 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { chmodSync, existsSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
+ import { createServer } from "node:net";
4
+ import { hostname } from "node:os";
5
+ import { basename, dirname, join } from "node:path";
6
+ import { findOnPath, findRealClaude, normalizeDir } from "./claude-shim.js";
7
+ import { ensureLauncher, hasPsBlock, launcherWins, realWindowsSystem, removeLauncher } from "./launcher-precedence.js";
8
+ import { pairRemote, checkRemoteToken, revokeRemoteToken } from "./remote.js";
9
+ import { downloadRemote, HOOK_FILE, readCurrent } from "./remote-download.js";
10
+ import { appConfigDir, exeName, legacyConfigDir, remoteDir, shimDir } from "./remote-paths.js";
11
+ import { installShimFiles, removeShimFiles, shimInstalled, shimPresent } from "./remote-shim.js";
12
+ import { detectLang, text } from "./remote-text.js";
13
+ import { run as defaultRun } from "./run.js";
14
+ import { addBinToPath, profileFiles, PROFILE_BEGIN, removeBinFromPath, windowsUserPath } from "./user-path.js";
15
+
16
+ /** The relay used when the pool has not been told its relay's address. */
17
+ export const DEFAULT_RELAY_ORIGIN = "https://remote.aimpact.io.vn";
18
+ /** The loopback port the daemon's hook endpoint is tried on first: not TicketFlow's 8976, so the two can run side by side. */
19
+ export const HOOK_PORT_FIRST = 8975;
20
+ /** How many ports from `HOOK_PORT_FIRST` are tried (8975 to 8999). */
21
+ const HOOK_PORT_TRIES = 25;
22
+ /** The relay's device socket, below its origin. */
23
+ const DEVICE_PATH = "/v1/device";
24
+ const RECORD_FILE = "install.json";
25
+
26
+ /** @param {string} value Text to hash. @returns {string} Its SHA-256 as hex (what `install.json` keeps instead of the token). */
27
+ function sha256(value) {
28
+ return createHash("sha256").update(value).digest("hex");
29
+ }
30
+ /**
31
+ * What the installer did, kept so `disconnect` and `remote status` undo and report exactly that.
32
+ * @typedef {object} InstallRecord
33
+ * @property {string} pool Pool address the computer is paired with.
34
+ * @property {string} version Installed daemon version.
35
+ * @property {string} deviceName The computer's name on the pool.
36
+ * @property {string} tokenSha256 SHA-256 of the device token, to recognise our own `relay.json`.
37
+ * @property {string} relayFile Path of the `relay.json` written.
38
+ * @property {string} [claudeDir] Claude Code's config folder the hooks went into.
39
+ * @property {{ binDir: string, targets: Array<{ kind: string, file?: string }> }} [shim] The launcher and where PATH was edited.
40
+ * @property {import("./launcher-precedence.js").LauncherRecord} [launcher] What was done to make `claude` start the launcher on Windows (profiles, execution policy, Machine Path).
41
+ */
42
+ /**
43
+ * @param {string} root The Remote folder.
44
+ * @returns {InstallRecord | undefined} The record, or undefined when there is none.
45
+ */
46
+ export function readRecord(root) {
47
+ try {
48
+ return JSON.parse(readFileSync(join(root, RECORD_FILE), "utf8"));
49
+ } catch {
50
+ return undefined;
51
+ }
52
+ }
53
+ /**
54
+ * Merge fields into the record (created when missing), so a half-finished install still leaves what `disconnect` needs.
55
+ * @param {string} root The Remote folder.
56
+ * @param {Partial<InstallRecord>} patch The fields to set.
57
+ * @returns {void}
58
+ */
59
+ function saveRecord(root, patch) {
60
+ mkdirSync(root, { recursive: true });
61
+ writeFileSync(join(root, RECORD_FILE), `${JSON.stringify({ ...readRecord(root), ...patch }, null, 2)}\n`);
62
+ }
63
+ /**
64
+ * @param {string} file Path of `relay.json`.
65
+ * @returns {Record<string, any> | undefined} Its contents, or undefined when it is missing or not a JSON object.
66
+ */
67
+ export function readRelayJson(file) {
68
+ try {
69
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
70
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : undefined;
71
+ } catch {
72
+ return undefined;
73
+ }
74
+ }
75
+ /**
76
+ * The relay's address from what the pool said: its origin when that is `https` (or `http` on a loopback host, for development), else the default.
77
+ * @param {string | undefined} origin What `POST /pair/remote/check` returned (empty when the pool has none).
78
+ * @returns {string} An origin without a trailing slash.
79
+ */
80
+ export function relayOriginFor(origin) {
81
+ try {
82
+ const url = new URL(String(origin));
83
+ const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
84
+ if ((url.protocol === "https:" || (url.protocol === "http:" && loopback)) && !url.username && !url.password) return url.origin;
85
+ } catch {
86
+ // not a URL: use the default
87
+ }
88
+ return DEFAULT_RELAY_ORIGIN;
89
+ }
90
+ /**
91
+ * The daemon's device socket for a relay origin (`https://x` becomes `wss://x/v1/device`).
92
+ * @param {string} origin A relay origin.
93
+ * @returns {string} The URL for `relay.json`.
94
+ */
95
+ export function relayUrlFor(origin) {
96
+ return `${origin.replace(/^http/, "ws")}${DEVICE_PATH}`;
97
+ }
98
+ /**
99
+ * The first free loopback port from `HOOK_PORT_FIRST`: the one `relay.json` names as `hookPort`, so the hook script of a hosted session
100
+ * reaches this daemon and never TicketFlow's server. A port is free when a listener can bind it on 127.0.0.1.
101
+ * @param {(port: number) => Promise<boolean>} [isFree] Whether a port can be bound (tests replace it).
102
+ * @returns {Promise<number | undefined>} The port, or undefined when every one tried is taken (the daemon then uses its own default).
103
+ */
104
+ export async function pickHookPort(isFree = canBind) {
105
+ for (let port = HOOK_PORT_FIRST; port < HOOK_PORT_FIRST + HOOK_PORT_TRIES; port++) if (await isFree(port)) return port;
106
+ return undefined;
107
+ }
108
+ /** @param {number} port A TCP port. @returns {Promise<boolean>} Whether a listener can bind it on 127.0.0.1 right now. */
109
+ function canBind(port) {
110
+ return new Promise((resolve) => {
111
+ const server = createServer();
112
+ server.once("error", () => resolve(false));
113
+ server.listen(port, "127.0.0.1", () => server.close(() => resolve(true)));
114
+ });
115
+ }
116
+ /**
117
+ * Write `relay.json` readable only by the current user: created with mode 0600 and renamed into place (POSIX), or with the folder's
118
+ * inherited access removed and only this user granted (Windows, `icacls`; skipped when that cannot be done safely).
119
+ * @param {string} file Path of `relay.json`.
120
+ * @param {Record<string, any>} contents What to write.
121
+ * @param {object} io
122
+ * @param {string} io.platform Node platform name.
123
+ * @param {Record<string, string | undefined>} io.env Environment (for the user name).
124
+ * @param {import("./run.js").Runner} io.run Runs `icacls`.
125
+ * @returns {Promise<boolean>} Whether the access was restricted (false: the folder's default access applies).
126
+ */
127
+ export async function writeRelayJson(file, contents, { platform, env, run }) {
128
+ mkdirSync(dirname(file), { recursive: true });
129
+ const temp = `${file}.${randomBytes(3).toString("hex")}.tmp`;
130
+ writeFileSync(temp, `${JSON.stringify(contents, null, 2)}\n`, { mode: 0o600 });
131
+ let restricted = true;
132
+ if (platform === "win32") {
133
+ const user = env.USERNAME;
134
+ // Grant first, remove inheritance only when that worked: never leave a file nobody can read.
135
+ restricted = Boolean(user) && (await run("icacls", [temp, "/grant:r", `${user}:F`])).code === 0 && (await run("icacls", [temp, "/inheritance:r"])).code === 0;
136
+ } else {
137
+ chmodSync(temp, 0o600);
138
+ }
139
+ renameSync(temp, file);
140
+ return restricted;
141
+ }
142
+ /**
143
+ * Run the hook script's own `install` or `uninstall` for a Claude config folder. The script keeps the backup and prints the diff.
144
+ * @param {"install" | "uninstall"} verb What to do.
145
+ * @param {object} options
146
+ * @param {string} options.script The installed `tf-remote-hook.mjs`.
147
+ * @param {string} options.claudeDir Claude Code's config folder (`settings.json` and `commands/` are in it).
148
+ * @param {string} options.node The Node program to run it with.
149
+ * @param {import("./run.js").Runner} options.run Runs a program.
150
+ * @returns {Promise<{ ok: boolean, output: string[] }>} Whether it succeeded, and the lines it printed (or its error).
151
+ */
152
+ async function runHookScript(verb, { script, claudeDir, node, run }) {
153
+ const result = await run(node, [script, verb, "--dir", claudeDir]);
154
+ const lines = (result.code === 0 ? result.stdout : result.stderr || result.stdout).split(/\r?\n/).filter((line) => line.trim() !== "");
155
+ return { ok: result.code === 0, output: lines };
156
+ }
157
+ /**
158
+ * Set up TokenHub Remote on this computer (the step `connect` offers after the settings are written).
159
+ *
160
+ * In order: download the daemon (verified, nothing in place before it checks out); pair this computer with the `remote` kind, or keep
161
+ * the token it already has when the pool still accepts it; write `relay.json` for the daemon; install the Claude Code hooks and
162
+ * `/tf-remote` by running the hook script's own `install`; and, after asking, the `claude` launcher and its PATH entry. The download
163
+ * comes first so a failed download does not leave a pairing behind. What was done is recorded in `<remote>/install.json` as it goes.
164
+ *
165
+ * @param {object} options
166
+ * @param {string} options.pool Pool address from `resolvePoolUrl`.
167
+ * @param {string} [options.baseUrl] Address the key was issued by (the public origin); defaults to `pool`.
168
+ * @param {string} options.settingsFile Claude Code's `settings.json`; its folder gets the hooks and `/tf-remote`.
169
+ * @param {"en" | "vi"} [options.lang] Message language.
170
+ * @param {(line: string) => void} [options.log] Output sink.
171
+ * @param {(url: string) => void} options.open Browser opener.
172
+ * @param {AbortSignal} [options.signal] Aborts the flow (Ctrl+C).
173
+ * @param {(question: string, defaultYes?: boolean) => Promise<boolean>} options.ask Yes/no prompt (false without a terminal).
174
+ * @param {boolean} [options.shim] `true`/`false` skips the launcher question.
175
+ * @param {string} [options.deviceName] Name for this computer on the pool.
176
+ * @param {number} [options.intervalOverrideMs] Pairing poll interval override (tests).
177
+ * @param {Record<string, string | undefined>} [options.env] Environment.
178
+ * @param {string} options.home Home directory.
179
+ * @param {string} [options.platform] Node platform name.
180
+ * @param {string} [options.arch] Node architecture name.
181
+ * @param {string} [options.node] Node program that runs the hook script (this one by default).
182
+ * @param {typeof fetch} [options.fetchImpl] `fetch` override for tests.
183
+ * @param {import("./run.js").Runner} [options.run] Process runner for `xattr`, `icacls` and the hook script (tests replace it).
184
+ * @param {ReturnType<typeof windowsUserPath>} [options.userPath] Registry access for the PATH edit (tests replace it).
185
+ * @param {typeof pickHookPort} [options.pickPort] Chooses the hook port when `relay.json` has none (tests replace it).
186
+ * @param {import("./launcher-precedence.js").WinSystem} [options.launcherSys] Windows access for the launcher check: Machine Path, PowerShell profiles and policies, elevation (tests replace it).
187
+ * @returns {Promise<{ ok: true, version: string, shim: boolean, launcher?: string } | { ok: false, code: number }>} The outcome (`launcher`: what makes `claude` start it on Windows, see `ensureLauncher`); on failure the exit code.
188
+ */
189
+ export async function installRemote({
190
+ pool,
191
+ baseUrl,
192
+ settingsFile,
193
+ lang = detectLang(),
194
+ log = console.log,
195
+ open,
196
+ signal,
197
+ ask,
198
+ shim,
199
+ deviceName = hostname(),
200
+ intervalOverrideMs,
201
+ env = process.env,
202
+ home,
203
+ platform = process.platform,
204
+ arch = process.arch,
205
+ node = process.execPath,
206
+ fetchImpl = fetch,
207
+ run = defaultRun,
208
+ userPath,
209
+ pickPort = pickHookPort,
210
+ launcherSys,
211
+ }) {
212
+ const t = text(lang);
213
+ if (platform !== "win32" && platform !== "darwin") {
214
+ log(t.unsupported(platform));
215
+ return { ok: false, code: 1 };
216
+ }
217
+ const root = remoteDir(env, home);
218
+ const binDir = shimDir(env, home);
219
+ const relayFile = join(appConfigDir(env, home), "relay.json");
220
+ const legacyFile = join(legacyConfigDir(env, home), "relay.json");
221
+ const claudeDir = dirname(settingsFile);
222
+ let origin = baseUrl ?? pool;
223
+
224
+ log("");
225
+ log(t.downloading);
226
+ let download;
227
+ try {
228
+ download = await downloadRemote({ pool, root, platform, arch, log, fetchImpl, signal, run });
229
+ } catch (error) {
230
+ log(t.failed(error.message));
231
+ return { ok: false, code: 1 };
232
+ }
233
+ log(download.action === "updated" ? t.updated(download.version, download.previous) : download.action === "repaired" ? t.repaired(download.version) : download.action === "kept" ? t.kept(download.version) : t.installed(download.version));
234
+ saveRecord(root, { version: download.version });
235
+
236
+ // Keep the token this computer already has unless the pool says it was revoked (or it is for another pool).
237
+ const record = readRecord(root);
238
+ let existing = readRelayJson(relayFile);
239
+ // Version 0.1.0 wrote relay.json into TicketFlow's config folder. When that file is ours, its token carries over and the file goes
240
+ // (it made TicketFlow's own `tfc` start our daemon); its port is dropped, it was TicketFlow's.
241
+ let legacy = false;
242
+ if (!existing) {
243
+ const old = readRelayJson(legacyFile);
244
+ if (old?.deviceToken && record?.tokenSha256 === sha256(old.deviceToken)) {
245
+ const { hookPort: _theirs, ...rest } = old;
246
+ existing = rest;
247
+ legacy = true;
248
+ }
249
+ }
250
+ let token;
251
+ let name = deviceName;
252
+ let relayOrigin;
253
+ if (existing?.deviceToken && record?.pool === origin && record.tokenSha256 === sha256(existing.deviceToken)) {
254
+ const check = await checkRemoteToken({ pool: origin, token: existing.deviceToken, signal, fetchImpl });
255
+ if (check.status !== "revoked") {
256
+ token = existing.deviceToken;
257
+ name = check.status === "valid" ? check.deviceName : (existing.name ?? deviceName);
258
+ relayOrigin = check.status === "valid" ? check.relayOrigin : undefined;
259
+ log(t.keepingToken(name));
260
+ }
261
+ }
262
+ if (!token) {
263
+ log(t.pairing);
264
+ const paired = await pairRemote({ pool, deviceName, log, open, signal, intervalOverrideMs, fetchImpl });
265
+ if (!paired.ok) {
266
+ log(t.pairingFailed);
267
+ return { ok: false, code: paired.code };
268
+ }
269
+ token = paired.token;
270
+ origin = paired.baseUrl;
271
+ const check = await checkRemoteToken({ pool: origin, token, signal, fetchImpl });
272
+ name = check.status === "valid" ? check.deviceName : deviceName;
273
+ relayOrigin = check.status === "valid" ? check.relayOrigin : undefined;
274
+ }
275
+ const relayUrl = relayUrlFor(relayOriginFor(relayOrigin ?? relayOriginFromFile(existing)));
276
+ // Keep other keys of an existing relay.json (a hook port, say); the three the daemon needs are ours. A new file gets a free hook port.
277
+ const hookPort = existing?.hookPort ?? (await pickPort());
278
+ const restricted = await writeRelayJson(relayFile, { ...existing, relayUrl, deviceToken: token, name, ...(hookPort ? { hookPort } : {}) }, { platform, env, run });
279
+ if (!restricted) log(`(could not restrict access to ${relayFile}; the folder's own permissions apply)`);
280
+ if (legacy) {
281
+ rmSync(legacyFile, { force: true });
282
+ log(t.movedConfig(legacyFile, relayFile));
283
+ }
284
+ saveRecord(root, { pool: origin, deviceName: name, tokenSha256: sha256(token), relayFile });
285
+
286
+ log(t.hooks);
287
+ const hooks = await runHookScript("install", { script: join(download.dir, HOOK_FILE), claudeDir, node, run });
288
+ for (const line of hooks.output) log(` ${line}`);
289
+ if (!hooks.ok) {
290
+ log(t.hooksFailed(hooks.output.at(-1) ?? "?"));
291
+ return { ok: false, code: 1 };
292
+ }
293
+ saveRecord(root, { claudeDir });
294
+
295
+ const registry = userPath ?? windowsUserPath({ run });
296
+ const shimOn = await offerShim({ shim, ask, log, t, binDir, platform, env, home, node, run, userPath: registry, root });
297
+ // Windows: the user Path is only half of what a new process gets (the Machine Path comes first), so check that `claude` would win.
298
+ let launcher = shimOn && platform === "win32" ? await ensureLauncher({ binDir, env, userPath: registry, sys: launcherSys ?? realWindowsSystem({ run }), ask, log, t, previous: record?.launcher }) : undefined;
299
+ if (launcher) saveRecord(root, { launcher: launcher.record });
300
+ const tfc = join(download.dir, exeName("tfc", platform));
301
+ const claudeCmd = join(binDir, "claude.cmd");
302
+ log("");
303
+ log(t.done(download.version));
304
+ log(t.lineComputer(name));
305
+ log(t.linePage(`${origin}/member/remote`));
306
+ log(t.lineHooks(claudeDir));
307
+ log(t.lineShim(shimOn && launcher?.how !== "none"));
308
+ if (launcher?.how === "profile") log(t.noteProfile);
309
+ log(!shimOn ? t.nextNoShim(tfc) : launcher?.how === "profile" ? t.nextProfile : launcher?.how === "none" ? t.nextByHand(claudeCmd) : t.next);
310
+ return { ok: true, version: download.version, shim: shimOn, launcher: launcher?.how };
311
+ }
312
+ /** @param {Record<string, any> | undefined} existing An existing `relay.json`. @returns {string | undefined} The origin its `relayUrl` was made from. */
313
+ function relayOriginFromFile(existing) {
314
+ try {
315
+ const url = new URL(String(existing?.relayUrl).replace(/^ws/, "http"));
316
+ return url.origin;
317
+ } catch {
318
+ return undefined;
319
+ }
320
+ }
321
+ /**
322
+ * The launcher step: explain it, ask (unless a flag or an earlier install already decided), write the shim, edit PATH.
323
+ *
324
+ * @param {object} options What `installRemote` has: `shim`, `ask`, `log`, `t`, `binDir`, `platform`, `env`, `home`, `run`, `userPath`, `root`.
325
+ * @returns {Promise<boolean>} Whether the launcher is installed afterwards.
326
+ */
327
+ async function offerShim({ shim, ask, log, t, binDir, platform, env, home, run, userPath, root }) {
328
+ const already = shimInstalled(binDir, platform);
329
+ let want = shim ?? already;
330
+ if (shim === undefined && !already) {
331
+ for (const line of t.shimIntro(binDir, platform === "win32" ? t.wherePath : t.whereProfile)) log(line);
332
+ want = await ask(t.askShim, true);
333
+ }
334
+ if (!want) {
335
+ log(t.shimSkipped);
336
+ log(` ${join(readCurrent(root)?.dir ?? "", exeName("tfc", platform))}`);
337
+ log(t.shimSkippedHint);
338
+ return false;
339
+ }
340
+ const realClaude = findRealClaude({ pathValue: env.PATH ?? env.Path ?? "", shimDirs: [binDir], env, platform, home });
341
+ if (!realClaude) log(t.shimNoClaude);
342
+ installShimFiles({ binDir, platform, realClaude });
343
+ log(t.shimOn(binDir));
344
+ try {
345
+ const edited = await addBinToPath({ dir: binDir, platform, home, userPath: userPath ?? windowsUserPath({ run }) });
346
+ saveRecord(root, { shim: { binDir, targets: edited.targets } });
347
+ } catch (error) {
348
+ saveRecord(root, { shim: { binDir, targets: [] } });
349
+ log(t.shimPathFailed(error.message));
350
+ }
351
+ return true;
352
+ }
353
+
354
+ /**
355
+ * The process-level facts the daemon check needs; tests replace them.
356
+ * @typedef {object} Proc
357
+ * @property {(pid: number) => boolean} isAlive Whether a process with this id exists.
358
+ * @property {(pid: number) => Promise<string | undefined>} imagePath The program file of a process.
359
+ * @property {(pid: number) => Promise<void>} stop Ends a process and waits for it to go.
360
+ */
361
+ /**
362
+ * @param {string} platform Node platform name.
363
+ * @param {import("./run.js").Runner} run Process runner.
364
+ * @returns {Proc} The real thing.
365
+ */
366
+ export function realProc(platform, run) {
367
+ const isAlive = (pid) => {
368
+ try {
369
+ process.kill(pid, 0);
370
+ return true;
371
+ } catch (error) {
372
+ return error.code === "EPERM";
373
+ }
374
+ };
375
+ return {
376
+ isAlive,
377
+ async imagePath(pid) {
378
+ const result =
379
+ platform === "win32"
380
+ ? await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", `[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false; (Get-Process -Id ${pid} -ErrorAction SilentlyContinue).Path`])
381
+ : await run("ps", ["-p", String(pid), "-o", "comm="]);
382
+ return result.stdout.trim() || undefined;
383
+ },
384
+ async stop(pid) {
385
+ if (platform === "win32") await run("taskkill", ["/PID", String(pid), "/T", "/F"]);
386
+ else process.kill(pid, "SIGTERM");
387
+ for (let i = 0; i < 50 && isAlive(pid); i++) await new Promise((resolve) => setTimeout(resolve, 100));
388
+ if (isAlive(pid) && platform !== "win32") process.kill(pid, "SIGKILL");
389
+ },
390
+ };
391
+ }
392
+ /**
393
+ * What runs for this computer's `host.json`: ours (a `tfr` under the Remote folder), someone else's (TicketFlow's `tf-host`), or nothing.
394
+ *
395
+ * @param {object} options
396
+ * @param {string} options.appDir The app config folder (`host.json` is in it).
397
+ * @param {string} options.root The Remote folder.
398
+ * @param {string} options.platform Node platform name.
399
+ * @param {Proc} options.proc Process facts.
400
+ * @returns {Promise<{ state: "running" | "other" | "stopped", pid?: number }>} A pid that is gone, or a stale file, is `stopped`.
401
+ */
402
+ export async function daemonState({ appDir, root, platform, proc }) {
403
+ let pid;
404
+ try {
405
+ pid = Number(JSON.parse(readFileSync(join(appDir, "host.json"), "utf8")).pid);
406
+ } catch {
407
+ return { state: "stopped" };
408
+ }
409
+ if (!Number.isInteger(pid) || pid <= 0 || !proc.isAlive(pid)) return { state: "stopped" };
410
+ const image = await proc.imagePath(pid);
411
+ // Resolved first: the same folder can be spelled with 8.3 short names (Windows) or through a symlink (macOS /tmp).
412
+ const canonical = (path) => {
413
+ try {
414
+ return realpathSync.native(path);
415
+ } catch {
416
+ try {
417
+ return join(realpathSync.native(dirname(path)), basename(path));
418
+ } catch {
419
+ return path;
420
+ }
421
+ }
422
+ };
423
+ const inside = image !== undefined && normalizeDir(canonical(image), platform).startsWith(`${normalizeDir(canonical(root), platform)}${platform === "win32" ? "\\" : "/"}`);
424
+ return { state: inside ? "running" : "other", pid };
425
+ }
426
+ /**
427
+ * Stop the Remote daemon before its files are removed, unless it still hosts sessions. A daemon that is not ours is left alone.
428
+ *
429
+ * Sessions are counted with `tfc ls`, which only connects (the daemon is known to be up). With sessions, or when they cannot be
430
+ * counted, nothing is stopped unless `force`: stopping the daemon ends the Claude sessions it hosts.
431
+ *
432
+ * @param {object} options
433
+ * @param {string} options.appDir The app config folder.
434
+ * @param {string} options.root The Remote folder.
435
+ * @param {string} options.platform Node platform name.
436
+ * @param {boolean} [options.force] Stop it even with sessions.
437
+ * @param {Record<string, string | undefined>} options.env Environment for `tfc`.
438
+ * @param {Proc} options.proc Process facts.
439
+ * @param {import("./run.js").Runner} options.run Runs `tfc ls`.
440
+ * @returns {Promise<{ status: "none" | "other" | "stopped" } | { status: "busy", sessions?: number }>} What happened.
441
+ */
442
+ export async function stopDaemon({ appDir, root, platform, force = false, env, proc, run }) {
443
+ const state = await daemonState({ appDir, root, platform, proc });
444
+ if (state.state === "stopped") return { status: "none" };
445
+ if (state.state === "other") return { status: "other" };
446
+ if (!force) {
447
+ const current = readCurrent(root);
448
+ const tfc = current ? join(current.dir, exeName("tfc", platform)) : undefined;
449
+ const listed = tfc && existsSync(tfc) ? await run(tfc, ["ls"], { env: { ...env, TFR_CONFIG_DIR: appDir }, timeoutMs: 10_000 }) : undefined;
450
+ if (!listed || listed.code !== 0) return { status: "busy" };
451
+ const rows = listed.stdout.split(/\r?\n/).filter((line) => line.trim() !== "");
452
+ if (!(rows.length === 1 && rows[0].trim() === "no sessions")) return { status: "busy", sessions: Math.max(0, rows.length - 1) };
453
+ }
454
+ await proc.stop(state.pid);
455
+ return { status: "stopped" };
456
+ }
457
+ /**
458
+ * Undo what `installRemote` did, in the reverse of the useful order; only files and lines the installer wrote are touched.
459
+ *
460
+ * Stops the daemon (refusing, with nothing changed, while it hosts sessions unless `force`), revokes the token on the pool, runs the
461
+ * hook script's `uninstall`, takes the launcher out of PATH and deletes it, deletes `relay.json` (only when it still holds our token),
462
+ * and deletes the Remote folder. A step that fails is reported and the rest still run.
463
+ *
464
+ * @param {object} options
465
+ * @param {string} options.settingsFile Claude Code's `settings.json` (its folder is the fallback for the hooks' place).
466
+ * @param {"en" | "vi"} [options.lang] Message language.
467
+ * @param {(line: string) => void} [options.log] Output sink.
468
+ * @param {boolean} [options.force] Stop the daemon even with sessions running.
469
+ * @param {Record<string, string | undefined>} [options.env] Environment.
470
+ * @param {string} options.home Home directory.
471
+ * @param {string} [options.platform] Node platform name.
472
+ * @param {string} [options.node] Node program that runs the hook script.
473
+ * @param {typeof fetch} [options.fetchImpl] `fetch` override for tests.
474
+ * @param {import("./run.js").Runner} [options.run] Process runner.
475
+ * @param {Proc} [options.proc] Process facts (tests replace them).
476
+ * @param {ReturnType<typeof windowsUserPath>} [options.userPath] Registry access (tests replace it).
477
+ * @param {import("./launcher-precedence.js").WinSystem} [options.launcherSys] Windows access for undoing the launcher fix (tests replace it).
478
+ * @returns {Promise<{ found: boolean, blocked: boolean }>} `found`: there was something of Remote to remove. `blocked`: it was not removed because sessions run.
479
+ */
480
+ export async function disconnectRemote({ settingsFile, lang = detectLang(), log = console.log, force = false, env = process.env, home, platform = process.platform, node = process.execPath, fetchImpl = fetch, run = defaultRun, proc, userPath, launcherSys }) {
481
+ const t = text(lang);
482
+ const root = remoteDir(env, home);
483
+ const binDir = shimDir(env, home);
484
+ const appDir = appConfigDir(env, home);
485
+ const record = readRecord(root);
486
+ const profileHasBlock = platform === "darwin" && profileFiles(home).some(({ file }) => existsSync(file) && readFileSync(file, "utf8").includes(PROFILE_BEGIN));
487
+ if (!record && !existsSync(root) && !shimPresent(binDir, platform) && !profileHasBlock) return { found: false, blocked: false };
488
+
489
+ const relayFile = record?.relayFile ?? join(appDir, "relay.json");
490
+ // The daemon's folder is the one relay.json is in (an install of 0.1.0 used TicketFlow's, where `daemonState` leaves a daemon that is not ours alone).
491
+ const stop = await stopDaemon({ appDir: dirname(relayFile), root, platform, force, env, proc: proc ?? realProc(platform, run), run });
492
+ if (stop.status === "busy") {
493
+ log(t.busy(stop.sessions));
494
+ return { found: true, blocked: true };
495
+ }
496
+ if (stop.status === "stopped") log(t.stopped);
497
+ const relay = readRelayJson(relayFile);
498
+ const ours = Boolean(record?.tokenSha256 && relay?.deviceToken && sha256(relay.deviceToken) === record.tokenSha256);
499
+ if (ours && record.pool) {
500
+ const outcome = await revokeRemoteToken({ pool: record.pool, token: relay.deviceToken, fetchImpl });
501
+ log(outcome === "revoked" ? t.revoked : outcome === "already" ? t.revokedAlready : t.revokeFailed(`${record.pool}/member/remote`));
502
+ }
503
+
504
+ const claudeDir = record?.claudeDir ?? dirname(settingsFile);
505
+ const current = readCurrent(root);
506
+ const script = current ? join(current.dir, HOOK_FILE) : undefined;
507
+ if (script && existsSync(script)) {
508
+ const hooks = await runHookScript("uninstall", { script, claudeDir, node, run });
509
+ if (hooks.ok) log(t.hooksRemoved);
510
+ else log(t.hooksStay(claudeDir));
511
+ } else if (settingsMentionsHook(join(claudeDir, "settings.json"))) {
512
+ log(t.hooksStay(claudeDir));
513
+ }
514
+
515
+ if (platform === "win32" && record?.launcher) await removeLauncher({ record: record.launcher, sys: launcherSys ?? realWindowsSystem({ run }), log, t });
516
+ if (record?.shim || shimPresent(binDir, platform) || profileHasBlock) {
517
+ const wasInRegistry = platform === "win32" && Boolean(record?.shim?.targets?.some((target) => target.kind === "registry"));
518
+ if (platform === "darwin" || wasInRegistry) {
519
+ try {
520
+ const removed = await removeBinFromPath({ dir: record?.shim?.binDir ?? binDir, platform, home, userPath: userPath ?? windowsUserPath({ run }) });
521
+ if (removed.changed) log(t.pathRemoved);
522
+ } catch (error) {
523
+ log(t.pathFailed(error.message));
524
+ }
525
+ }
526
+ if (removeShimFiles(binDir, platform).length > 0) log(t.shimRemoved);
527
+ }
528
+
529
+ if (ours) rmSync(relayFile, { force: true });
530
+ try {
531
+ rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 300 }); // a client (tfc) of the daemon just stopped may take a moment to exit and free its file
532
+ log(t.remoteRemoved);
533
+ } catch (error) {
534
+ log(t.notRemoved(error.message));
535
+ }
536
+ return { found: true, blocked: false };
537
+ }
538
+ /**
539
+ * What a NEW terminal on Windows would do with `claude`, when this terminal's own PATH does not reach the launcher: read the Machine and User Path
540
+ * from the registry (the way a new process builds its Path), and look for our PowerShell profile function.
541
+ * @param {object} options `binDir`, `env`, `record` (install.json), `userPath` (registry User Path), `sys` (Machine Path).
542
+ * @returns {Promise<"new-terminals" | "powershell-only" | "installed">} The first when the launcher wins by PATH (this terminal started earlier), the second when only the profile function does.
543
+ */
544
+ async function windowsLauncherState({ binDir, env, record, userPath, sys }) {
545
+ try {
546
+ const [machine, user] = await Promise.all([sys.machinePath(), userPath.get()]);
547
+ if (launcherWins({ machine: machine.value, user: user.value, env, binDir }).ours) return "new-terminals";
548
+ } catch {
549
+ // Unreadable: fall through to what the record says.
550
+ }
551
+ return record?.launcher?.profiles?.some((profile) => hasPsBlock(profile.file)) ? "powershell-only" : "installed";
552
+ }
553
+ /** @param {string} file Path of a settings file. @returns {boolean} Whether it mentions the hook script (entries of ours that could not be removed). */
554
+ function settingsMentionsHook(file) {
555
+ try {
556
+ return readFileSync(file, "utf8").includes(HOOK_FILE);
557
+ } catch {
558
+ return false;
559
+ }
560
+ }
561
+ /**
562
+ * `tokenhub remote status`: what is installed, whether the daemon runs, the relay configuration and the launcher, and where the member's
563
+ * Remote page is. Changes nothing.
564
+ *
565
+ * @param {object} options
566
+ * @param {string} options.settingsFile Claude Code's `settings.json`.
567
+ * @param {"en" | "vi"} [options.lang] Message language.
568
+ * @param {(line: string) => void} [options.log] Output sink.
569
+ * @param {Record<string, string | undefined>} [options.env] Environment (its PATH shows whether `claude` resolves to the launcher).
570
+ * @param {string} options.home Home directory.
571
+ * @param {string} [options.platform] Node platform name.
572
+ * @param {import("./run.js").Runner} [options.run] Process runner.
573
+ * @param {Proc} [options.proc] Process facts.
574
+ * @param {ReturnType<typeof windowsUserPath>} [options.userPath] Registry access (tests replace it).
575
+ * @param {import("./launcher-precedence.js").WinSystem} [options.launcherSys] Windows access (tests replace it).
576
+ * @returns {Promise<number>} 0 when installed, 1 when not.
577
+ */
578
+ export async function remoteStatus({ settingsFile, lang = detectLang(), log = console.log, env = process.env, home, platform = process.platform, run = defaultRun, proc, userPath, launcherSys }) {
579
+ const t = text(lang);
580
+ const root = remoteDir(env, home);
581
+ const binDir = shimDir(env, home);
582
+ const appDir = appConfigDir(env, home);
583
+ const record = readRecord(root);
584
+ const current = readCurrent(root);
585
+ if (!record && !current) {
586
+ log(t.notInstalled);
587
+ return 1;
588
+ }
589
+ if (current) log(t.statusVersion(current.version, current.dir));
590
+ const relayFile = record?.relayFile ?? join(appDir, "relay.json");
591
+ const daemon = await daemonState({ appDir: dirname(relayFile), root, platform, proc: proc ?? realProc(platform, run) });
592
+ log(t.statusDaemon(daemon.state, daemon.pid));
593
+ const relay = readRelayJson(relayFile);
594
+ if (relay?.relayUrl && relay.deviceToken) {
595
+ log(t.statusDevice(relay.name || record?.deviceName || "?"));
596
+ log(t.statusRelay(relay.relayUrl));
597
+ } else {
598
+ log(t.statusNoRelay);
599
+ }
600
+ let shimState = "off";
601
+ if (shimInstalled(binDir, platform)) {
602
+ const first = findOnPath(platform === "win32" ? ["claude.exe", "claude.cmd"] : ["claude"], env.PATH ?? env.Path ?? "", { platform });
603
+ shimState = first && normalizeDir(dirname(first), platform) === normalizeDir(binDir, platform) ? "active" : "installed";
604
+ if (shimState === "installed" && platform === "win32") shimState = await windowsLauncherState({ binDir, env, record, userPath: userPath ?? windowsUserPath({ run }), sys: launcherSys ?? realWindowsSystem({ run }) });
605
+ }
606
+ log(t.statusShim(shimState));
607
+ const claudeDir = record?.claudeDir ?? dirname(settingsFile);
608
+ log(t.statusHooks(settingsMentionsHook(join(claudeDir, "settings.json")) && existsSync(join(claudeDir, "commands", "tf-remote.md"))));
609
+ if (record?.pool) log(t.statusPage(`${record.pool}/member/remote`));
610
+ return 0;
611
+ }
@@ -0,0 +1,7 @@
1
+ export function tokenhubDir(env?: Record<string, string | undefined>, home?: string): string;
2
+ export function remoteDir(env?: Record<string, string | undefined>, home?: string): string;
3
+ export function shimDir(env?: Record<string, string | undefined>, home?: string): string;
4
+ export function appConfigDir(env?: Record<string, string | undefined>, home?: string): string;
5
+ export function legacyConfigDir(env?: Record<string, string | undefined>, home?: string): string;
6
+ export function exeName(base: string, platform?: string): string;
7
+ export function platformKeys(platform: string, arch: string): string[];