@emesoft/tokenhub 0.8.13 → 0.9.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.
@@ -0,0 +1,242 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { exeName, platformKeys } from "./remote-paths.js";
5
+ import { run as defaultRun } from "./run.js";
6
+
7
+ /** Where the pool publishes the daemon (served from `<DOWNLOADS_DIR>/remote`, see `src/downloads.ts`). */
8
+ export const REMOTE_DOWNLOADS = "/downloads/remote";
9
+ /** The hook script the daemon's installer registers with Claude Code. Every platform's file list must have it. */
10
+ export const HOOK_FILE = "tf-remote-hook.mjs";
11
+ const VERSION = /^\d+\.\d+\.\d+([-+][0-9A-Za-z.-]+)?$/;
12
+ const FILE_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
13
+ const PLATFORM_NAME = /^[a-z0-9]+-[a-z0-9]+$/;
14
+ const SHA256 = /^[0-9a-f]{64}$/i;
15
+ const FILE_TIMEOUT_MS = 180_000;
16
+
17
+ /**
18
+ * @param {Buffer | Uint8Array | string} bytes Data to hash.
19
+ * @returns {string} Its SHA-256 as lowercase hex.
20
+ */
21
+ export function sha256Hex(bytes) {
22
+ return createHash("sha256").update(bytes).digest("hex");
23
+ }
24
+ /**
25
+ * Validate the download manifest. Every name that later becomes a path or a URL is checked here, so a hostile or damaged manifest
26
+ * cannot reach outside the install folder.
27
+ *
28
+ * Shape: `{ "version": "0.1.0", "platforms": { "win32-x64": { "files": [ { "name": "tfr.exe", "sha256": "<64 hex>", "size": 123 } ] } } }`.
29
+ * A file is served at `<pool>/downloads/remote/<platform>/<name>`; `size` is optional.
30
+ *
31
+ * @param {unknown} json The parsed manifest.
32
+ * @returns {{ version: string, platforms: Record<string, Array<{ name: string, sha256: string, size?: number }>> }} The manifest, normalised (hashes lowercase).
33
+ * @throws {Error} Saying what is wrong with it.
34
+ */
35
+ export function parseManifest(json) {
36
+ const fail = (why) => {
37
+ throw new Error(`The Remote download manifest is not valid (${why}).`);
38
+ };
39
+ if (!json || typeof json !== "object" || Array.isArray(json)) fail("not an object");
40
+ if (typeof json.version !== "string" || !VERSION.test(json.version)) fail("version");
41
+ if (!json.platforms || typeof json.platforms !== "object" || Array.isArray(json.platforms)) fail("platforms");
42
+ const platforms = {};
43
+ for (const [key, entry] of Object.entries(json.platforms)) {
44
+ if (!PLATFORM_NAME.test(key)) fail(`platform name ${key}`);
45
+ const list = entry?.files;
46
+ if (!Array.isArray(list) || list.length === 0) fail(`files of ${key}`);
47
+ const seen = new Set();
48
+ platforms[key] = list.map((file) => {
49
+ if (!file || typeof file.name !== "string" || !FILE_NAME.test(file.name) || seen.has(file.name)) fail(`file name in ${key}`);
50
+ if (typeof file.sha256 !== "string" || !SHA256.test(file.sha256)) fail(`sha256 of ${file.name}`);
51
+ if (file.size !== undefined && !(Number.isInteger(file.size) && file.size >= 0)) fail(`size of ${file.name}`);
52
+ seen.add(file.name);
53
+ return { name: file.name, sha256: file.sha256.toLowerCase(), ...(file.size === undefined ? {} : { size: file.size }) };
54
+ });
55
+ }
56
+ return { version: json.version, platforms };
57
+ }
58
+ /**
59
+ * The file list for this system.
60
+ * @param {ReturnType<typeof parseManifest>} manifest A parsed manifest.
61
+ * @param {string} platform Node platform name.
62
+ * @param {string} arch Node architecture name.
63
+ * @returns {{ key: string, files: Array<{ name: string, sha256: string, size?: number }> }} The platform folder name and its files.
64
+ * @throws {Error} When the manifest has no build for this system, or lacks `tfr`, `tfc` or the hook script.
65
+ */
66
+ export function pickPlatform(manifest, platform, arch) {
67
+ const key = platformKeys(platform, arch).find((candidate) => manifest.platforms[candidate]);
68
+ if (!key) throw new Error(`There is no TokenHub Remote build for this system (${platform}/${arch}).`);
69
+ const files = manifest.platforms[key];
70
+ for (const name of [exeName("tfr", platform), exeName("tfc", platform), HOOK_FILE]) {
71
+ if (!files.some((file) => file.name === name)) throw new Error(`The Remote download for ${key} is missing ${name}.`);
72
+ }
73
+ return { key, files };
74
+ }
75
+ /**
76
+ * Compare two versions by their numbers (a pre-release suffix is ignored).
77
+ * @param {string} a A version such as `0.2.1`.
78
+ * @param {string} b Another.
79
+ * @returns {number} Negative when `a` is older, 0 when equal, positive when newer.
80
+ */
81
+ export function compareVersions(a, b) {
82
+ const parts = (v) => v.split(/[-+]/)[0].split(".").map(Number);
83
+ const [x, y] = [parts(a), parts(b)];
84
+ for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] - y[i];
85
+ return 0;
86
+ }
87
+ /**
88
+ * Read `current.json`, the pointer to the installed version.
89
+ * @param {string} root The Remote folder (`remoteDir()`).
90
+ * @returns {{ version: string, dir: string } | undefined} The pointer, or undefined when nothing is installed or it is unreadable.
91
+ */
92
+ export function readCurrent(root) {
93
+ try {
94
+ const pointer = JSON.parse(readFileSync(join(root, "current.json"), "utf8"));
95
+ return typeof pointer.version === "string" && typeof pointer.dir === "string" ? { version: pointer.version, dir: pointer.dir } : undefined;
96
+ } catch {
97
+ return undefined;
98
+ }
99
+ }
100
+ /**
101
+ * Download the manifest.
102
+ * @param {string} pool Pool address.
103
+ * @param {{ fetchImpl?: typeof fetch, signal?: AbortSignal }} [options] `fetch` override and cancel signal.
104
+ * @returns {Promise<ReturnType<typeof parseManifest>>} The validated manifest.
105
+ * @throws {Error} When the pool is unreachable, has not published the daemon (404), or the manifest is invalid.
106
+ */
107
+ export async function fetchManifest(pool, { fetchImpl = fetch, signal } = {}) {
108
+ let res;
109
+ try {
110
+ res = await fetchImpl(`${pool}${REMOTE_DOWNLOADS}/manifest.json`, { signal: signal ?? AbortSignal.timeout(20_000) });
111
+ } catch (error) {
112
+ throw new Error(`Could not reach the pool (${error.message}).`);
113
+ }
114
+ if (res.status === 404) throw new Error("This pool has not published TokenHub Remote yet. Ask your admin.");
115
+ if (!res.ok) throw new Error(`The pool answered HTTP ${res.status} for the Remote download list.`);
116
+ return parseManifest(await res.json().catch(() => null));
117
+ }
118
+ /**
119
+ * Fetch one file and check it against the manifest before it is kept.
120
+ * @param {string} url File address.
121
+ * @param {{ name: string, sha256: string, size?: number }} file Its manifest entry.
122
+ * @param {{ fetchImpl: typeof fetch, signal?: AbortSignal }} io `fetch` and cancel signal.
123
+ * @returns {Promise<Buffer>} The bytes, whose SHA-256 (and size, when the manifest has one) match.
124
+ * @throws {Error} On a failed download or a mismatch (the bytes are never returned then).
125
+ */
126
+ async function fetchVerified(url, file, { fetchImpl, signal }) {
127
+ const res = await fetchImpl(url, { signal: signal ?? AbortSignal.timeout(FILE_TIMEOUT_MS) });
128
+ if (!res.ok) throw new Error(`Downloading ${file.name} failed (HTTP ${res.status}).`);
129
+ const bytes = Buffer.from(await res.arrayBuffer());
130
+ if (file.size !== undefined && bytes.length !== file.size) throw new Error(`${file.name} did not download completely (${bytes.length} of ${file.size} bytes). Nothing was installed.`);
131
+ if (sha256Hex(bytes) !== file.sha256) throw new Error(`${file.name} does not match the SHA-256 in the download list. Nothing was installed.`);
132
+ return bytes;
133
+ }
134
+ /**
135
+ * Whether every file of an installed version is there and (when `verify`) has the manifest's hash.
136
+ * @param {string} dir The version folder.
137
+ * @param {Array<{ name: string, sha256: string }>} files The manifest's files.
138
+ * @param {boolean} verify Also hash the files.
139
+ * @returns {boolean} True when the version is complete.
140
+ */
141
+ function installedOk(dir, files, verify) {
142
+ return files.every((file) => {
143
+ const path = join(dir, file.name);
144
+ return existsSync(path) && (!verify || sha256Hex(readFileSync(path)) === file.sha256);
145
+ });
146
+ }
147
+ /**
148
+ * Install the daemon from the pool into `<root>/<version>/` and point `current.json` at it.
149
+ *
150
+ * Nothing lands in its final place before it is verified: each file is fetched into memory, its SHA-256 (and size) checked, and
151
+ * only then written, into a staging folder inside `root`; the folder is renamed to `<version>` once all files are in. A newer
152
+ * manifest version installs beside the old one and then older versions are removed (one a running daemon still holds is left
153
+ * for next time). The same or an older installed version is kept when it is complete and, for the same version, matches the hashes.
154
+ *
155
+ * @param {object} options
156
+ * @param {string} options.pool Pool address.
157
+ * @param {string} options.root The Remote folder (`remoteDir()`); created.
158
+ * @param {string} [options.platform] Node platform name.
159
+ * @param {string} [options.arch] Node architecture name.
160
+ * @param {(line: string) => void} [options.log] Progress output.
161
+ * @param {typeof fetch} [options.fetchImpl] `fetch` override for tests.
162
+ * @param {AbortSignal} [options.signal] Cancels the downloads.
163
+ * @param {import("./run.js").Runner} [options.run] Runs `xattr` on macOS (tests replace it).
164
+ * @param {ReturnType<typeof parseManifest>} [options.manifest] A manifest already fetched.
165
+ * @returns {Promise<{ version: string, dir: string, action: "installed" | "updated" | "repaired" | "kept", previous?: string, platformKey: string }>} What was done.
166
+ * @throws {Error} On any download, verification or write failure; nothing is switched over then.
167
+ */
168
+ export async function downloadRemote({ pool, root, platform = process.platform, arch = process.arch, log = () => {}, fetchImpl = fetch, signal, run = defaultRun, manifest }) {
169
+ const parsed = manifest ?? (await fetchManifest(pool, { fetchImpl, signal }));
170
+ const { key, files } = pickPlatform(parsed, platform, arch);
171
+ const current = readCurrent(root);
172
+ const target = join(root, parsed.version);
173
+ if (current && existsSync(current.dir)) {
174
+ const cmp = compareVersions(parsed.version, current.version);
175
+ const sameVersion = cmp === 0;
176
+ if (cmp < 0 && installedOk(current.dir, files, false)) return { version: current.version, dir: current.dir, action: "kept", platformKey: key };
177
+ if (sameVersion && installedOk(current.dir, files, true)) return { version: current.version, dir: current.dir, action: "kept", platformKey: key };
178
+ }
179
+ mkdirSync(root, { recursive: true });
180
+ const stage = join(root, `.stage-${randomBytes(4).toString("hex")}`);
181
+ try {
182
+ mkdirSync(stage);
183
+ for (const file of files) {
184
+ log(` ${file.name}${file.size ? ` (${(file.size / 1024 / 1024).toFixed(1)} MB)` : ""}`);
185
+ const bytes = await fetchVerified(`${pool}${REMOTE_DOWNLOADS}/${key}/${file.name}`, file, { fetchImpl, signal });
186
+ writeFileSync(join(stage, file.name), bytes);
187
+ }
188
+ if (existsSync(target)) {
189
+ try {
190
+ rmSync(target, { recursive: true, force: true });
191
+ } catch (error) {
192
+ throw new Error(`Could not replace ${target} (${error.message}). A Remote daemon may still be running: close your Claude sessions and try again.`);
193
+ }
194
+ }
195
+ renameSync(stage, target);
196
+ } finally {
197
+ rmSync(stage, { recursive: true, force: true });
198
+ }
199
+ if (platform !== "win32") {
200
+ for (const name of [exeName("tfr", platform), exeName("tfc", platform)]) chmodSync(join(target, name), 0o755);
201
+ }
202
+ if (platform === "darwin") {
203
+ // Files written by Node carry no quarantine mark; remove it anyway in case the folder was filled some other way. "No such attribute" is the usual answer.
204
+ for (const file of files) await run("xattr", ["-d", "com.apple.quarantine", join(target, file.name)]);
205
+ }
206
+ const previous = current?.version;
207
+ writeCurrent(root, parsed.version, target);
208
+ removeOtherVersions(root, parsed.version);
209
+ const action = previous === undefined ? "installed" : previous === parsed.version ? "repaired" : "updated";
210
+ return { version: parsed.version, dir: target, action, previous, platformKey: key };
211
+ }
212
+ /**
213
+ * Point `current.json` at a version folder (written to a temporary name and renamed, so a launching shim never reads half of it).
214
+ * @param {string} root The Remote folder.
215
+ * @param {string} version Version name.
216
+ * @param {string} dir The version's folder.
217
+ * @returns {void}
218
+ */
219
+ function writeCurrent(root, version, dir) {
220
+ const file = join(root, "current.json");
221
+ const temp = `${file}.${randomBytes(3).toString("hex")}.tmp`;
222
+ writeFileSync(temp, `${JSON.stringify({ version, dir }, null, 2)}\n`);
223
+ renameSync(temp, file);
224
+ }
225
+ /**
226
+ * Delete the version folders (and leftover staging folders) other than `keep`; one that cannot be deleted (a running daemon holds it)
227
+ * stays until the next run.
228
+ * @param {string} root The Remote folder.
229
+ * @param {string} keep The version to keep.
230
+ * @returns {void}
231
+ */
232
+ function removeOtherVersions(root, keep) {
233
+ for (const entry of readdirSync(root, { withFileTypes: true })) {
234
+ if (!entry.isDirectory() || entry.name === keep) continue;
235
+ if (!VERSION.test(entry.name) && !entry.name.startsWith(".stage-")) continue;
236
+ try {
237
+ rmSync(join(root, entry.name), { recursive: true, force: true });
238
+ } catch {
239
+ // still in use; the next connect removes it
240
+ }
241
+ }
242
+ }
@@ -0,0 +1,85 @@
1
+ import type { Runner } from "./run.js";
2
+ import type { UserPath } from "./user-path.js";
3
+ export const DEFAULT_RELAY_ORIGIN: string;
4
+ export interface InstallRecord {
5
+ pool: string;
6
+ version: string;
7
+ deviceName: string;
8
+ tokenSha256: string;
9
+ relayFile: string;
10
+ claudeDir?: string;
11
+ shim?: { binDir: string; targets: Array<{ kind: string; file?: string }> };
12
+ }
13
+ export interface Proc {
14
+ isAlive(pid: number): boolean;
15
+ imagePath(pid: number): Promise<string | undefined>;
16
+ stop(pid: number): Promise<void>;
17
+ }
18
+ export const HOOK_PORT_FIRST: number;
19
+ export function pickHookPort(isFree?: (port: number) => Promise<boolean>): Promise<number | undefined>;
20
+ export function readRecord(root: string): InstallRecord | undefined;
21
+ export function readRelayJson(file: string): Record<string, any> | undefined;
22
+ export function relayOriginFor(origin: string | undefined): string;
23
+ export function relayUrlFor(origin: string): string;
24
+ export function writeRelayJson(
25
+ file: string,
26
+ contents: Record<string, unknown>,
27
+ io: { platform: string; env: Record<string, string | undefined>; run: Runner },
28
+ ): Promise<boolean>;
29
+ export function installRemote(options: {
30
+ pool: string;
31
+ baseUrl?: string;
32
+ settingsFile: string;
33
+ lang?: "en" | "vi";
34
+ log?: (line: string) => void;
35
+ open: (url: string) => void;
36
+ signal?: AbortSignal;
37
+ ask: (question: string, defaultYes?: boolean) => Promise<boolean>;
38
+ shim?: boolean;
39
+ deviceName?: string;
40
+ intervalOverrideMs?: number;
41
+ env?: Record<string, string | undefined>;
42
+ home: string;
43
+ platform?: string;
44
+ arch?: string;
45
+ node?: string;
46
+ fetchImpl?: typeof fetch;
47
+ run?: Runner;
48
+ userPath?: UserPath;
49
+ pickPort?: typeof pickHookPort;
50
+ }): Promise<{ ok: true; version: string; shim: boolean } | { ok: false; code: number }>;
51
+ export function realProc(platform: string, run: Runner): Proc;
52
+ export function daemonState(options: { appDir: string; root: string; platform: string; proc: Proc }): Promise<{ state: "running" | "other" | "stopped"; pid?: number }>;
53
+ export function stopDaemon(options: {
54
+ appDir: string;
55
+ root: string;
56
+ platform: string;
57
+ force?: boolean;
58
+ env: Record<string, string | undefined>;
59
+ proc: Proc;
60
+ run: Runner;
61
+ }): Promise<{ status: "none" | "other" | "stopped" } | { status: "busy"; sessions?: number }>;
62
+ export function disconnectRemote(options: {
63
+ settingsFile: string;
64
+ lang?: "en" | "vi";
65
+ log?: (line: string) => void;
66
+ force?: boolean;
67
+ env?: Record<string, string | undefined>;
68
+ home: string;
69
+ platform?: string;
70
+ node?: string;
71
+ fetchImpl?: typeof fetch;
72
+ run?: Runner;
73
+ proc?: Proc;
74
+ userPath?: UserPath;
75
+ }): Promise<{ found: boolean; blocked: boolean }>;
76
+ export function remoteStatus(options: {
77
+ settingsFile: string;
78
+ lang?: "en" | "vi";
79
+ log?: (line: string) => void;
80
+ env?: Record<string, string | undefined>;
81
+ home: string;
82
+ platform?: string;
83
+ run?: Runner;
84
+ proc?: Proc;
85
+ }): Promise<number>;