@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.
- package/README.md +13 -1
- package/bin/tokenhub.js +44 -5
- package/lib/claude-shim.d.ts +37 -0
- package/lib/claude-shim.js +284 -0
- package/lib/desktop-connect.js +2 -2
- package/lib/desktop.d.ts +2 -1
- package/lib/desktop.js +18 -5
- package/lib/pair.d.ts +6 -0
- package/lib/pair.js +14 -1
- package/lib/remote-download.d.ts +29 -0
- package/lib/remote-download.js +242 -0
- package/lib/remote-install.d.ts +85 -0
- package/lib/remote-install.js +582 -0
- package/lib/remote-paths.d.ts +7 -0
- package/lib/remote-paths.js +72 -0
- package/lib/remote-shim.d.ts +8 -0
- package/lib/remote-shim.js +124 -0
- package/lib/remote-text.d.ts +4 -0
- package/lib/remote-text.js +143 -0
- package/lib/remote.d.ts +33 -0
- package/lib/remote.js +201 -0
- package/lib/run.d.ts +8 -0
- package/lib/run.js +16 -0
- package/lib/user-path.d.ts +20 -0
- package/lib/user-path.js +227 -0
- package/package.json +1 -1
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { chmodSync, copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmdirSync, rmSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { SHIM_MARKER } from "./claude-shim.js";
|
|
5
|
+
|
|
6
|
+
/** The runtime the wrappers start; this package's copy, which `installShimFiles` copies to `claude-shim.mjs` in the shim folder. */
|
|
7
|
+
const SHIM_SOURCE = fileURLToPath(new URL("./claude-shim.js", import.meta.url));
|
|
8
|
+
/** Name of the copy in the shim folder (`.mjs`, so Node reads it as a module whatever folder it is in). */
|
|
9
|
+
export const SHIM_RUNTIME = "claude-shim.mjs";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* The `claude.cmd` wrapper for Windows (cmd.exe and PowerShell find it first on PATH): run the runtime with Node, as npm's own
|
|
13
|
+
* `.cmd` shims do (the `goto` ends the batch context so Ctrl+C does not ask "Terminate batch job?"); without Node, run the real
|
|
14
|
+
* claude found at install time.
|
|
15
|
+
* @param {string | undefined} realClaude The real claude's path at install time (the fallback when Node is not on PATH).
|
|
16
|
+
* @returns {string} The file's text (CRLF lines).
|
|
17
|
+
*/
|
|
18
|
+
export function renderCmdWrapper(realClaude) {
|
|
19
|
+
const fallback = realClaude ? `"${realClaude.replace(/%/g, "%%")}" %*` : "echo tokenhub: Node.js and Claude Code were not found. Run `tokenhub disconnect` to remove this shim. 1>&2\r\nexit /b 127";
|
|
20
|
+
return [
|
|
21
|
+
"@echo off",
|
|
22
|
+
`rem ${SHIM_MARKER}: written by \`tokenhub connect\`, removed by \`tokenhub disconnect\``,
|
|
23
|
+
"where node >nul 2>nul || goto :nonode",
|
|
24
|
+
`goto #_undefined_# 2>NUL || node "%~dp0${SHIM_RUNTIME}" %*`,
|
|
25
|
+
":nonode",
|
|
26
|
+
fallback,
|
|
27
|
+
"",
|
|
28
|
+
].join("\r\n");
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* The extensionless `claude` wrapper, a POSIX shell script: the shim on macOS, and on Windows what Git Bash finds (it does not run
|
|
32
|
+
* `.cmd` files by name). Runs the runtime with Node; without Node, runs the first other `claude` on PATH.
|
|
33
|
+
* @returns {string} The file's text (LF lines).
|
|
34
|
+
*/
|
|
35
|
+
export function renderShWrapper() {
|
|
36
|
+
return `#!/bin/sh
|
|
37
|
+
# ${SHIM_MARKER}: written by \`tokenhub connect\`, removed by \`tokenhub disconnect\`
|
|
38
|
+
here=$(cd "$(dirname "$0")" && pwd)
|
|
39
|
+
if command -v node >/dev/null 2>&1; then
|
|
40
|
+
dir=$here
|
|
41
|
+
case "$(uname -s)" in MINGW*|MSYS*|CYGWIN*) dir=$(cygpath -w "$here" 2>/dev/null || echo "$here") ;; esac
|
|
42
|
+
exec node "$dir/${SHIM_RUNTIME}" "$@"
|
|
43
|
+
fi
|
|
44
|
+
old=$IFS
|
|
45
|
+
IFS=:
|
|
46
|
+
for d in $PATH; do
|
|
47
|
+
[ "$d" = "$here" ] && continue
|
|
48
|
+
for n in claude claude.exe; do
|
|
49
|
+
if [ -f "$d/$n" ] && [ -x "$d/$n" ]; then IFS=$old; exec "$d/$n" "$@"; fi
|
|
50
|
+
done
|
|
51
|
+
done
|
|
52
|
+
echo "tokenhub: Node.js and Claude Code were not found. Run \\\`tokenhub disconnect\\\` to remove this shim." >&2
|
|
53
|
+
exit 127
|
|
54
|
+
`;
|
|
55
|
+
}
|
|
56
|
+
/** @param {string} platform Node platform name. @returns {string[]} The wrapper files for that system (the runtime is separate). */
|
|
57
|
+
export function wrapperNames(platform) {
|
|
58
|
+
return platform === "win32" ? ["claude.cmd", "claude"] : ["claude"];
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Write the `claude` shim into `binDir`: the wrapper(s) and the runtime. Files already there are replaced (the folder is ours).
|
|
62
|
+
*
|
|
63
|
+
* @param {object} options
|
|
64
|
+
* @param {string} options.binDir The shim folder (`~/.tokenhub/bin`); created.
|
|
65
|
+
* @param {string} options.platform `win32` or `darwin`.
|
|
66
|
+
* @param {string | undefined} options.realClaude The real claude's path (for the `.cmd`'s no-Node fallback).
|
|
67
|
+
* @returns {string[]} The paths written.
|
|
68
|
+
*/
|
|
69
|
+
export function installShimFiles({ binDir, platform, realClaude }) {
|
|
70
|
+
mkdirSync(binDir, { recursive: true });
|
|
71
|
+
const written = [];
|
|
72
|
+
copyFileSync(SHIM_SOURCE, join(binDir, SHIM_RUNTIME));
|
|
73
|
+
written.push(join(binDir, SHIM_RUNTIME));
|
|
74
|
+
for (const name of wrapperNames(platform)) {
|
|
75
|
+
const file = join(binDir, name);
|
|
76
|
+
writeFileSync(file, name === "claude.cmd" ? renderCmdWrapper(realClaude) : renderShWrapper());
|
|
77
|
+
if (platform !== "win32") chmodSync(file, 0o755);
|
|
78
|
+
written.push(file);
|
|
79
|
+
}
|
|
80
|
+
return written;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Whether the shim files are in `binDir` (the runtime and every wrapper, each carrying our marker).
|
|
84
|
+
* @param {string} binDir The shim folder.
|
|
85
|
+
* @param {string} platform Node platform name.
|
|
86
|
+
* @returns {boolean} True when the shim is installed.
|
|
87
|
+
*/
|
|
88
|
+
export function shimInstalled(binDir, platform) {
|
|
89
|
+
return [SHIM_RUNTIME, ...wrapperNames(platform)].every((name) => isOurs(join(binDir, name)));
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Whether any shim file of ours is in `binDir` (a half-installed or half-removed shim counts).
|
|
93
|
+
* @param {string} binDir The shim folder.
|
|
94
|
+
* @param {string} platform Node platform name.
|
|
95
|
+
* @returns {boolean} True when at least one file carries our marker.
|
|
96
|
+
*/
|
|
97
|
+
export function shimPresent(binDir, platform) {
|
|
98
|
+
return [SHIM_RUNTIME, ...wrapperNames(platform)].some((name) => isOurs(join(binDir, name)));
|
|
99
|
+
}
|
|
100
|
+
/** @param {string} file A path. @returns {boolean} Whether it is a file carrying our marker. */
|
|
101
|
+
function isOurs(file) {
|
|
102
|
+
try {
|
|
103
|
+
return readFileSync(file, "utf8").includes(SHIM_MARKER);
|
|
104
|
+
} catch {
|
|
105
|
+
return false;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Remove the shim's files from `binDir`: only those that carry our marker; the folder goes too when that leaves it empty.
|
|
110
|
+
* @param {string} binDir The shim folder.
|
|
111
|
+
* @param {string} platform Node platform name.
|
|
112
|
+
* @returns {string[]} The paths removed.
|
|
113
|
+
*/
|
|
114
|
+
export function removeShimFiles(binDir, platform) {
|
|
115
|
+
const removed = [];
|
|
116
|
+
for (const name of [...wrapperNames(platform), SHIM_RUNTIME]) {
|
|
117
|
+
const file = join(binDir, name);
|
|
118
|
+
if (!isOurs(file)) continue;
|
|
119
|
+
rmSync(file);
|
|
120
|
+
removed.push(file);
|
|
121
|
+
}
|
|
122
|
+
if (existsSync(binDir) && readdirSync(binDir).length === 0) rmdirSync(binDir);
|
|
123
|
+
return removed;
|
|
124
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export function detectLang(env?: Record<string, string | undefined>): "en" | "vi";
|
|
2
|
+
type Strings = Record<string, string | ((...args: any[]) => any)>;
|
|
3
|
+
export function text(lang: "en" | "vi"): Record<string, any>;
|
|
4
|
+
export const DICTIONARIES: { en: Strings; vi: Strings };
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { detectLang } from "./claude-shim.js";
|
|
2
|
+
|
|
3
|
+
export { detectLang };
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The words of the Remote installer, in English and Vietnamese (the CLI's prompts for this feature are bilingual: `detectLang`
|
|
7
|
+
* picks from `TOKENHUB_LANG`, `LC_ALL`, `LANG` or the system locale). Both languages have the same keys; a test holds them to it.
|
|
8
|
+
*/
|
|
9
|
+
const TEXT = {
|
|
10
|
+
en: {
|
|
11
|
+
askRemote: "Use Claude from your phone (TokenHub Remote)?",
|
|
12
|
+
askShim: "Make `claude` start through TokenHub Remote?",
|
|
13
|
+
shimIntro: (dir, where) => [
|
|
14
|
+
"",
|
|
15
|
+
"To use Remote just by typing `claude`, TokenHub can put a small launcher first on your PATH:",
|
|
16
|
+
` - it adds ${dir} ${where}`,
|
|
17
|
+
" - `claude` then starts your session through TokenHub Remote, so your phone can join it",
|
|
18
|
+
" - `claude mcp`, `claude -p`, `claude --version`, redirected input and the like run Claude Code untouched",
|
|
19
|
+
" - `tokenhub disconnect` removes it again",
|
|
20
|
+
],
|
|
21
|
+
wherePath: "to your user PATH (it takes effect in new terminals)",
|
|
22
|
+
whereProfile: "to PATH in ~/.zprofile (and ~/.bash_profile if you have one)",
|
|
23
|
+
unsupported: (platform) => `TokenHub Remote is available for Windows and macOS (this is ${platform}).`,
|
|
24
|
+
downloading: "Downloading TokenHub Remote...",
|
|
25
|
+
installed: (version) => `TokenHub Remote ${version} installed.`,
|
|
26
|
+
updated: (version, previous) => `TokenHub Remote updated: ${previous} -> ${version}.`,
|
|
27
|
+
repaired: (version) => `TokenHub Remote ${version} reinstalled (a file was missing or damaged).`,
|
|
28
|
+
kept: (version) => `TokenHub Remote ${version} is already installed and up to date.`,
|
|
29
|
+
failed: (reason) => `TokenHub Remote was not installed: ${reason}`,
|
|
30
|
+
keepingToken: (name) => `This computer is already paired for Remote as "${name}"; keeping its token.`,
|
|
31
|
+
movedConfig: (from, to) => `Moved the Remote settings out of TicketFlow's folder (${from}) to ${to}.`,
|
|
32
|
+
pairing: "Pairing this computer for TokenHub Remote (one more approval in the browser):",
|
|
33
|
+
pairingFailed: "TokenHub Remote was not set up: this computer was not paired.",
|
|
34
|
+
hooks: "Adding the /tf-remote command to Claude Code...",
|
|
35
|
+
hooksFailed: (reason) => `TokenHub Remote was not set up: the Claude Code hook could not be installed (${reason}).`,
|
|
36
|
+
shimOn: (dir) => `Launcher installed in ${dir}.`,
|
|
37
|
+
shimPathFailed: (reason) => `The launcher is in place but PATH was not changed (${reason}). Add its folder to PATH yourself, or run \`tokenhub disconnect\` to remove it.`,
|
|
38
|
+
shimNoClaude: "Claude Code was not found on PATH. The launcher will find it once it is installed.",
|
|
39
|
+
shimSkipped: "Launcher skipped. Start Claude through Remote with:",
|
|
40
|
+
shimSkippedHint: "Run `tokenhub connect --remote` again in a terminal to add the launcher.",
|
|
41
|
+
done: (version) => `TokenHub Remote ${version} is set up.`,
|
|
42
|
+
lineComputer: (name) => ` Computer: ${name}`,
|
|
43
|
+
linePage: (url) => ` Manage: ${url} (your computers; revoke any time)`,
|
|
44
|
+
lineHooks: (dir) => ` Hooks: /tf-remote command and hooks in ${dir}`,
|
|
45
|
+
lineShim: (on) => ` Launcher: ${on ? "on: `claude` starts through Remote" : "off"}`,
|
|
46
|
+
next: "Next: open a NEW terminal, run `claude`, type /tf-remote and scan the QR code with your phone.",
|
|
47
|
+
nextNoShim: (tfc) => `Next: run \`${tfc}\` instead of \`claude\`, type /tf-remote and scan the QR code with your phone.`,
|
|
48
|
+
// disconnect
|
|
49
|
+
busy: (n) => `${n === undefined ? "Hosted Claude sessions" : `${n} hosted Claude session(s)`} may be running through TokenHub Remote. Close them (or run \`tokenhub disconnect --force\` to stop them) and run this again. Nothing was changed.`,
|
|
50
|
+
stopped: "Stopped the Remote daemon.",
|
|
51
|
+
revoked: "This computer's Remote token was revoked on the pool.",
|
|
52
|
+
revokedAlready: "This computer's Remote token was already revoked.",
|
|
53
|
+
revokeFailed: (url) => `Could not reach the pool to revoke this computer's Remote token. Revoke it on ${url}`,
|
|
54
|
+
hooksRemoved: "Removed the /tf-remote command and hooks from Claude Code.",
|
|
55
|
+
hooksStay: (dir) => `The hook script is gone, so the TokenHub Remote hooks in ${dir} were left: remove the entries that mention tf-remote-hook.mjs.`,
|
|
56
|
+
pathRemoved: "Removed the launcher from PATH.",
|
|
57
|
+
pathFailed: (reason) => `Could not take the launcher out of PATH (${reason}). Remove ~/.tokenhub/bin from your PATH yourself.`,
|
|
58
|
+
shimRemoved: "Removed the claude launcher.",
|
|
59
|
+
remoteRemoved: "Removed TokenHub Remote.",
|
|
60
|
+
notRemoved: (reason) => `Could not remove the Remote folder (${reason}). Delete it yourself once no Claude session is open.`,
|
|
61
|
+
nothingRemote: "TokenHub Remote was not installed.",
|
|
62
|
+
// status
|
|
63
|
+
notInstalled: "TokenHub Remote is not installed. Run `tokenhub connect --remote` to set it up.",
|
|
64
|
+
statusVersion: (version, dir) => `Version: ${version} (${dir})`,
|
|
65
|
+
statusDaemon: (state, pid) => `Daemon: ${state === "running" ? `running (pid ${pid})` : state === "other" ? `another host daemon is running (pid ${pid}), not TokenHub Remote's` : "not running (it starts with your next Claude session)"}`,
|
|
66
|
+
statusRelay: (url) => `Relay: ${url} (the daemon does not report its connection; this is its configuration)`,
|
|
67
|
+
statusNoRelay: "Relay: not configured (relay.json is missing): run `tokenhub connect --remote`",
|
|
68
|
+
statusDevice: (name) => `Computer: ${name}`,
|
|
69
|
+
statusShim: (state) => `Launcher: ${state === "active" ? "on: `claude` in this terminal starts through Remote" : state === "installed" ? "installed, but `claude` in this terminal does not use it (open a new terminal, or another claude comes first on PATH)" : "off"}`,
|
|
70
|
+
statusHooks: (on) => `Hooks: ${on ? "installed (/tf-remote)" : "missing: run `tokenhub connect --remote`"}`,
|
|
71
|
+
statusPage: (url) => `Manage: ${url}`,
|
|
72
|
+
},
|
|
73
|
+
vi: {
|
|
74
|
+
askRemote: "Dùng Claude từ điện thoại của bạn (TokenHub Remote)?",
|
|
75
|
+
askShim: "Cho lệnh `claude` khởi động qua TokenHub Remote?",
|
|
76
|
+
shimIntro: (dir, where) => [
|
|
77
|
+
"",
|
|
78
|
+
"Để dùng Remote chỉ bằng cách gõ `claude`, TokenHub có thể đặt một trình khởi chạy nhỏ lên đầu PATH của bạn:",
|
|
79
|
+
` - thêm ${dir} ${where}`,
|
|
80
|
+
" - lệnh `claude` sẽ mở phiên làm việc qua TokenHub Remote để điện thoại của bạn tham gia được",
|
|
81
|
+
" - `claude mcp`, `claude -p`, `claude --version`, đầu vào được chuyển hướng... vẫn chạy Claude Code như bình thường",
|
|
82
|
+
" - `tokenhub disconnect` sẽ gỡ nó đi",
|
|
83
|
+
],
|
|
84
|
+
wherePath: "vào PATH của người dùng (có hiệu lực ở cửa sổ terminal mới)",
|
|
85
|
+
whereProfile: "vào PATH trong ~/.zprofile (và ~/.bash_profile nếu bạn có)",
|
|
86
|
+
unsupported: (platform) => `TokenHub Remote chỉ có cho Windows và macOS (đây là ${platform}).`,
|
|
87
|
+
downloading: "Đang tải TokenHub Remote...",
|
|
88
|
+
installed: (version) => `Đã cài TokenHub Remote ${version}.`,
|
|
89
|
+
updated: (version, previous) => `Đã cập nhật TokenHub Remote: ${previous} -> ${version}.`,
|
|
90
|
+
repaired: (version) => `Đã cài lại TokenHub Remote ${version} (thiếu hoặc hỏng một tệp).`,
|
|
91
|
+
kept: (version) => `TokenHub Remote ${version} đã được cài và đang mới nhất.`,
|
|
92
|
+
failed: (reason) => `Chưa cài được TokenHub Remote: ${reason}`,
|
|
93
|
+
keepingToken: (name) => `Máy này đã được ghép cho Remote với tên "${name}"; giữ nguyên token.`,
|
|
94
|
+
movedConfig: (from, to) => `Đã chuyển cài đặt Remote ra khỏi thư mục của TicketFlow (${from}) sang ${to}.`,
|
|
95
|
+
pairing: "Đang ghép máy này với TokenHub Remote (thêm một lần xác nhận trên trình duyệt):",
|
|
96
|
+
pairingFailed: "Chưa thiết lập TokenHub Remote: máy này chưa được ghép.",
|
|
97
|
+
hooks: "Đang thêm lệnh /tf-remote vào Claude Code...",
|
|
98
|
+
hooksFailed: (reason) => `Chưa thiết lập TokenHub Remote: không cài được hook cho Claude Code (${reason}).`,
|
|
99
|
+
shimOn: (dir) => `Đã cài trình khởi chạy vào ${dir}.`,
|
|
100
|
+
shimPathFailed: (reason) => `Trình khởi chạy đã có nhưng chưa sửa được PATH (${reason}). Hãy tự thêm thư mục của nó vào PATH, hoặc chạy \`tokenhub disconnect\` để gỡ.`,
|
|
101
|
+
shimNoClaude: "Không thấy Claude Code trong PATH. Trình khởi chạy sẽ tự tìm thấy nó khi bạn cài xong.",
|
|
102
|
+
shimSkipped: "Bỏ qua trình khởi chạy. Hãy mở Claude qua Remote bằng lệnh:",
|
|
103
|
+
shimSkippedHint: "Chạy lại `tokenhub connect --remote` trong terminal để thêm trình khởi chạy.",
|
|
104
|
+
done: (version) => `TokenHub Remote ${version} đã sẵn sàng.`,
|
|
105
|
+
lineComputer: (name) => ` Máy tính: ${name}`,
|
|
106
|
+
linePage: (url) => ` Quản lý: ${url} (các máy của bạn; thu hồi bất cứ lúc nào)`,
|
|
107
|
+
lineHooks: (dir) => ` Hook: lệnh /tf-remote và các hook trong ${dir}`,
|
|
108
|
+
lineShim: (on) => ` Khởi chạy: ${on ? "bật: `claude` mở qua Remote" : "tắt"}`,
|
|
109
|
+
next: "Tiếp theo: mở cửa sổ terminal MỚI, chạy `claude`, gõ /tf-remote rồi quét mã QR bằng điện thoại.",
|
|
110
|
+
nextNoShim: (tfc) => `Tiếp theo: chạy \`${tfc}\` thay cho \`claude\`, gõ /tf-remote rồi quét mã QR bằng điện thoại.`,
|
|
111
|
+
busy: (n) => `${n === undefined ? "Có thể còn phiên Claude" : `Còn ${n} phiên Claude`} đang chạy qua TokenHub Remote. Hãy đóng chúng (hoặc chạy \`tokenhub disconnect --force\` để dừng) rồi chạy lại. Chưa có gì bị thay đổi.`,
|
|
112
|
+
stopped: "Đã dừng daemon Remote.",
|
|
113
|
+
revoked: "Đã thu hồi token Remote của máy này trên pool.",
|
|
114
|
+
revokedAlready: "Token Remote của máy này đã được thu hồi từ trước.",
|
|
115
|
+
revokeFailed: (url) => `Không kết nối được pool để thu hồi token Remote của máy này. Hãy thu hồi tại ${url}`,
|
|
116
|
+
hooksRemoved: "Đã gỡ lệnh /tf-remote và các hook khỏi Claude Code.",
|
|
117
|
+
hooksStay: (dir) => `Tệp hook không còn nên các hook của TokenHub Remote trong ${dir} được giữ lại: hãy xóa các mục nhắc đến tf-remote-hook.mjs.`,
|
|
118
|
+
pathRemoved: "Đã gỡ trình khởi chạy khỏi PATH.",
|
|
119
|
+
pathFailed: (reason) => `Không gỡ được trình khởi chạy khỏi PATH (${reason}). Hãy tự xóa ~/.tokenhub/bin khỏi PATH.`,
|
|
120
|
+
shimRemoved: "Đã gỡ trình khởi chạy claude.",
|
|
121
|
+
remoteRemoved: "Đã gỡ TokenHub Remote.",
|
|
122
|
+
notRemoved: (reason) => `Không xóa được thư mục Remote (${reason}). Hãy tự xóa khi không còn phiên Claude nào đang mở.`,
|
|
123
|
+
nothingRemote: "TokenHub Remote chưa được cài.",
|
|
124
|
+
notInstalled: "TokenHub Remote chưa được cài. Chạy `tokenhub connect --remote` để thiết lập.",
|
|
125
|
+
statusVersion: (version, dir) => `Phiên bản: ${version} (${dir})`,
|
|
126
|
+
statusDaemon: (state, pid) => `Daemon: ${state === "running" ? `đang chạy (pid ${pid})` : state === "other" ? `đang chạy một daemon khác (pid ${pid}), không phải của TokenHub Remote` : "không chạy (sẽ tự khởi động cùng phiên Claude kế tiếp)"}`,
|
|
127
|
+
statusRelay: (url) => `Relay: ${url} (daemon không báo trạng thái kết nối; đây là cấu hình của nó)`,
|
|
128
|
+
statusNoRelay: "Relay: chưa cấu hình (thiếu relay.json): chạy `tokenhub connect --remote`",
|
|
129
|
+
statusDevice: (name) => `Máy tính: ${name}`,
|
|
130
|
+
statusShim: (state) => `Khởi chạy: ${state === "active" ? "bật: `claude` trong terminal này mở qua Remote" : state === "installed" ? "đã cài, nhưng `claude` trong terminal này chưa dùng nó (mở terminal mới, hoặc có claude khác đứng trước trong PATH)" : "tắt"}`,
|
|
131
|
+
statusHooks: (on) => `Hook: ${on ? "đã cài (/tf-remote)" : "thiếu: chạy `tokenhub connect --remote`"}`,
|
|
132
|
+
statusPage: (url) => `Quản lý: ${url}`,
|
|
133
|
+
},
|
|
134
|
+
};
|
|
135
|
+
/**
|
|
136
|
+
* @param {"en" | "vi"} lang The language.
|
|
137
|
+
* @returns {typeof TEXT.en} Its strings and message builders.
|
|
138
|
+
*/
|
|
139
|
+
export function text(lang) {
|
|
140
|
+
return TEXT[lang] ?? TEXT.en;
|
|
141
|
+
}
|
|
142
|
+
/** The two dictionaries, for the test that checks they have the same keys. */
|
|
143
|
+
export const DICTIONARIES = TEXT;
|
package/lib/remote.d.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export function startRemotePairing(options: {
|
|
2
|
+
pool: string;
|
|
3
|
+
deviceName: string;
|
|
4
|
+
signal?: AbortSignal;
|
|
5
|
+
fetchImpl?: typeof fetch;
|
|
6
|
+
}): Promise<
|
|
7
|
+
| { ok: true; deviceCode: string; userCode: string; verifyUrl: string; interval: number; expiresIn: number }
|
|
8
|
+
| { ok: false; reason: "rate-limited" | "unsupported" | "rejected"; status: number }
|
|
9
|
+
>;
|
|
10
|
+
export function pollRemotePairing(options: {
|
|
11
|
+
pool: string;
|
|
12
|
+
deviceCode: string;
|
|
13
|
+
signal?: AbortSignal;
|
|
14
|
+
fetchImpl?: typeof fetch;
|
|
15
|
+
}): Promise<{ status: "pending" | "denied" | "expired" } | { status: "approved"; token: string; baseUrl: string }>;
|
|
16
|
+
export function pairRemote(options: {
|
|
17
|
+
pool: string;
|
|
18
|
+
deviceName?: string;
|
|
19
|
+
log: (line: string) => void;
|
|
20
|
+
open: (url: string) => void;
|
|
21
|
+
signal?: AbortSignal;
|
|
22
|
+
intervalOverrideMs?: number;
|
|
23
|
+
fetchImpl?: typeof fetch;
|
|
24
|
+
}): Promise<{ ok: true; token: string; baseUrl: string } | { ok: false; code: number }>;
|
|
25
|
+
export function remoteDevConfigPath(dir?: string): string;
|
|
26
|
+
export function writeRemoteDevConfig(file: string, baseUrl: string, token: string): void;
|
|
27
|
+
export function checkRemoteToken(options: {
|
|
28
|
+
pool: string;
|
|
29
|
+
token: string;
|
|
30
|
+
signal?: AbortSignal;
|
|
31
|
+
fetchImpl?: typeof fetch;
|
|
32
|
+
}): Promise<{ status: "valid"; deviceName: string; relayOrigin: string } | { status: "revoked" } | { status: "unknown" }>;
|
|
33
|
+
export function revokeRemoteToken(options: { pool: string; token: string; signal?: AbortSignal; fetchImpl?: typeof fetch }): Promise<"revoked" | "already" | "failed">;
|
package/lib/remote.js
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import { mkdirSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { hostname, tmpdir } from "node:os";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
|
|
5
|
+
/** Path the confirm page of a `remote` pairing has; a pool without it would turn the pairing into a gateway key, so it is checked first. */
|
|
6
|
+
const REMOTE_VERIFY_PATH = "/member/remote/pair";
|
|
7
|
+
const MAX_WAIT_MS = 15 * 60 * 1000;
|
|
8
|
+
/**
|
|
9
|
+
* POST JSON to the pool and parse the reply.
|
|
10
|
+
* @param {string} url Endpoint URL.
|
|
11
|
+
* @param {object} body JSON payload.
|
|
12
|
+
* @param {AbortSignal} [signal] Cancels the request.
|
|
13
|
+
* @param {typeof fetch} [fetchImpl] `fetch` override for tests.
|
|
14
|
+
* @returns {Promise<{ status: number, body: any }>} HTTP status and parsed JSON (null when not JSON).
|
|
15
|
+
*/
|
|
16
|
+
async function postJson(url, body, signal, fetchImpl = fetch) {
|
|
17
|
+
const res = await fetchImpl(url, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), signal });
|
|
18
|
+
return { status: res.status, body: await res.json().catch(() => null) };
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Sleep that resolves early when the signal aborts.
|
|
22
|
+
* @param {number} ms Duration in milliseconds.
|
|
23
|
+
* @param {AbortSignal} [signal] Cancels the wait.
|
|
24
|
+
* @returns {Promise<void>}
|
|
25
|
+
*/
|
|
26
|
+
function sleep(ms, signal) {
|
|
27
|
+
return new Promise((resolve) => {
|
|
28
|
+
if (signal?.aborted) return resolve();
|
|
29
|
+
const timer = setTimeout(done, ms);
|
|
30
|
+
function done() {
|
|
31
|
+
clearTimeout(timer);
|
|
32
|
+
signal?.removeEventListener("abort", done);
|
|
33
|
+
resolve();
|
|
34
|
+
}
|
|
35
|
+
signal?.addEventListener("abort", done);
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Start a TokenHub Remote pairing: ask the pool for a device code of kind `remote`. Nothing is opened or printed.
|
|
40
|
+
*
|
|
41
|
+
* The reply's `verifyUrl` is checked to be the Remote confirm page. A pool that does not know the `remote` kind (not updated
|
|
42
|
+
* yet) would answer with the member page, whose approval issues a gateway key, so that reply is refused here.
|
|
43
|
+
*
|
|
44
|
+
* @param {object} options
|
|
45
|
+
* @param {string} options.pool Pool address from `resolvePoolUrl`.
|
|
46
|
+
* @param {string} options.deviceName Name shown on the confirmation page and listed on `/member/remote`.
|
|
47
|
+
* @param {AbortSignal} [options.signal] Cancels the request.
|
|
48
|
+
* @param {typeof fetch} [options.fetchImpl] `fetch` override for tests.
|
|
49
|
+
* @returns {Promise<{ ok: true, deviceCode: string, userCode: string, verifyUrl: string, interval: number, expiresIn: number } | { ok: false, reason: "rate-limited" | "unsupported" | "rejected", status: number }>}
|
|
50
|
+
*/
|
|
51
|
+
export async function startRemotePairing({ pool, deviceName, signal, fetchImpl = fetch }) {
|
|
52
|
+
const start = await postJson(`${pool}/pair/start`, { deviceName, kind: "remote" }, signal, fetchImpl);
|
|
53
|
+
if (start.status === 429) return { ok: false, reason: "rate-limited", status: 429 };
|
|
54
|
+
const body = start.body;
|
|
55
|
+
if (start.status !== 200 || !body?.deviceCode || !body.userCode) return { ok: false, reason: "rejected", status: start.status };
|
|
56
|
+
const verifyUrl = pool.startsWith("https://") && String(body.verifyUrl || "").startsWith("http://") ? body.verifyUrl.replace(/^http:\/\//, "https://") : String(body.verifyUrl || "");
|
|
57
|
+
if (!URL.canParse(verifyUrl) || new URL(verifyUrl).pathname !== REMOTE_VERIFY_PATH) return { ok: false, reason: "unsupported", status: start.status };
|
|
58
|
+
return { ok: true, deviceCode: body.deviceCode, userCode: body.userCode, verifyUrl, interval: Number(body.interval) || 3, expiresIn: Number(body.expiresIn) || 600 };
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Ask the pool once whether a Remote pairing was approved.
|
|
62
|
+
*
|
|
63
|
+
* @param {object} options
|
|
64
|
+
* @param {string} options.pool Pool address.
|
|
65
|
+
* @param {string} options.deviceCode Secret code from `startRemotePairing`.
|
|
66
|
+
* @param {AbortSignal} [options.signal] Cancels the request.
|
|
67
|
+
* @param {typeof fetch} [options.fetchImpl] `fetch` override for tests.
|
|
68
|
+
* @returns {Promise<{ status: "pending" | "denied" | "expired" } | { status: "approved", token: string, baseUrl: string }>} An approved
|
|
69
|
+
* answer carries the relay-scoped device token (once) and the address it was issued by. A token of another kind is reported as `denied`.
|
|
70
|
+
*/
|
|
71
|
+
export async function pollRemotePairing({ pool, deviceCode, signal, fetchImpl = fetch }) {
|
|
72
|
+
const poll = await postJson(`${pool}/pair/poll`, { deviceCode }, signal, fetchImpl);
|
|
73
|
+
if (poll.status === 429) return { status: "pending" };
|
|
74
|
+
const body = poll.body;
|
|
75
|
+
if (body?.status === "approved") {
|
|
76
|
+
if (body.kind !== "remote" || typeof body.key !== "string") return { status: "denied" };
|
|
77
|
+
const baseUrl = pool.startsWith("https://") && String(body.baseUrl || "").startsWith("http://") ? body.baseUrl.replace(/^http:\/\//, "https://") : body.baseUrl || pool;
|
|
78
|
+
return { status: "approved", token: body.key, baseUrl };
|
|
79
|
+
}
|
|
80
|
+
return { status: body?.status === "denied" || body?.status === "expired" ? body.status : "pending" };
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Pair this machine for TokenHub Remote: start, show the code and open the confirm page, then poll until the member decides.
|
|
84
|
+
*
|
|
85
|
+
* @param {object} options
|
|
86
|
+
* @param {string} options.pool Pool address from `resolvePoolUrl`.
|
|
87
|
+
* @param {string} [options.deviceName] Name for this machine (the host name by default).
|
|
88
|
+
* @param {(line: string) => void} options.log Output sink.
|
|
89
|
+
* @param {(url: string) => void} options.open Browser opener.
|
|
90
|
+
* @param {AbortSignal} [options.signal] Aborts the flow (Ctrl+C).
|
|
91
|
+
* @param {number} [options.intervalOverrideMs] Poll interval override (tests).
|
|
92
|
+
* @param {typeof fetch} [options.fetchImpl] `fetch` override for tests.
|
|
93
|
+
* @returns {Promise<{ ok: true, token: string, baseUrl: string } | { ok: false, code: number }>} The device token and the pool address, or
|
|
94
|
+
* the exit code to report (cancelled, denied, expired, timed out, pool too old).
|
|
95
|
+
*/
|
|
96
|
+
export async function pairRemote({ pool, deviceName = hostname(), log, open, signal, intervalOverrideMs, fetchImpl = fetch }) {
|
|
97
|
+
const start = await startRemotePairing({ pool, deviceName, signal, fetchImpl });
|
|
98
|
+
if (!start.ok) {
|
|
99
|
+
log(
|
|
100
|
+
start.reason === "rate-limited"
|
|
101
|
+
? "Too many pairing attempts. Wait a few minutes and try again."
|
|
102
|
+
: start.reason === "unsupported"
|
|
103
|
+
? "Error: this pool does not support TokenHub Remote yet. Nothing was paired."
|
|
104
|
+
: `Error: the pool rejected the pairing request (HTTP ${start.status}).`,
|
|
105
|
+
);
|
|
106
|
+
return { ok: false, code: 1 };
|
|
107
|
+
}
|
|
108
|
+
log("");
|
|
109
|
+
log(` Your code: ${start.userCode}`);
|
|
110
|
+
log("");
|
|
111
|
+
log(`Confirm it at: ${start.verifyUrl}`);
|
|
112
|
+
log("Opening your browser. Waiting for approval (Ctrl+C to cancel)...");
|
|
113
|
+
open(start.verifyUrl);
|
|
114
|
+
const intervalMs = intervalOverrideMs ?? Math.max(1, start.interval) * 1000;
|
|
115
|
+
const deadline = Date.now() + Math.min(MAX_WAIT_MS, start.expiresIn * 1000 + intervalMs);
|
|
116
|
+
while (Date.now() < deadline) {
|
|
117
|
+
await sleep(intervalMs, signal);
|
|
118
|
+
if (signal?.aborted) {
|
|
119
|
+
log("Cancelled.");
|
|
120
|
+
return { ok: false, code: 130 };
|
|
121
|
+
}
|
|
122
|
+
const poll = await pollRemotePairing({ pool, deviceCode: start.deviceCode, signal, fetchImpl });
|
|
123
|
+
if (poll.status === "approved") return { ok: true, token: poll.token, baseUrl: poll.baseUrl };
|
|
124
|
+
if (poll.status === "denied") {
|
|
125
|
+
log("The request was denied.");
|
|
126
|
+
return { ok: false, code: 1 };
|
|
127
|
+
}
|
|
128
|
+
if (poll.status === "expired") {
|
|
129
|
+
log("The code expired. Run the command again.");
|
|
130
|
+
return { ok: false, code: 1 };
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
log("Timed out waiting for approval. Run the command again.");
|
|
134
|
+
return { ok: false, code: 1 };
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* POST to a token-authenticated Remote endpoint of the pool (`Authorization: Bearer <device token>`).
|
|
138
|
+
* @param {string} url Endpoint URL.
|
|
139
|
+
* @param {string} token The Remote device token.
|
|
140
|
+
* @param {AbortSignal} [signal] Cancels the request.
|
|
141
|
+
* @param {typeof fetch} [fetchImpl] `fetch` override for tests.
|
|
142
|
+
* @returns {Promise<{ status: number, body: any }>} HTTP status and parsed JSON (null when not JSON); status 0 when the pool could not be reached.
|
|
143
|
+
*/
|
|
144
|
+
async function postWithToken(url, token, signal, fetchImpl) {
|
|
145
|
+
try {
|
|
146
|
+
const res = await fetchImpl(url, { method: "POST", headers: { authorization: `Bearer ${token}` }, signal: signal ?? AbortSignal.timeout(20_000) });
|
|
147
|
+
return { status: res.status, body: await res.json().catch(() => null) };
|
|
148
|
+
} catch {
|
|
149
|
+
return { status: 0, body: null };
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Ask the pool whether a Remote device token still works, and where its relay is (`POST /pair/remote/check`).
|
|
154
|
+
*
|
|
155
|
+
* @param {object} options
|
|
156
|
+
* @param {string} options.pool Pool address.
|
|
157
|
+
* @param {string} options.token The device token.
|
|
158
|
+
* @param {AbortSignal} [options.signal] Cancels the request.
|
|
159
|
+
* @param {typeof fetch} [options.fetchImpl] `fetch` override for tests.
|
|
160
|
+
* @returns {Promise<{ status: "valid", deviceName: string, relayOrigin: string } | { status: "revoked" } | { status: "unknown" }>} `valid` carries the name the pool
|
|
161
|
+
* has for the machine and the relay origin it is configured with (empty when it has none); `revoked` is a 401 (re-pair); `unknown` is
|
|
162
|
+
* anything else (pool down, an older pool without the endpoint, rate limited): the token may still be good, so keep it.
|
|
163
|
+
*/
|
|
164
|
+
export async function checkRemoteToken({ pool, token, signal, fetchImpl = fetch }) {
|
|
165
|
+
const res = await postWithToken(`${pool}/pair/remote/check`, token, signal, fetchImpl);
|
|
166
|
+
if (res.status === 200 && typeof res.body?.device?.name === "string") return { status: "valid", deviceName: res.body.device.name, relayOrigin: typeof res.body.relayOrigin === "string" ? res.body.relayOrigin : "" };
|
|
167
|
+
return { status: res.status === 401 ? "revoked" : "unknown" };
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Revoke this machine's own Remote device token on the pool (`POST /pair/remote/revoke`).
|
|
171
|
+
*
|
|
172
|
+
* @param {object} options
|
|
173
|
+
* @param {string} options.pool Pool address.
|
|
174
|
+
* @param {string} options.token The device token.
|
|
175
|
+
* @param {AbortSignal} [options.signal] Cancels the request.
|
|
176
|
+
* @param {typeof fetch} [options.fetchImpl] `fetch` override for tests.
|
|
177
|
+
* @returns {Promise<"revoked" | "already" | "failed">} `already` when the pool no longer knows the token (401); `failed` when it could not be reached or refused.
|
|
178
|
+
*/
|
|
179
|
+
export async function revokeRemoteToken({ pool, token, signal, fetchImpl = fetch }) {
|
|
180
|
+
const res = await postWithToken(`${pool}/pair/remote/revoke`, token, signal, fetchImpl);
|
|
181
|
+
return res.status === 200 ? "revoked" : res.status === 401 ? "already" : "failed";
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Where the dev command parks the token until the daemon's config location exists (phase 1 of the Remote design decides it).
|
|
185
|
+
* @param {string} [dir] Folder to use instead of the system temp folder (tests).
|
|
186
|
+
* @returns {string} Absolute path of `remote-dev.json`.
|
|
187
|
+
*/
|
|
188
|
+
export function remoteDevConfigPath(dir = join(tmpdir(), "tokenhub-remote-dev")) {
|
|
189
|
+
return join(dir, "remote-dev.json");
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Store the pool address and Remote device token, readable only by the current user where the OS supports it.
|
|
193
|
+
* @param {string} file Path from `remoteDevConfigPath`.
|
|
194
|
+
* @param {string} baseUrl Pool address.
|
|
195
|
+
* @param {string} token Remote device token issued by the pool.
|
|
196
|
+
* @returns {void}
|
|
197
|
+
*/
|
|
198
|
+
export function writeRemoteDevConfig(file, baseUrl, token) {
|
|
199
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
200
|
+
writeFileSync(file, `${JSON.stringify({ baseUrl, token }, null, 2)}\n`, { mode: 0o600 });
|
|
201
|
+
}
|
package/lib/run.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export interface RunResult {
|
|
2
|
+
code: number;
|
|
3
|
+
stdout: string;
|
|
4
|
+
stderr: string;
|
|
5
|
+
}
|
|
6
|
+
/** Runs a program (no shell) and collects its output; resolves with code -1 when it could not start or timed out. */
|
|
7
|
+
export type Runner = (file: string, args: string[], options?: { env?: Record<string, string | undefined>; timeoutMs?: number; cwd?: string }) => Promise<RunResult>;
|
|
8
|
+
export const run: Runner;
|
package/lib/run.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Run a program and collect its output; never throws.
|
|
5
|
+
* @param {string} file Program to run (no shell is involved).
|
|
6
|
+
* @param {string[]} args Its arguments.
|
|
7
|
+
* @param {{ env?: Record<string, string | undefined>, timeoutMs?: number, cwd?: string }} [options] Environment, time limit (default 30 s) and working folder.
|
|
8
|
+
* @returns {Promise<{ code: number, stdout: string, stderr: string }>} Exit code (-1 when it could not start or timed out) and the text it printed.
|
|
9
|
+
*/
|
|
10
|
+
export function run(file, args, { env, timeoutMs = 30_000, cwd } = {}) {
|
|
11
|
+
return new Promise((done) => {
|
|
12
|
+
execFile(file, args, { env, cwd, timeout: timeoutMs, windowsHide: true, encoding: "utf8", maxBuffer: 8 * 1024 * 1024 }, (error, stdout, stderr) => {
|
|
13
|
+
done({ code: error ? (typeof error.code === "number" ? error.code : -1) : 0, stdout: String(stdout ?? ""), stderr: String(stderr ?? "") });
|
|
14
|
+
});
|
|
15
|
+
});
|
|
16
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { Runner } from "./run.js";
|
|
2
|
+
export const PROFILE_BEGIN: string;
|
|
3
|
+
export const PROFILE_END: string;
|
|
4
|
+
export interface UserPath {
|
|
5
|
+
get(): Promise<{ value: string | null; kind: string }>;
|
|
6
|
+
set(value: string | null, kind: string): Promise<void>;
|
|
7
|
+
}
|
|
8
|
+
export function addPathEntry(value: string | null, dir: string, platform?: string): string;
|
|
9
|
+
export function removePathEntry(value: string | null, dir: string, platform?: string): string;
|
|
10
|
+
export function hasPathEntry(value: string | null, dir: string, platform?: string): boolean;
|
|
11
|
+
export function profileBlock(dir: string): string;
|
|
12
|
+
export function addProfileBlock(text: string, dir: string): string;
|
|
13
|
+
export function removeProfileBlock(text: string): { text: string; removed: boolean };
|
|
14
|
+
export function profileFiles(home: string): Array<{ file: string; create: boolean }>;
|
|
15
|
+
export function windowsUserPath(options?: { run?: Runner; subKey?: string }): UserPath;
|
|
16
|
+
export function addBinToPath(options: { dir: string; platform: string; home: string; userPath?: UserPath }): Promise<{
|
|
17
|
+
changed: boolean;
|
|
18
|
+
targets: Array<{ kind: "registry" } | { kind: "profile"; file: string }>;
|
|
19
|
+
}>;
|
|
20
|
+
export function removeBinFromPath(options: { dir: string; platform: string; home: string; userPath?: UserPath }): Promise<{ changed: boolean }>;
|