@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,430 @@
1
+ // Making the `claude` launcher win on Windows (TokenHub Remote, ADR-0058).
2
+ //
3
+ // Putting `~/.tokenhub/bin` first in the USER Path is not enough: a new process gets the MACHINE Path followed by the USER Path, so a
4
+ // real `claude.exe` in a Machine Path folder still comes first. This module computes what a new process would resolve `claude` to
5
+ // (the registry's two Path values, expanded, in order, with PATHEXT), and when the launcher would not win it offers, in order:
6
+ // a. a `claude` function in the CurrentUser AllHosts profile of Windows PowerShell 5.1 and PowerShell 7 (no admin; asks before it
7
+ // allows profiles to run when the execution policy blocks them),
8
+ // b. an entry in the Machine Path before the real claude's folder (one UAC prompt),
9
+ // c. otherwise it says how to start a remote-ready session by hand.
10
+ // Everything that touches the system (registry, shells, elevation) goes through a `WinSystem`, so tests inject fakes.
11
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
12
+ import { dirname, win32 } from "node:path";
13
+ import { run as defaultRun } from "./run.js";
14
+ import { addPathEntry, hasPathEntry, PROFILE_BEGIN, PROFILE_END, removePathEntry, removeProfileBlock } from "./user-path.js";
15
+
16
+ /** The default PATHEXT of Windows, used when the environment has none. */
17
+ const DEFAULT_PATHEXT = ".COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC";
18
+ /** The execution policies that stop a profile from running. */
19
+ const BLOCKING = new Set(["restricted", "allsigned"]);
20
+ /** The scopes whose policy a change to `CurrentUser` can override (the group-policy scopes and `Process` cannot be). */
21
+ const OVERRIDABLE_SOURCES = new Set(["CurrentUser", "LocalMachine", "default"]);
22
+
23
+ /**
24
+ * `%NAME%` references replaced from an environment (names compare without case, as on Windows); unknown names stay as they are.
25
+ * @param {string} text A Path entry.
26
+ * @param {Record<string, string | undefined>} env Environment.
27
+ * @returns {string} The expanded text.
28
+ */
29
+ export function expandEnv(text, env) {
30
+ const lower = new Map(Object.entries(env).map(([name, value]) => [name.toLowerCase(), value]));
31
+ return text.replace(/%([^%]+)%/g, (whole, name) => lower.get(name.toLowerCase()) ?? whole);
32
+ }
33
+ /** @param {string} dir A folder. @returns {string} It in the form folders are compared in (absolute-looking, lower case, no trailing slash). */
34
+ function same(dir) {
35
+ return win32.normalize(dir.trim().replace(/^"(.*)"$/, "$1")).replace(/[\\/]+$/, "").toLowerCase();
36
+ }
37
+ /**
38
+ * The folders a new process searches, in order: the Machine Path, then the User Path, each entry unquoted and expanded; empty entries
39
+ * and later duplicates go.
40
+ * @param {string | null} machine The Machine `Path` as stored (may hold `%VAR%`).
41
+ * @param {string | null} user The User `Path` as stored.
42
+ * @param {Record<string, string | undefined>} env Environment to expand `%VAR%` from (USERPROFILE, SystemRoot...).
43
+ * @returns {string[]} The folders.
44
+ */
45
+ export function effectiveDirs(machine, user, env) {
46
+ const seen = new Set();
47
+ const dirs = [];
48
+ for (const raw of [...String(machine ?? "").split(";"), ...String(user ?? "").split(";")]) {
49
+ const entry = expandEnv(raw.trim().replace(/^"(.*)"$/, "$1"), env);
50
+ if (!entry || seen.has(same(entry))) continue;
51
+ seen.add(same(entry));
52
+ dirs.push(entry);
53
+ }
54
+ return dirs;
55
+ }
56
+ /**
57
+ * What `name` resolves to as a program: the first folder holding `name` with an extension of PATHEXT (in PATHEXT's order within the folder).
58
+ * cmd.exe and PowerShell (after its functions and aliases) search the same way.
59
+ * @param {string} name The command without extension.
60
+ * @param {string[]} dirs The folders, in order.
61
+ * @param {object} [options]
62
+ * @param {string} [options.pathext] PATHEXT.
63
+ * @param {(file: string) => boolean} [options.exists] File check (tests replace it).
64
+ * @returns {string | undefined} The file.
65
+ */
66
+ export function resolveCommand(name, dirs, { pathext, exists = existsSync } = {}) {
67
+ const exts = (pathext || DEFAULT_PATHEXT).split(";").map((ext) => ext.trim().toLowerCase()).filter(Boolean);
68
+ for (const dir of dirs) {
69
+ for (const ext of exts) {
70
+ const file = win32.join(dir, `${name}${ext}`);
71
+ if (exists(file)) return file;
72
+ }
73
+ }
74
+ return undefined;
75
+ }
76
+ /**
77
+ * Whether `claude` would start our launcher in a new process, from the two registry values.
78
+ * @param {object} options
79
+ * @param {string | null} options.machine The Machine `Path`.
80
+ * @param {string | null} options.user The User `Path`.
81
+ * @param {Record<string, string | undefined>} options.env Environment (expansion and PATHEXT).
82
+ * @param {string} options.binDir The launcher's folder.
83
+ * @param {(file: string) => boolean} [options.exists] File check.
84
+ * @returns {{ ours: boolean, winner: string | undefined }} `winner` is the file `claude` resolves to (undefined: none found).
85
+ */
86
+ export function launcherWins({ machine, user, env, binDir, exists }) {
87
+ const dirs = effectiveDirs(machine, user, env);
88
+ const pathext = Object.entries(env).find(([name]) => name.toUpperCase() === "PATHEXT")?.[1];
89
+ const winner = resolveCommand("claude", dirs, { pathext, exists });
90
+ return { ours: winner !== undefined && same(win32.dirname(winner)) === same(binDir), winner };
91
+ }
92
+ /**
93
+ * A Path value with `dir` inserted before the entry for `anchor` (the real claude's folder); at the front when `anchor` is not in it.
94
+ * @param {string | null} value The Path as stored.
95
+ * @param {string} dir The folder to add (any earlier copy of it goes).
96
+ * @param {string | undefined} anchor The folder it must come before (as expanded).
97
+ * @param {Record<string, string | undefined>} [env] Environment, to expand `%VAR%` entries when looking for the anchor.
98
+ * @returns {string} The new value; other entries are kept as they are.
99
+ */
100
+ export function insertBefore(value, dir, anchor, env = {}) {
101
+ const rest = removePathEntry(value, dir, "win32").split(";").filter(Boolean);
102
+ const at = anchor ? rest.findIndex((entry) => same(expandEnv(entry, env)) === same(anchor)) : -1;
103
+ if (at === -1) return addPathEntry(rest.join(";"), dir, "win32");
104
+ rest.splice(at, 0, dir);
105
+ return rest.join(";");
106
+ }
107
+
108
+ /**
109
+ * The marked block a PowerShell profile gets: a `claude` function that runs the launcher, and falls back to the real program if the
110
+ * launcher is gone (so a profile that outlives `tokenhub disconnect` does not break `claude`).
111
+ * @param {string} binDir The launcher's folder.
112
+ * @returns {string} The lines, without a final newline.
113
+ */
114
+ export function psProfileBlock(binDir) {
115
+ const launcher = `'${win32.join(binDir, "claude.cmd").replace(/'/g, "''")}'`;
116
+ const fallback = "(Get-Command claude -CommandType Application -ErrorAction Stop | Select-Object -First 1).Source";
117
+ return [PROFILE_BEGIN, `function claude { $l = ${launcher}; if (Test-Path -LiteralPath $l) { & $l @args } else { & ${fallback} @args } }`, PROFILE_END].join("\n");
118
+ }
119
+ /**
120
+ * A profile's text with our block at the end (an earlier block is replaced, so running twice adds nothing).
121
+ * @param {string} text The profile's text.
122
+ * @param {string} binDir The launcher's folder.
123
+ * @returns {string} The new text.
124
+ */
125
+ export function addPsBlock(text, binDir) {
126
+ const clean = removeProfileBlock(text).text;
127
+ const block = psProfileBlock(binDir);
128
+ if (clean === "") return `${block}\n`;
129
+ return `${clean.endsWith("\n") ? clean : `${clean}\n`}\n${block}\n`;
130
+ }
131
+ /**
132
+ * Add our block to a PowerShell profile file.
133
+ * @param {string} file The profile path (its folder is created).
134
+ * @param {string} binDir The launcher's folder.
135
+ * @returns {{ changed: boolean, skipped?: string }} `skipped` says why the file was left alone: it holds characters outside ASCII in an encoding we cannot tell, and the block has some too.
136
+ * @sideEffect Copies an existing profile to `<file>.tokenhub.bak` once. The file keeps a UTF-8 byte-order mark it had, and gets one when it is new
137
+ * or the block has non-ASCII characters (Windows PowerShell 5.1 reads a file without one as ANSI).
138
+ */
139
+ export function writePsProfile(file, binDir) {
140
+ const exists = existsSync(file);
141
+ const bytes = exists ? readFileSync(file) : Buffer.alloc(0);
142
+ const hasBom = bytes.length >= 3 && bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf;
143
+ const before = bytes.subarray(hasBom ? 3 : 0).toString("utf8");
144
+ const after = addPsBlock(before, binDir);
145
+ if (after === before) return { changed: false };
146
+ const wide = /[^\x00-\x7f]/.test(psProfileBlock(binDir));
147
+ if (wide && !hasBom && bytes.some((byte) => byte >= 0x80)) return { changed: false, skipped: "non-ASCII text in an unknown encoding" };
148
+ mkdirSync(dirname(file), { recursive: true });
149
+ if (exists && !existsSync(`${file}.tokenhub.bak`)) copyFileSync(file, `${file}.tokenhub.bak`);
150
+ const bom = hasBom || wide || !exists ? "" : "";
151
+ writeFileSync(file, `${bom}${after}`, "utf8");
152
+ return { changed: true };
153
+ }
154
+ /**
155
+ * Take our block out of a PowerShell profile; a profile left empty (only our block was in it) is deleted.
156
+ * @param {string} file The profile path.
157
+ * @returns {boolean} Whether a block was removed.
158
+ */
159
+ export function removePsProfile(file) {
160
+ if (!existsSync(file)) return false;
161
+ const bytes = readFileSync(file);
162
+ const hasBom = bytes.length >= 3 && bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf;
163
+ const { text, removed } = removeProfileBlock(bytes.subarray(hasBom ? 3 : 0).toString("utf8"));
164
+ if (!removed) return false;
165
+ if (text.trim() === "") rmSync(file, { force: true });
166
+ else writeFileSync(file, `${hasBom ? "" : ""}${text}`, "utf8");
167
+ return true;
168
+ }
169
+ /**
170
+ * Whether a profile file holds our block.
171
+ * @param {string} file The profile path.
172
+ * @returns {boolean} True when it does.
173
+ */
174
+ export function hasPsBlock(file) {
175
+ try {
176
+ const text = readFileSync(file, "utf8");
177
+ return text.includes(PROFILE_BEGIN) && text.includes(PROFILE_END);
178
+ } catch {
179
+ return false;
180
+ }
181
+ }
182
+
183
+ /**
184
+ * What the shell's execution policy means for a profile.
185
+ * @param {{ effective: string, policies: Array<{ scope: string, policy: string }> }} info What `Get-ExecutionPolicy` and `-List` said.
186
+ * @returns {{ blocked: boolean, source?: string, fixable?: boolean, previous?: string }} `blocked`: the profile would not run. `source`: the scope that decides.
187
+ * `fixable`: a change to the CurrentUser scope would override it (not so for a group policy or the process scope). `previous`: the CurrentUser value now.
188
+ */
189
+ export function policyDecision(info) {
190
+ const previous = info.policies.find((entry) => entry.scope === "CurrentUser")?.policy ?? "Undefined";
191
+ if (!BLOCKING.has(String(info.effective).toLowerCase())) return { blocked: false, previous };
192
+ const source = info.policies.find((entry) => entry.policy !== "Undefined")?.scope ?? "default";
193
+ return { blocked: true, source, fixable: OVERRIDABLE_SOURCES.has(source), previous };
194
+ }
195
+
196
+ /**
197
+ * What the installer needs from Windows, so tests can replace it.
198
+ * @typedef {object} WinSystem
199
+ * @property {() => Promise<{ value: string | null, kind: string }>} machinePath The Machine `Path` as stored (read-only, no elevation).
200
+ * @property {(expected: string | null, next: string, kind: string) => Promise<boolean>} machineSet Writes the Machine `Path` through an elevated
201
+ * PowerShell (one UAC prompt), only if it still equals `expected`; resolves with whether it was written.
202
+ * @property {() => Promise<Array<{ shell: "powershell" | "pwsh", profile: string, effective: string, policies: Array<{ scope: string, policy: string }> }>>} shells
203
+ * The PowerShells that are installed, with their CurrentUser AllHosts profile path and execution policies.
204
+ * @property {(shell: string, policy: string) => Promise<boolean>} setPolicy `Set-ExecutionPolicy -Scope CurrentUser` in that shell.
205
+ */
206
+ /**
207
+ * @typedef {object} LauncherRecord What was done to make the launcher win, kept in `install.json` so `disconnect` undoes exactly that.
208
+ * @property {Array<{ shell: string, file: string }>} [profiles] The profiles that got our block.
209
+ * @property {Array<{ shell: string, previous: string }>} [policies] Shells whose CurrentUser execution policy we set to RemoteSigned, and what it was.
210
+ * @property {{ entry: string }} [machinePath] The folder we put in the Machine Path.
211
+ */
212
+ /**
213
+ * Make sure `claude` starts the launcher, and when it would not, fix it with the user's consent.
214
+ *
215
+ * @param {object} options
216
+ * @param {string} options.binDir The launcher's folder (already first in the User Path).
217
+ * @param {Record<string, string | undefined>} options.env Environment (for expansion and PATHEXT).
218
+ * @param {{ get: () => Promise<{ value: string | null, kind: string }> }} options.userPath The registry's User Path.
219
+ * @param {WinSystem} options.sys Windows access.
220
+ * @param {(question: string, defaultYes?: boolean) => Promise<boolean>} options.ask Yes/no prompt (false without a terminal).
221
+ * @param {(line: string) => void} options.log Output sink.
222
+ * @param {Record<string, any>} options.t The messages (`text(lang)`).
223
+ * @param {(file: string) => boolean} [options.exists] File check for the resolution (tests replace it).
224
+ * @param {LauncherRecord} [options.previous] What an earlier run recorded: its profile blocks count (nothing is asked again) and its records are kept.
225
+ * @returns {Promise<{ how: "path" | "profile" | "machine" | "none" | "unknown", path: boolean, powershell: boolean, record: LauncherRecord }>}
226
+ * `how`: what makes `claude` start the launcher (`path`: nothing was needed). `path`: it wins in cmd.exe and Git Bash too. `powershell`: it wins in PowerShell.
227
+ * `unknown`: the registry could not be read, so nothing could be checked.
228
+ */
229
+ export async function ensureLauncher({ binDir, env, userPath, sys, ask, log, t, exists, previous }) {
230
+ /** Reads both Path values and decides. */
231
+ const check = async () => {
232
+ const [machine, user] = await Promise.all([sys.machinePath(), userPath.get()]);
233
+ return { machine, user, ...launcherWins({ machine: machine.value, user: user.value, env, binDir, exists }) };
234
+ };
235
+ let now;
236
+ try {
237
+ now = await check();
238
+ } catch (error) {
239
+ log(t.launcherUnchecked(String(error.message ?? error)));
240
+ return { how: "unknown", path: false, powershell: false, record: {} };
241
+ }
242
+ if (now.ours) return { how: "path", path: true, powershell: true, record: previous ?? {} };
243
+ // An earlier run put the function in a profile and it is still there: PowerShell is covered, and the user already chose.
244
+ if (previous?.profiles?.some((profile) => hasPsBlock(profile.file))) return { how: "profile", path: false, powershell: true, record: previous };
245
+ log(t.launcherShadowed(now.winner ?? "?"));
246
+ /** @type {LauncherRecord} */
247
+ const record = { ...previous };
248
+
249
+ // a. the PowerShell profile function
250
+ const shells = await sys.shells().catch(() => []);
251
+ let powershell = false;
252
+ if (shells.length > 0) {
253
+ for (const line of t.profileIntro) log(line);
254
+ if (await ask(t.askProfile, true)) {
255
+ for (const shell of shells) {
256
+ const decision = policyDecision(shell);
257
+ if (decision.blocked) {
258
+ if (!decision.fixable) {
259
+ log(t.policyLocked(shell.shell, decision.source));
260
+ continue;
261
+ }
262
+ for (const line of t.policyIntro(shell.shell, shell.effective)) log(line);
263
+ if (!(await ask(t.askPolicy, false))) continue;
264
+ if (!(await sys.setPolicy(shell.shell, "RemoteSigned"))) {
265
+ log(t.policyFailed(shell.shell));
266
+ continue;
267
+ }
268
+ record.policies = [...(record.policies ?? []).filter((p) => p.shell !== shell.shell), { shell: shell.shell, previous: decision.previous ?? "Undefined" }];
269
+ }
270
+ try {
271
+ const written = writePsProfile(shell.profile, binDir);
272
+ if (written.skipped) {
273
+ log(t.profileSkipped(shell.profile, written.skipped));
274
+ continue;
275
+ }
276
+ record.profiles = [...(record.profiles ?? []).filter((p) => p.file !== shell.profile), { shell: shell.shell, file: shell.profile }];
277
+ log(t.profileAdded(shell.shell, shell.profile));
278
+ powershell = true;
279
+ } catch (error) {
280
+ log(t.profileFailed(shell.profile, String(error.message ?? error)));
281
+ }
282
+ }
283
+ }
284
+ }
285
+ if (powershell) return { how: "profile", path: false, powershell: true, record };
286
+
287
+ // b. the Machine Path
288
+ for (const line of t.machineIntro) log(line);
289
+ if (await ask(t.askMachine, true)) {
290
+ const before = now.machine.value;
291
+ const next = insertBefore(before, binDir, now.winner ? win32.dirname(now.winner) : undefined, env);
292
+ const written = await sys.machineSet(before, next, now.machine.kind).catch(() => false);
293
+ const after = written ? await check().catch(() => undefined) : undefined;
294
+ if (after?.ours) {
295
+ record.machinePath = { entry: binDir };
296
+ log(t.machineDone);
297
+ return { how: "machine", path: true, powershell: true, record };
298
+ }
299
+ log(written ? t.machineNotEnough : t.machineFailed);
300
+ }
301
+
302
+ // c. by hand
303
+ log(t.startByHand(win32.join(binDir, "claude.cmd")));
304
+ return { how: "none", path: false, powershell: false, record };
305
+ }
306
+ /**
307
+ * Undo `ensureLauncher`: our profile blocks, our Machine Path entry (elevated) and the execution policy we changed, each only if it is
308
+ * still what we left.
309
+ *
310
+ * @param {object} options
311
+ * @param {LauncherRecord | undefined} options.record What `install.json` kept.
312
+ * @param {WinSystem} options.sys Windows access.
313
+ * @param {(line: string) => void} options.log Output sink.
314
+ * @param {Record<string, any>} options.t The messages.
315
+ * @returns {Promise<void>}
316
+ */
317
+ export async function removeLauncher({ record, sys, log, t }) {
318
+ if (!record) return;
319
+ for (const { file } of record.profiles ?? []) {
320
+ try {
321
+ if (removePsProfile(file)) log(t.profileRemoved(file));
322
+ } catch (error) {
323
+ log(t.profileRemoveFailed(file, String(error.message ?? error)));
324
+ }
325
+ }
326
+ if (record.machinePath) {
327
+ try {
328
+ const now = await sys.machinePath();
329
+ if (now.value !== null && hasPathEntry(now.value, record.machinePath.entry, "win32")) {
330
+ const ok = await sys.machineSet(now.value, removePathEntry(now.value, record.machinePath.entry, "win32"), now.kind);
331
+ log(ok ? t.machineRemoved : t.machineRemoveFailed(record.machinePath.entry));
332
+ }
333
+ } catch (error) {
334
+ log(t.machineRemoveFailed(record.machinePath.entry));
335
+ }
336
+ }
337
+ if (record.policies?.length) {
338
+ const shells = await sys.shells().catch(() => []);
339
+ for (const { shell, previous } of record.policies) {
340
+ const current = shells.find((s) => s.shell === shell)?.policies.find((entry) => entry.scope === "CurrentUser")?.policy;
341
+ // Only what we set, and only if nobody changed it since.
342
+ if (current === "RemoteSigned" && (await sys.setPolicy(shell, previous))) log(t.policyRestored(shell, previous));
343
+ }
344
+ }
345
+ }
346
+
347
+ /** The PowerShell that reads the Machine `Path` (read-only: no elevation). */
348
+ const MACHINE_READ_SCRIPT = `
349
+ $ErrorActionPreference = 'Stop'
350
+ [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false
351
+ $key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey('SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment')
352
+ $raw = $key.GetValue('Path', $null, [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
353
+ if ($null -eq $raw) { Write-Output '{"value":null,"kind":"ExpandString"}' }
354
+ else { Write-Output (ConvertTo-Json -Compress @{ value = [string]$raw; kind = $key.GetValueKind('Path').ToString() }) }
355
+ `;
356
+ /** The PowerShell that describes one shell: its CurrentUser AllHosts profile and its execution policies. */
357
+ const SHELL_SCRIPT = `
358
+ $ErrorActionPreference = 'Stop'
359
+ [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false
360
+ $list = @(Get-ExecutionPolicy -List | ForEach-Object { [pscustomobject]@{ scope = [string]$_.Scope; policy = [string]$_.ExecutionPolicy } })
361
+ ConvertTo-Json -Compress -Depth 4 -InputObject ([pscustomobject]@{ profile = [string]$PROFILE.CurrentUserAllHosts; effective = [string](Get-ExecutionPolicy); policies = $list })
362
+ `;
363
+ /**
364
+ * The script the elevated PowerShell runs: sets the Machine `Path` if it still has the value we read, and tells every window.
365
+ * @param {string | null} expected The value read before.
366
+ * @param {string} next The value to write.
367
+ * @param {string} kind `ExpandString` or `String`.
368
+ * @returns {string} PowerShell source (the values are embedded as JSON strings).
369
+ */
370
+ function machineWriteScript(expected, next, kind) {
371
+ return `
372
+ $ErrorActionPreference = 'Stop'
373
+ $expected = ConvertFrom-Json '${JSON.stringify(expected).replace(/'/g, "''")}'
374
+ $next = ConvertFrom-Json '${JSON.stringify(next).replace(/'/g, "''")}'
375
+ $key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey('SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment', $true)
376
+ $raw = $key.GetValue('Path', $null, [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
377
+ if ($raw -ne $expected) { exit 3 }
378
+ $key.SetValue('Path', $next, [Microsoft.Win32.RegistryValueKind]'${kind === "String" ? "String" : "ExpandString"}')
379
+ $key.Close()
380
+ Add-Type -Namespace TokenHub -Name Native -MemberDefinition '[DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)] public static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam, uint flags, uint timeout, out UIntPtr result);'
381
+ $result = [UIntPtr]::Zero
382
+ [void][TokenHub.Native]::SendMessageTimeout([IntPtr]0xffff, 0x1A, [UIntPtr]::Zero, 'Environment', 2, 5000, [ref]$result)
383
+ `;
384
+ }
385
+ /** @param {string} script PowerShell source. @returns {string} It as `-EncodedCommand` takes it. */
386
+ const encode = (script) => Buffer.from(script, "utf16le").toString("base64");
387
+ /**
388
+ * The real Windows access: Windows PowerShell for the registry and policies, `pwsh` too when it is installed, and an elevated
389
+ * PowerShell (`Start-Process -Verb RunAs`, so Windows shows its UAC prompt) for the one write that needs it.
390
+ *
391
+ * @param {object} [options]
392
+ * @param {import("./run.js").Runner} [options.run] Runs a program (tests replace it).
393
+ * @returns {WinSystem} The access.
394
+ */
395
+ export function realWindowsSystem({ run = defaultRun } = {}) {
396
+ const ps = (exe, script, timeoutMs = 60_000) => run(exe, ["-NoProfile", "-NonInteractive", "-EncodedCommand", encode(script)], { timeoutMs });
397
+ return {
398
+ async machinePath() {
399
+ const result = await ps("powershell.exe", MACHINE_READ_SCRIPT);
400
+ if (result.code !== 0) throw new Error(`could not read the Machine PATH (${result.stderr.trim().split("\n")[0] || `exit ${result.code}`})`);
401
+ const parsed = JSON.parse(result.stdout.replace(/^/, "").trim());
402
+ return { value: parsed.value ?? null, kind: parsed.kind === "String" ? "String" : "ExpandString" };
403
+ },
404
+ async machineSet(expected, next, kind) {
405
+ const inner = encode(machineWriteScript(expected, next, kind));
406
+ const outer = `$p = Start-Process -FilePath powershell.exe -Verb RunAs -Wait -PassThru -WindowStyle Hidden -ArgumentList '-NoProfile','-NonInteractive','-EncodedCommand','${inner}'; exit $p.ExitCode`;
407
+ const result = await ps("powershell.exe", outer, 180_000);
408
+ return result.code === 0;
409
+ },
410
+ async shells() {
411
+ const found = [];
412
+ for (const [shell, exe] of [["powershell", "powershell.exe"], ["pwsh", "pwsh.exe"]]) {
413
+ const result = await ps(exe, SHELL_SCRIPT).catch(() => ({ code: -1, stdout: "", stderr: "" }));
414
+ if (result.code !== 0) continue;
415
+ try {
416
+ const parsed = JSON.parse(result.stdout.replace(/^/, "").trim());
417
+ if (typeof parsed.profile === "string" && parsed.profile) found.push({ shell, profile: parsed.profile, effective: String(parsed.effective), policies: parsed.policies ?? [] });
418
+ } catch {
419
+ // Not readable: that shell is left alone.
420
+ }
421
+ }
422
+ return found;
423
+ },
424
+ async setPolicy(shell, policy) {
425
+ const exe = shell === "pwsh" ? "pwsh.exe" : "powershell.exe";
426
+ const result = await run(exe, ["-NoProfile", "-NonInteractive", "-Command", `Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy ${policy} -Force`], { timeoutMs: 60_000 });
427
+ return result.code === 0;
428
+ },
429
+ };
430
+ }
package/lib/pair.d.ts CHANGED
@@ -43,6 +43,12 @@ export function runConnect(options: {
43
43
  modelPicker?: boolean;
44
44
  /** Where the picker is installed; `modelPickerDir()` by default. */
45
45
  modelPickerDir?: string;
46
+ /** `true` installs TokenHub Remote (--remote), `false` skips it (--no-remote); left out, the question is asked (default no). */
47
+ remote?: boolean;
48
+ /** The Remote installer; tests replace it. */
49
+ installRemoteFn?: typeof import("./remote-install.js").installRemote;
50
+ /** Home directory the Remote installer uses. */
51
+ home?: string;
46
52
  /** Yes/no prompt; answers false without a terminal. */
47
53
  ask?: (question: string, defaultYes?: boolean) => Promise<boolean>;
48
54
  }): Promise<number>;
package/lib/pair.js CHANGED
@@ -1,9 +1,11 @@
1
1
  import { spawn } from "node:child_process";
2
- import { hostname } from "node:os";
2
+ import { homedir, hostname } from "node:os";
3
3
  import { emitKeypressEvents } from "node:readline";
4
4
  import { createInterface } from "node:readline/promises";
5
5
  import { writeAdminConfig } from "./admin.js";
6
6
  import { askYesNo, enableFullscreen, installModelPicker, layoutUnset, modelPickerDir } from "./model-picker.js";
7
+ import { installRemote } from "./remote-install.js";
8
+ import { detectLang, text } from "./remote-text.js";
7
9
  import { connectSettings, normalizeUrl, overridingEnvVars, readSettings } from "./settings.js";
8
10
 
9
11
  const MAX_WAIT_MS = 15 * 60 * 1000;
@@ -294,6 +296,9 @@ export async function pairDevice({ pool, admin = false, deviceName, log, open, s
294
296
  * @param {string} [options.adminFile] Path from `adminConfigPath`; required with `admin`.
295
297
  * @param {boolean} [options.modelPicker] Offer to install the Claude Code model picker after pairing (default true).
296
298
  * @param {string} [options.modelPickerDir] Where the picker is installed (`modelPickerDir()` by default).
299
+ * @param {boolean} [options.remote] `true` (--remote) installs TokenHub Remote, `false` (--no-remote) skips it; left out, it is asked (default no).
300
+ * @param {typeof installRemote} [options.installRemoteFn] The Remote installer (tests replace it).
301
+ * @param {string} [options.home] Home directory the Remote installer uses.
297
302
  * @param {(question: string, defaultYes?: boolean) => Promise<boolean>} [options.ask] Yes/no prompt (tests); false without a terminal.
298
303
  * @returns {Promise<number>} Process exit code.
299
304
  */
@@ -311,6 +316,9 @@ export async function runConnect({
311
316
  adminFile,
312
317
  modelPicker = true,
313
318
  modelPickerDir: pickerDir = modelPickerDir(),
319
+ remote,
320
+ installRemoteFn = installRemote,
321
+ home = homedir(),
314
322
  ask = (question, defaultYes = true) => askYesNo(question, { defaultYes }),
315
323
  }) {
316
324
  let pool;
@@ -357,6 +365,11 @@ export async function runConnect({
357
365
  log(`Model picker not installed: ${error.message}`);
358
366
  }
359
367
  }
368
+ const lang = detectLang(env);
369
+ if (remote ?? (await ask(text(lang).askRemote, false))) {
370
+ const installed = await installRemoteFn({ pool, baseUrl, settingsFile, lang, log, open, signal, ask, deviceName, intervalOverrideMs, env, home });
371
+ if (!installed.ok) return installed.code;
372
+ }
360
373
  return 0;
361
374
  } catch (error) {
362
375
  if (signal?.aborted) {
@@ -0,0 +1,29 @@
1
+ import type { Runner } from "./run.js";
2
+ export const REMOTE_DOWNLOADS: string;
3
+ export const HOOK_FILE: string;
4
+ export interface ManifestFile {
5
+ name: string;
6
+ sha256: string;
7
+ size?: number;
8
+ }
9
+ export interface Manifest {
10
+ version: string;
11
+ platforms: Record<string, ManifestFile[]>;
12
+ }
13
+ export function sha256Hex(bytes: Buffer | Uint8Array | string): string;
14
+ export function parseManifest(json: unknown): Manifest;
15
+ export function pickPlatform(manifest: Manifest, platform: string, arch: string): { key: string; files: ManifestFile[] };
16
+ export function compareVersions(a: string, b: string): number;
17
+ export function readCurrent(root: string): { version: string; dir: string } | undefined;
18
+ export function fetchManifest(pool: string, options?: { fetchImpl?: typeof fetch; signal?: AbortSignal }): Promise<Manifest>;
19
+ export function downloadRemote(options: {
20
+ pool: string;
21
+ root: string;
22
+ platform?: string;
23
+ arch?: string;
24
+ log?: (line: string) => void;
25
+ fetchImpl?: typeof fetch;
26
+ signal?: AbortSignal;
27
+ run?: Runner;
28
+ manifest?: Manifest;
29
+ }): Promise<{ version: string; dir: string; action: "installed" | "updated" | "repaired" | "kept"; previous?: string; platformKey: string }>;