agentroam 0.2.0-preview.77 → 0.2.0-preview.79
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/dist/args.js +24 -4
- package/dist/cli.js +40 -2
- package/dist/codex-sharing.js +5 -3
- package/dist/device-pairing.js +35 -12
- package/dist/mesh/mesh-command.js +51 -0
- package/dist/mesh/mesh-config.js +95 -0
- package/dist/mesh/mesh-payload.js +20 -0
- package/dist/mesh/mesh-runtime.js +101 -0
- package/dist/opencode-runtime-manager.js +44 -23
- package/dist/platform-packages.js +2 -0
- package/dist/runtime-manager.js +10 -1
- package/dist/self-hosted-relay.json +1 -0
- package/dist/service/service-command.js +8 -1
- package/dist/service/service-controller.js +2 -0
- package/dist/tailscale/bundled-asset.js +43 -0
- package/dist/tailscale/daemon-manager.js +112 -0
- package/dist/tailscale/installer.js +131 -0
- package/dist/tailscale/manifest.js +15 -0
- package/dist/tailscale/tailnet-cli.js +101 -0
- package/dist/tunnel/relay-orchestrator.js +43 -37
- package/dist/tunnel/self-hosted-provider.js +147 -0
- package/dist/tunnel/tunnel-controller.js +10 -0
- package/dist/update/update-command.js +1 -0
- package/dist/update/update-worker.js +2 -0
- package/install/write-relay-default.mjs +6 -0
- package/package.json +10 -8
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { execFile } from "node:child_process";
|
|
2
2
|
import { constants } from "node:fs";
|
|
3
3
|
import { access, chmod, mkdir, mkdtemp, open, rename, rm, stat } from "node:fs/promises";
|
|
4
|
+
import { homedir } from "node:os";
|
|
4
5
|
import { delimiter, isAbsolute, relative, resolve, win32 } from "node:path";
|
|
5
6
|
import { promisify } from "node:util";
|
|
6
7
|
import { resolveNpmExecutor } from "./codex-runtime-manager.js";
|
|
@@ -12,6 +13,7 @@ export const OPENCODE_MINIMUM_VERSION = "1.18.27";
|
|
|
12
13
|
const OPENCODE_PACKAGE = `opencode-ai@${OPENCODE_RUNTIME_VERSION}`;
|
|
13
14
|
const NPM_REGISTRY = "https://registry.npmjs.org";
|
|
14
15
|
const defaults = {
|
|
16
|
+
accessible,
|
|
15
17
|
async run(command, args, timeoutMs, signal) {
|
|
16
18
|
try {
|
|
17
19
|
const { stdout, stderr } = await execFileAsync(command, args, {
|
|
@@ -53,9 +55,15 @@ async function resolveRuntime(options) {
|
|
|
53
55
|
const absolute = platform === "win32" ? win32.isAbsolute(explicit) : isAbsolute(explicit);
|
|
54
56
|
if (!absolute)
|
|
55
57
|
throw new Error("AGENT_OPENCODE_BIN must be an absolute path");
|
|
56
|
-
|
|
58
|
+
if (platform === "win32" && /^opencode\.(?:cmd|bat)$/i.test(win32.basename(explicit))) {
|
|
59
|
+
const bundled = await firstCompatible(windowsOpenCodeNpmCandidates(windowsNpmModules(win32.dirname(explicit)), win32.resolve), "explicit", dependencies);
|
|
60
|
+
if (bundled)
|
|
61
|
+
return bundled;
|
|
62
|
+
throw new Error("AGENT_OPENCODE_BIN points to a Windows launcher without a compatible OpenCode executable");
|
|
63
|
+
}
|
|
64
|
+
return validate(explicit, "explicit", dependencies);
|
|
57
65
|
}
|
|
58
|
-
const global = await findGlobal(environment
|
|
66
|
+
const global = await findGlobal(environment, platform, dependencies);
|
|
59
67
|
if (global)
|
|
60
68
|
return global;
|
|
61
69
|
const managedRoot = resolve(options.dataDir, "runtimes", "opencode", OPENCODE_RUNTIME_VERSION);
|
|
@@ -74,8 +82,7 @@ export function parseOpenCodeVersion(output) {
|
|
|
74
82
|
export function managedOpenCodeBinaryCandidates(root, platform) {
|
|
75
83
|
return platform === "win32"
|
|
76
84
|
? [
|
|
77
|
-
resolve(root, "node_modules",
|
|
78
|
-
resolve(root, "node_modules", ".bin", "opencode.cmd"),
|
|
85
|
+
...windowsOpenCodeNpmCandidates(resolve(root, "node_modules"), resolve),
|
|
79
86
|
resolve(root, "node_modules", ".bin", "opencode.exe"),
|
|
80
87
|
]
|
|
81
88
|
: [
|
|
@@ -83,21 +90,35 @@ export function managedOpenCodeBinaryCandidates(root, platform) {
|
|
|
83
90
|
resolve(root, "node_modules", ".bin", "opencode"),
|
|
84
91
|
];
|
|
85
92
|
}
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
93
|
+
function windowsNpmModules(prefix) {
|
|
94
|
+
return win32.resolve(prefix, win32.basename(prefix).toLowerCase() === ".bin" ? ".." : "node_modules");
|
|
95
|
+
}
|
|
96
|
+
function windowsOpenCodeNpmCandidates(modules, resolvePath) {
|
|
97
|
+
return ["opencode-ai", "opencode-windows-x64-baseline", "opencode-windows-x64"]
|
|
98
|
+
.map(name => resolvePath(modules, name, "bin", "opencode.exe"));
|
|
99
|
+
}
|
|
100
|
+
async function findGlobal(environment, platform, dependencies) {
|
|
101
|
+
const windows = platform === "win32";
|
|
102
|
+
const directories = (environment.PATH ?? environment.Path ?? "").split(windows ? ";" : delimiter).filter(Boolean);
|
|
103
|
+
if (!windows) {
|
|
104
|
+
return firstCompatible(directories.map(dir => resolve(dir, "opencode")), "global", dependencies, true);
|
|
105
|
+
}
|
|
106
|
+
const pathDirs = directories.map(dir => dir.trim().replace(/^"(.*)"$/, "$1")).filter(Boolean);
|
|
107
|
+
const roaming = environment.APPDATA || win32.join(homedir(), "AppData", "Roaming");
|
|
108
|
+
const prefixes = [environment.npm_config_prefix || environment.NPM_CONFIG_PREFIX, win32.join(roaming, "npm")];
|
|
109
|
+
return firstCompatible([
|
|
110
|
+
...pathDirs.flatMap(dir => [win32.resolve(dir, "opencode.exe"), ...windowsOpenCodeNpmCandidates(windowsNpmModules(dir), win32.resolve)]),
|
|
111
|
+
...prefixes.filter((dir) => Boolean(dir)).flatMap(dir => windowsOpenCodeNpmCandidates(windowsNpmModules(dir), win32.resolve)),
|
|
112
|
+
], "global", dependencies);
|
|
113
|
+
}
|
|
114
|
+
async function firstCompatible(candidates, source, dependencies, executable = false) {
|
|
115
|
+
for (const candidate of new Set(candidates)) {
|
|
116
|
+
if (!await dependencies.accessible(candidate, executable))
|
|
117
|
+
continue;
|
|
118
|
+
try {
|
|
119
|
+
return await validate(candidate, source, dependencies);
|
|
100
120
|
}
|
|
121
|
+
catch { /* Keep looking for a compatible install. */ }
|
|
101
122
|
}
|
|
102
123
|
return null;
|
|
103
124
|
}
|
|
@@ -185,21 +206,21 @@ async function acquireLock(lockPath, managedRoot, platform, dependencies, waitMs
|
|
|
185
206
|
}
|
|
186
207
|
async function validateManaged(root, platform, dependencies) {
|
|
187
208
|
for (const executable of managedOpenCodeBinaryCandidates(root, platform)) {
|
|
188
|
-
if (!within(root, executable) || !(await accessible(executable)))
|
|
209
|
+
if (!within(root, executable) || !(await dependencies.accessible(executable)))
|
|
189
210
|
continue;
|
|
190
211
|
try {
|
|
191
212
|
if (platform !== "win32")
|
|
192
213
|
await chmod(executable, 0o755);
|
|
193
|
-
return await validate(executable, "managed",
|
|
214
|
+
return await validate(executable, "managed", dependencies);
|
|
194
215
|
}
|
|
195
216
|
catch {
|
|
196
|
-
|
|
217
|
+
// An unusable launcher may coexist with a working platform binary.
|
|
197
218
|
}
|
|
198
219
|
}
|
|
199
220
|
return null;
|
|
200
221
|
}
|
|
201
|
-
async function validate(executable, source,
|
|
202
|
-
if (!(await accessible(executable)))
|
|
222
|
+
async function validate(executable, source, dependencies) {
|
|
223
|
+
if (!(await dependencies.accessible(executable)))
|
|
203
224
|
throw new Error(`OpenCode executable not found: ${executable}`);
|
|
204
225
|
const result = await dependencies.run(executable, ["--version"], 5_000);
|
|
205
226
|
const version = parseOpenCodeVersion(`${result.stdout}\n${result.stderr}`);
|
|
@@ -15,11 +15,13 @@ export const PLATFORM_PACKAGES = {
|
|
|
15
15
|
"darwin-arm64": {
|
|
16
16
|
runtime: "agentroam-runtime-darwin-arm64",
|
|
17
17
|
cloudflared: "agentroam-cloudflared-darwin-arm64",
|
|
18
|
+
tailscale: "agentroam-tailscale-darwin-arm64",
|
|
18
19
|
tui: "agentroam-tui-darwin-arm64",
|
|
19
20
|
},
|
|
20
21
|
"windows-amd64": {
|
|
21
22
|
runtime: "agentroam-runtime-win32-x64",
|
|
22
23
|
cloudflared: "agentroam-cloudflared-win32-x64",
|
|
24
|
+
tailscale: "agentroam-tailscale-win32-x64",
|
|
23
25
|
tui: "@caoqu/agentroam-tui-win32-x64",
|
|
24
26
|
},
|
|
25
27
|
};
|
package/dist/runtime-manager.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { loadMeshEnvironment } from "./mesh/mesh-config.js";
|
|
1
2
|
import { mkdir } from "node:fs/promises";
|
|
2
3
|
import { delimiter, resolve } from "node:path";
|
|
3
4
|
import { fileURLToPath } from "node:url";
|
|
@@ -29,7 +30,8 @@ export class RuntimeManager {
|
|
|
29
30
|
const port = await findAvailablePort(options.port);
|
|
30
31
|
const dataDir = resolve(options.dataDir);
|
|
31
32
|
await Promise.all(["data", "bin", "cache", "logs"].map((name) => mkdir(resolve(dataDir, name), { recursive: true })));
|
|
32
|
-
const
|
|
33
|
+
const { AGENTROAM_MESH_ACTIVATION_CODE: _, ...runtimeEnvironment } = process.env;
|
|
34
|
+
const childEnvironment = await withCliProgress("正在检查 Agent 组件;缺少 Codex 时自动安装最新版,最多等待 180 秒", () => prepareAgentRuntimeEnvironment(runtimeEnvironment, { dataDir, target }, this.codexResolver, this.report, this.opencodeResolver));
|
|
33
35
|
if (process.platform === "darwin" && childEnvironment.AGENT_CODEX_BIN) {
|
|
34
36
|
try {
|
|
35
37
|
await withTimeout(signal => configureCodexSharing(options, { environment: childEnvironment, signal }), CODEX_SHARING_TIMEOUT_MS, "Codex 共享后台配置超时(10 秒)");
|
|
@@ -50,11 +52,18 @@ export class RuntimeManager {
|
|
|
50
52
|
const { runtimeRoot } = resolvePlatformRuntime(target);
|
|
51
53
|
await repairNativeRuntimePermissions(runtimeRoot);
|
|
52
54
|
const gateway = resolve(runtimeRoot, "ws-server.mjs");
|
|
55
|
+
const meshEnvironment = await loadMeshEnvironment(dataDir, process.env).catch(error => {
|
|
56
|
+
if (process.env.AGENTROAM_MESH_ACTIVATION_CODE?.trim())
|
|
57
|
+
throw error;
|
|
58
|
+
this.report(`组网配置未加载:${error.message}`);
|
|
59
|
+
return {};
|
|
60
|
+
});
|
|
53
61
|
const child = this.supervisor.spawn(process.execPath, [gateway, ...(options.testNoPairing ? ["--test-no-pairing"] : [])], {
|
|
54
62
|
stdio: ["ignore", "pipe", "pipe", "ipc"],
|
|
55
63
|
cwd: runtimeRoot,
|
|
56
64
|
env: {
|
|
57
65
|
...childEnvironment,
|
|
66
|
+
...meshEnvironment,
|
|
58
67
|
NODE_ENV: "production",
|
|
59
68
|
NEXT_DIST_DIR: ".next",
|
|
60
69
|
PORT: String(port),
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"url":"https://connect.kaiwuyouwei.com"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { saveMeshEnvironment } from "../mesh/mesh-config.js";
|
|
1
2
|
import { printLocalDesktopUrl } from '../local-desktop-url.js';
|
|
2
3
|
import { delimiter, dirname, isAbsolute, resolve, win32 } from "node:path";
|
|
3
4
|
import { resolveCodexRuntime } from "../codex-runtime-manager.js";
|
|
@@ -49,6 +50,7 @@ export async function runServiceCommand(options, context) {
|
|
|
49
50
|
catch (error) {
|
|
50
51
|
log(`Codex will be checked and installed during service startup: ${error instanceof Error ? error.message : error}`);
|
|
51
52
|
}
|
|
53
|
+
const relayUrl = options.relayUrl ?? environment.AGENTROAM_HTTPS_RELAY_URL?.trim();
|
|
52
54
|
const config = {
|
|
53
55
|
version: context.version,
|
|
54
56
|
nodePath: context.nodePath,
|
|
@@ -60,6 +62,7 @@ export async function runServiceCommand(options, context) {
|
|
|
60
62
|
port: options.port,
|
|
61
63
|
relay: options.relay,
|
|
62
64
|
tunnelCommand: options.tunnelCommand,
|
|
65
|
+
...(relayUrl ? { relayUrl } : {}),
|
|
63
66
|
localOnly: options.localOnly,
|
|
64
67
|
dataDir: options.dataDir,
|
|
65
68
|
installedAt: now.toISOString(),
|
|
@@ -74,6 +77,7 @@ export async function runServiceCommand(options, context) {
|
|
|
74
77
|
log(`Codex sharing setup incomplete; repair it from the computer menu: ${error instanceof Error ? error.message : error}`);
|
|
75
78
|
}
|
|
76
79
|
}
|
|
80
|
+
await saveMeshEnvironment(options.dataDir, environment);
|
|
77
81
|
const { definition, state } = await withCliProgress("Starting service; Codex: up to 180s, Cloudflare: up to 30s, then LAN fallback", () => controller.install(config));
|
|
78
82
|
log(`✓ AgentRoam service installed: ${definition}`);
|
|
79
83
|
if (state?.status !== "ready" && state?.localUrl)
|
|
@@ -104,7 +108,10 @@ export async function runServiceCommand(options, context) {
|
|
|
104
108
|
if (options.desktopSetup && ["darwin", "win32"].includes(platform)) {
|
|
105
109
|
await withCliProgress("Configuring Codex Desktop sharing", () => (context.desktopSetup ?? setupCodexDesktop)(options, { platform, environment, service: config, log }));
|
|
106
110
|
}
|
|
107
|
-
await (context.pairingPrinter ?? printPairingCode)(options.dataDir, log, {
|
|
111
|
+
await (context.pairingPrinter ?? printPairingCode)(options.dataDir, log, {
|
|
112
|
+
fallbackUrl: state.accessUrl, waitForMesh: Boolean(environment.AGENTROAM_MESH_ACTIVATION_CODE?.trim()),
|
|
113
|
+
qr: options.qr, interactive: stdoutIsTTY,
|
|
114
|
+
});
|
|
108
115
|
return;
|
|
109
116
|
}
|
|
110
117
|
case "start": {
|
|
@@ -9,6 +9,8 @@ export function buildStartArguments(config) {
|
|
|
9
9
|
args.push("--local-only");
|
|
10
10
|
else
|
|
11
11
|
args.push("--relay", config.relay);
|
|
12
|
+
if (config.relayUrl)
|
|
13
|
+
args.push("--relay-url", config.relayUrl);
|
|
12
14
|
if (!config.localOnly && config.tunnelCommand)
|
|
13
15
|
args.push("--tunnel-command", config.tunnelCommand);
|
|
14
16
|
args.push("--data-dir", config.dataDir, "--no-qr");
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { PLATFORM_DEPENDENCY_VERSIONS } from "../platform-packages.js";
|
|
4
|
+
import { TAILSCALE_PACKAGES } from "./manifest.js";
|
|
5
|
+
export async function resolveBundledTailscale(target, requireFromCli = createRequire(import.meta.url)) {
|
|
6
|
+
const packageName = TAILSCALE_PACKAGES[target];
|
|
7
|
+
if (!packageName)
|
|
8
|
+
return null;
|
|
9
|
+
let manifestPath;
|
|
10
|
+
let assetPath;
|
|
11
|
+
try {
|
|
12
|
+
manifestPath = requireFromCli.resolve(`${packageName}/manifest.json`);
|
|
13
|
+
assetPath = requireFromCli.resolve(`${packageName}/archive`);
|
|
14
|
+
}
|
|
15
|
+
catch (error) {
|
|
16
|
+
if (["MODULE_NOT_FOUND", "ERR_PACKAGE_PATH_NOT_EXPORTED"].includes(error?.code ?? ""))
|
|
17
|
+
return null;
|
|
18
|
+
throw error;
|
|
19
|
+
}
|
|
20
|
+
const manifest = JSON.parse(await readFile(manifestPath, "utf8"));
|
|
21
|
+
const expectedEntries = target === "windows-amd64" ? ["tailscale.exe", "tailscaled.exe"] : ["tailscale", "tailscaled"];
|
|
22
|
+
if (manifest.packageVersion !== PLATFORM_DEPENDENCY_VERSIONS[packageName] ||
|
|
23
|
+
manifest.target !== target ||
|
|
24
|
+
manifest.assetFormat !== "tgz" ||
|
|
25
|
+
typeof manifest.upstreamVersion !== "string" ||
|
|
26
|
+
!Array.isArray(manifest.entries) ||
|
|
27
|
+
manifest.entries.length !== expectedEntries.length ||
|
|
28
|
+
!expectedEntries.every(entry => manifest.entries.includes(entry)) ||
|
|
29
|
+
typeof manifest.size !== "number" ||
|
|
30
|
+
!Number.isSafeInteger(manifest.size) ||
|
|
31
|
+
manifest.size <= 0 ||
|
|
32
|
+
typeof manifest.sha256 !== "string" ||
|
|
33
|
+
!/^[a-f0-9]{64}$/.test(manifest.sha256)) {
|
|
34
|
+
throw new Error(`invalid tailscale platform manifest: ${manifestPath}`);
|
|
35
|
+
}
|
|
36
|
+
return {
|
|
37
|
+
assetPath,
|
|
38
|
+
sha256: manifest.sha256,
|
|
39
|
+
size: manifest.size,
|
|
40
|
+
entries: manifest.entries,
|
|
41
|
+
version: manifest.upstreamVersion,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
import { chmod, mkdir } from "node:fs/promises";
|
|
4
|
+
import { resolve } from "node:path";
|
|
5
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
6
|
+
import { readTailscaleStatus } from "./tailnet-cli.js";
|
|
7
|
+
/**
|
|
8
|
+
* tailscaled(userspace 模式)生命周期管理。
|
|
9
|
+
*
|
|
10
|
+
* 复用优先:socket 上已有可用的 tailscaled(例如同机另一个 agentroam 进程已拉起)时
|
|
11
|
+
* 直接复用,绝不启动第二个守护进程争抢 statedir。userspace 模式不需要 root/TUN。
|
|
12
|
+
*/
|
|
13
|
+
export class TailscaleDaemon {
|
|
14
|
+
options;
|
|
15
|
+
child = null;
|
|
16
|
+
constructor(options) {
|
|
17
|
+
this.options = options;
|
|
18
|
+
}
|
|
19
|
+
socketPath() {
|
|
20
|
+
if (process.platform === "win32") {
|
|
21
|
+
const id = createHash("sha256").update(this.stateDir().toLowerCase()).digest("hex").slice(0, 24);
|
|
22
|
+
return `\\\\.\\pipe\\agentroam-tailscale-${id}`;
|
|
23
|
+
}
|
|
24
|
+
return resolve(this.stateDir(), "tailscaled.sock");
|
|
25
|
+
}
|
|
26
|
+
stateDir() {
|
|
27
|
+
return resolve(this.options.dataDir, "tailscale");
|
|
28
|
+
}
|
|
29
|
+
/** tailscale CLI 与 tailscaled 同目录、同名去 d(PATH 探测来源同样是成对相邻的)。 */
|
|
30
|
+
cliPath() {
|
|
31
|
+
return this.options.tailscaledPath.replace(/tailscaled(\.exe)?$/, "tailscale$1");
|
|
32
|
+
}
|
|
33
|
+
cliOptionsWith(tailscalePath) {
|
|
34
|
+
return {
|
|
35
|
+
tailscalePath,
|
|
36
|
+
socketPath: this.socketPath(),
|
|
37
|
+
timeoutMs: this.options.timeoutMs,
|
|
38
|
+
spawnImpl: this.options.spawnImpl,
|
|
39
|
+
signal: this.options.signal,
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
/** 用给定 tailscale CLI 探活;BackendState=Unknown 且无 100.x 视为未就绪。 */
|
|
43
|
+
async probeStatus(cliPath) {
|
|
44
|
+
try {
|
|
45
|
+
const status = await readTailscaleStatus(this.cliOptionsWith(cliPath));
|
|
46
|
+
if (["Unknown", "NoState", "Starting"].includes(status.backendState))
|
|
47
|
+
return null;
|
|
48
|
+
return status;
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
async ensureRunning(tailscalePath) {
|
|
55
|
+
const socketPath = this.socketPath();
|
|
56
|
+
const stateDir = this.stateDir();
|
|
57
|
+
await mkdir(stateDir, { recursive: true, mode: 0o700 });
|
|
58
|
+
if (process.platform !== "win32")
|
|
59
|
+
await chmod(stateDir, 0o700);
|
|
60
|
+
const existing = await this.probeStatus(tailscalePath);
|
|
61
|
+
if (existing)
|
|
62
|
+
return { socketPath, stateDir, reused: true, status: existing };
|
|
63
|
+
if (this.child)
|
|
64
|
+
await this.stopChild();
|
|
65
|
+
const log = this.options.onLog ?? (() => { });
|
|
66
|
+
log("Starting tailscaled (userspace)…");
|
|
67
|
+
const spawnImpl = this.options.spawnImpl ?? spawn;
|
|
68
|
+
let startupError;
|
|
69
|
+
const child = spawnImpl(this.options.tailscaledPath, [
|
|
70
|
+
"--tun=userspace-networking", "--port=0",
|
|
71
|
+
...(process.platform === "win32" ? ["--windows-mode=dev"] : []),
|
|
72
|
+
`--statedir=${stateDir}`,
|
|
73
|
+
`--socket=${socketPath}`,
|
|
74
|
+
], {
|
|
75
|
+
stdio: ["ignore", "ignore", "pipe"], windowsHide: true,
|
|
76
|
+
env: { ...process.env, AGENT_HEADSCALE_API_KEY: undefined },
|
|
77
|
+
});
|
|
78
|
+
this.child = child;
|
|
79
|
+
child.stderr?.on("data", (chunk) => log(String(chunk).trimEnd()));
|
|
80
|
+
child.once("error", error => { startupError = error; });
|
|
81
|
+
child.once("exit", () => { if (this.child === child)
|
|
82
|
+
this.child = null; });
|
|
83
|
+
const deadline = Date.now() + 15_000;
|
|
84
|
+
while (Date.now() < deadline) {
|
|
85
|
+
this.options.signal?.throwIfAborted();
|
|
86
|
+
if (startupError)
|
|
87
|
+
throw startupError;
|
|
88
|
+
if (this.child === null)
|
|
89
|
+
throw new Error("tailscaled exited during startup");
|
|
90
|
+
const status = await this.probeStatus(tailscalePath);
|
|
91
|
+
if (status)
|
|
92
|
+
return { socketPath, stateDir, reused: false, status };
|
|
93
|
+
await delay(300, undefined, { signal: this.options.signal });
|
|
94
|
+
}
|
|
95
|
+
await this.stopChild();
|
|
96
|
+
throw new Error("tailscaled did not become ready within 15s (check tailscaled availability and statedir permissions)");
|
|
97
|
+
}
|
|
98
|
+
async stop() {
|
|
99
|
+
await this.stopChild();
|
|
100
|
+
}
|
|
101
|
+
async stopChild() {
|
|
102
|
+
const child = this.child;
|
|
103
|
+
this.child = null;
|
|
104
|
+
if (!child?.pid || child.exitCode !== null || child.signalCode !== null)
|
|
105
|
+
return;
|
|
106
|
+
await new Promise((resolveExit) => {
|
|
107
|
+
const timer = setTimeout(() => { child.kill("SIGKILL"); resolveExit(null); }, 3_000);
|
|
108
|
+
child.once("exit", () => { clearTimeout(timer); resolveExit(null); });
|
|
109
|
+
child.kill("SIGTERM");
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { constants } from "node:fs";
|
|
3
|
+
import { access, chmod, copyFile, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
4
|
+
import { delimiter, resolve } from "node:path";
|
|
5
|
+
import { resolveBundledTailscale } from "./bundled-asset.js";
|
|
6
|
+
import { sha256File } from "../cloudflared/checksum.js";
|
|
7
|
+
/** 归档内固定两个二进制(tailscale CLI + tailscaled 守护进程),安装到 <dataDir>/bin。 */
|
|
8
|
+
export async function ensureTailscaleBinaries(target, dataDir, options = {}) {
|
|
9
|
+
const executableSuffix = target === "windows-amd64" ? ".exe" : "";
|
|
10
|
+
const binDir = resolve(dataDir, "bin");
|
|
11
|
+
const finalPaths = {
|
|
12
|
+
tailscale: resolve(binDir, `tailscale${executableSuffix}`),
|
|
13
|
+
tailscaled: resolve(binDir, `tailscaled${executableSuffix}`),
|
|
14
|
+
};
|
|
15
|
+
await mkdir(binDir, { recursive: true });
|
|
16
|
+
const resolveBundled = options.resolveBundled ?? resolveBundledTailscale;
|
|
17
|
+
const findSystem = options.findSystem ?? findSystemTailscale;
|
|
18
|
+
const failures = [];
|
|
19
|
+
try {
|
|
20
|
+
const bundled = await resolveBundled(target);
|
|
21
|
+
if (bundled) {
|
|
22
|
+
if (await cachedPair(finalPaths, bundled.sha256))
|
|
23
|
+
return finalPaths;
|
|
24
|
+
await installBundledTailscale(bundled, target, binDir, finalPaths);
|
|
25
|
+
return finalPaths;
|
|
26
|
+
}
|
|
27
|
+
failures.push(`platform package missing for ${target}`);
|
|
28
|
+
}
|
|
29
|
+
catch (error) {
|
|
30
|
+
failures.push(describeError(error));
|
|
31
|
+
}
|
|
32
|
+
const system = await findSystem(target);
|
|
33
|
+
if (system)
|
|
34
|
+
return system;
|
|
35
|
+
throw new Error(`tailscale binaries unavailable: ${failures.join("; ")}; install Tailscale (brew install tailscale) or build the platform package`);
|
|
36
|
+
}
|
|
37
|
+
/** macOS/Windows 的 GUI/服务进程 PATH 可能不含 Homebrew,显式探测常见前缀。 */
|
|
38
|
+
export async function findSystemTailscale(target = "darwin-arm64") {
|
|
39
|
+
const platform = target === "windows-amd64" ? "win32" : process.platform;
|
|
40
|
+
const suffix = platform === "win32" ? ".exe" : "";
|
|
41
|
+
const directories = new Set();
|
|
42
|
+
for (const value of (process.env.PATH ?? "").split(delimiter).filter(Boolean))
|
|
43
|
+
directories.add(value);
|
|
44
|
+
if (platform === "darwin")
|
|
45
|
+
directories.add("/opt/homebrew/bin");
|
|
46
|
+
if (platform !== "win32") {
|
|
47
|
+
directories.add("/usr/local/bin");
|
|
48
|
+
directories.add("/usr/bin");
|
|
49
|
+
}
|
|
50
|
+
for (const directory of directories) {
|
|
51
|
+
const pair = {
|
|
52
|
+
tailscale: resolve(directory, `tailscale${suffix}`),
|
|
53
|
+
tailscaled: resolve(directory, `tailscaled${suffix}`),
|
|
54
|
+
};
|
|
55
|
+
if (await bothExecutable(pair))
|
|
56
|
+
return pair;
|
|
57
|
+
}
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
async function bothExecutable(pair) {
|
|
61
|
+
for (const path of [pair.tailscale, pair.tailscaled]) {
|
|
62
|
+
try {
|
|
63
|
+
await access(path, constants.X_OK);
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return true;
|
|
70
|
+
}
|
|
71
|
+
async function cachedPair(paths, hash) {
|
|
72
|
+
for (const path of [paths.tailscale, paths.tailscaled]) {
|
|
73
|
+
const marker = `${path}.source.sha256`;
|
|
74
|
+
try {
|
|
75
|
+
if (!(await stat(path)).isFile())
|
|
76
|
+
return false;
|
|
77
|
+
if ((await readFile(marker, "utf8")).trim() !== hash)
|
|
78
|
+
return false;
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
return false;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return true;
|
|
85
|
+
}
|
|
86
|
+
async function installBundledTailscale(asset, target, binDir, finalPaths) {
|
|
87
|
+
const archiveInfo = await stat(asset.assetPath);
|
|
88
|
+
if (!archiveInfo.isFile() || archiveInfo.size !== asset.size)
|
|
89
|
+
throw new Error("bundled tailscale size mismatch");
|
|
90
|
+
if ((await sha256File(asset.assetPath)) !== asset.sha256)
|
|
91
|
+
throw new Error("bundled tailscale checksum mismatch");
|
|
92
|
+
const temporaryDir = resolve(binDir, `.tailscale-${process.pid}-${Date.now()}`);
|
|
93
|
+
await mkdir(temporaryDir, { recursive: true });
|
|
94
|
+
try {
|
|
95
|
+
await extractTgz(asset.assetPath, temporaryDir);
|
|
96
|
+
const entries = (await readdir(temporaryDir)).sort();
|
|
97
|
+
const expected = [...asset.entries].sort();
|
|
98
|
+
if (entries.length !== expected.length || !entries.every((entry, index) => entry === expected[index])) {
|
|
99
|
+
throw new Error(`unexpected bundled tailscale contents: ${entries.join(", ")}`);
|
|
100
|
+
}
|
|
101
|
+
for (const entry of asset.entries) {
|
|
102
|
+
const destination = /^tailscale(?:\.exe)?$/.test(entry) ? finalPaths.tailscale : finalPaths.tailscaled;
|
|
103
|
+
const extracted = resolve(temporaryDir, entry);
|
|
104
|
+
if (!(await stat(extracted)).isFile())
|
|
105
|
+
throw new Error(`bundled tailscale executable missing: ${entry}`);
|
|
106
|
+
if (target !== "windows-amd64")
|
|
107
|
+
await chmod(extracted, 0o755);
|
|
108
|
+
await copyFile(extracted, destination);
|
|
109
|
+
const markerTemp = `${destination}.source.sha256.${process.pid}.tmp`;
|
|
110
|
+
await writeFileAtomic(markerTemp, `${asset.sha256}\n`, `${destination}.source.sha256`);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
finally {
|
|
114
|
+
await rm(temporaryDir, { recursive: true, force: true });
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
async function writeFileAtomic(temporary, content, final) {
|
|
118
|
+
await writeFile(temporary, content);
|
|
119
|
+
await rename(temporary, final);
|
|
120
|
+
}
|
|
121
|
+
function describeError(error) {
|
|
122
|
+
const value = error;
|
|
123
|
+
return [value.cause?.code, value.message, value.cause?.message].filter(Boolean).join(": ") || String(error);
|
|
124
|
+
}
|
|
125
|
+
function extractTgz(archive, dir) {
|
|
126
|
+
return new Promise((resolvePromise, reject) => {
|
|
127
|
+
const child = spawn("tar", ["-xzf", archive, "-C", dir], { stdio: "ignore" });
|
|
128
|
+
child.once("exit", (code) => (code === 0 ? resolvePromise() : reject(new Error(`tar exited ${code}`))));
|
|
129
|
+
child.once("error", reject);
|
|
130
|
+
});
|
|
131
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { PLATFORM_DEPENDENCY_VERSIONS, requirePlatformPackages } from "../platform-packages.js";
|
|
2
|
+
/**
|
|
3
|
+
* tailscale 平台包(agentroam-tailscale-<target>)由
|
|
4
|
+
* scripts/build-tailscale-platform-package.mjs 在打包期从 tailscale 源码
|
|
5
|
+
* (pinned tag)构建:官方只为 Linux 发布裸 tgz,macOS/Windows 无官方裸二进制分发,
|
|
6
|
+
* 因此归档在打包期生成,运行期缺平台包时回落 PATH 探测(Homebrew / 官方安装)。
|
|
7
|
+
*/
|
|
8
|
+
export const TAILSCALE_PACKAGES = {
|
|
9
|
+
"darwin-arm64": requirePlatformPackages("darwin-arm64").tailscale,
|
|
10
|
+
"windows-amd64": requirePlatformPackages("windows-amd64").tailscale,
|
|
11
|
+
};
|
|
12
|
+
export function tailscalePackageVersion(target) {
|
|
13
|
+
const packageName = TAILSCALE_PACKAGES[target];
|
|
14
|
+
return packageName ? PLATFORM_DEPENDENCY_VERSIONS[packageName] : undefined;
|
|
15
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
export class TailscaleCommandError extends Error {
|
|
5
|
+
result;
|
|
6
|
+
constructor(message, result) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.result = result;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
export async function runTailscaleCommand(options, args) {
|
|
12
|
+
options.signal?.throwIfAborted();
|
|
13
|
+
const timeoutMs = options.timeoutMs ?? 30_000;
|
|
14
|
+
const spawnImpl = options.spawnImpl ?? spawn;
|
|
15
|
+
return await new Promise((resolveCommand, rejectCommand) => {
|
|
16
|
+
const child = spawnImpl(options.tailscalePath, ["--socket", options.socketPath, ...args], {
|
|
17
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
18
|
+
windowsHide: true,
|
|
19
|
+
signal: options.signal,
|
|
20
|
+
});
|
|
21
|
+
let stdout = "";
|
|
22
|
+
let stderr = "";
|
|
23
|
+
const timer = setTimeout(() => {
|
|
24
|
+
child.kill("SIGKILL");
|
|
25
|
+
rejectCommand(new TailscaleCommandError(`tailscale ${args[0]} timed out after ${timeoutMs}ms`, { stdout, stderr, code: -1 }));
|
|
26
|
+
}, timeoutMs);
|
|
27
|
+
child.stdout?.on("data", (chunk) => { stdout += String(chunk); });
|
|
28
|
+
child.stderr?.on("data", (chunk) => { stderr += String(chunk); });
|
|
29
|
+
child.once("error", (error) => { clearTimeout(timer); rejectCommand(error); });
|
|
30
|
+
child.once("close", (code) => {
|
|
31
|
+
clearTimeout(timer);
|
|
32
|
+
const result = { stdout, stderr, code: code ?? -1 };
|
|
33
|
+
if (code === 0)
|
|
34
|
+
resolveCommand(result);
|
|
35
|
+
else
|
|
36
|
+
rejectCommand(new TailscaleCommandError(`tailscale ${args[0]} exited ${code}: ${stderr.trim() || stdout.trim().slice(0, 400)}`, result));
|
|
37
|
+
});
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
/** `tailscale status --json` 在未登录时也可能退出 0,因此按 BackendState 判定而不是只看退出码。 */
|
|
41
|
+
export async function readTailscaleStatus(options) {
|
|
42
|
+
const result = await runTailscaleCommand({ ...options, timeoutMs: options.timeoutMs ?? 8_000 }, ["status", "--json"]);
|
|
43
|
+
let payload;
|
|
44
|
+
try {
|
|
45
|
+
payload = JSON.parse(result.stdout);
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
throw new TailscaleCommandError("tailscale status --json returned invalid JSON", result);
|
|
49
|
+
}
|
|
50
|
+
const tailscaleIPs = Array.isArray(payload.Self?.TailscaleIPs)
|
|
51
|
+
? payload.Self?.TailscaleIPs.filter((value) => typeof value === "string") ?? []
|
|
52
|
+
: [];
|
|
53
|
+
const dnsName = typeof payload.Self?.DNSName === "string" && payload.Self.DNSName
|
|
54
|
+
? payload.Self.DNSName.replace(/\.$/, "")
|
|
55
|
+
: null;
|
|
56
|
+
let controlPlaneUrl = null;
|
|
57
|
+
if (payload.BackendState === "Running") {
|
|
58
|
+
const prefs = await runTailscaleCommand(options, ["debug", "prefs"]);
|
|
59
|
+
const { ControlURL } = JSON.parse(prefs.stdout);
|
|
60
|
+
if (ControlURL)
|
|
61
|
+
controlPlaneUrl = new URL(ControlURL).origin;
|
|
62
|
+
}
|
|
63
|
+
return {
|
|
64
|
+
backendState: typeof payload.BackendState === "string" ? payload.BackendState : "Unknown",
|
|
65
|
+
tailscaleIPs,
|
|
66
|
+
dnsName,
|
|
67
|
+
hostname: typeof payload.Self?.HostName === "string" ? payload.Self.HostName : null,
|
|
68
|
+
controlPlaneUrl,
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
/** `tailscale up` 会阻塞到状态收敛;userspace 模式下首联一般数秒内完成。 */
|
|
72
|
+
export async function tailscaleUp(options, config) {
|
|
73
|
+
const directory = await mkdtemp(join(config.stateDir, ".auth-"));
|
|
74
|
+
const keyPath = join(directory, "key");
|
|
75
|
+
try {
|
|
76
|
+
await writeFile(keyPath, config.authKey, { mode: 0o600, flag: "wx" });
|
|
77
|
+
return await runTailscaleCommand({ ...options, timeoutMs: options.timeoutMs ?? 60_000 }, [
|
|
78
|
+
"up", `--login-server=${config.loginServer}`, `--auth-key=file:${keyPath}`,
|
|
79
|
+
`--hostname=${config.hostname}`, "--accept-dns=false", "--timeout=30s",
|
|
80
|
+
]);
|
|
81
|
+
}
|
|
82
|
+
catch (error) {
|
|
83
|
+
if (error instanceof TailscaleCommandError) {
|
|
84
|
+
throw new Error(error.message.replaceAll(config.authKey, "[redacted]"));
|
|
85
|
+
}
|
|
86
|
+
throw error;
|
|
87
|
+
}
|
|
88
|
+
finally {
|
|
89
|
+
await rm(directory, { recursive: true, force: true });
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
export async function tailscaleServe(options, localUrl) {
|
|
93
|
+
// --http=80:headscale 不签发 MagicDNS 节点证书,tailnet 内用 80 端口 HTTP 暴露网关。
|
|
94
|
+
return await runTailscaleCommand(options, ["serve", "--bg", "--http=80", localUrl]);
|
|
95
|
+
}
|
|
96
|
+
export async function tailscaleServeReset(options) {
|
|
97
|
+
return await runTailscaleCommand(options, ["serve", "reset"]);
|
|
98
|
+
}
|
|
99
|
+
export async function tailscaleLogout(options) {
|
|
100
|
+
return await runTailscaleCommand({ ...options, timeoutMs: options.timeoutMs ?? 20_000 }, ["logout"]);
|
|
101
|
+
}
|