agentroam 0.2.0-preview.78 → 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/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 +8 -6
|
@@ -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
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { ensureCloudflared } from "../cloudflared/installer.js";
|
|
2
2
|
import { CloudflareTunnelProvider } from "./cloudflare-provider.js";
|
|
3
3
|
import { CustomCommandTunnelProvider } from "./custom-command-provider.js";
|
|
4
|
+
import { readDefaultRelayUrl, SelfHostedTunnelProvider } from "./self-hosted-provider.js";
|
|
4
5
|
import { PinggyTunnelProvider } from "./pinggy-provider.js";
|
|
5
6
|
import { waitForPublicReadiness } from "./public-readiness.js";
|
|
6
7
|
import { withAbortSignal } from "../abort.js";
|
|
@@ -9,52 +10,57 @@ export async function selectRelay(options) {
|
|
|
9
10
|
options.signal.throwIfAborted();
|
|
10
11
|
if (options.cli.localOnly)
|
|
11
12
|
return { tunnel: null, publicUrl: options.lanUrl, provider: "lan", failures: [] };
|
|
12
|
-
const
|
|
13
|
+
const { relay, relayUrl: configuredUrl } = options.cli;
|
|
14
|
+
const relayUrl = configuredUrl ?? (relay === "auto" || relay === "self-hosted" ? readDefaultRelayUrl() : null);
|
|
15
|
+
const providerName = relay === "auto" ? (relayUrl ? "self-hosted" : "cloudflare") : relay;
|
|
13
16
|
const failures = [];
|
|
14
17
|
const readiness = options.readiness ?? waitForPublicReadiness;
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
18
|
+
options.onStage?.("connecting");
|
|
19
|
+
options.onAttempt?.(providerName);
|
|
20
|
+
const attempt = { tunnel: null };
|
|
21
|
+
const deadline = new AbortController();
|
|
22
|
+
const timeoutMs = options.timeoutMs ?? RELAY_START_TIMEOUT_MS;
|
|
23
|
+
const timer = setTimeout(() => deadline.abort(new Error(`relay connection timed out after ${timeoutMs}ms`)), timeoutMs);
|
|
24
|
+
const signal = AbortSignal.any([options.signal, deadline.signal]);
|
|
25
|
+
try {
|
|
26
|
+
return await withAbortSignal(async () => {
|
|
27
|
+
const provider = await createProvider(providerName, options, relayUrl);
|
|
28
|
+
signal.throwIfAborted();
|
|
29
|
+
const handle = await provider.start({ localUrl: options.localUrl, signal, log: options.log });
|
|
30
|
+
if (signal.aborted) {
|
|
31
|
+
void handle.close().catch(() => { });
|
|
26
32
|
signal.throwIfAborted();
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
options.onFailure?.(providerName, message);
|
|
47
|
-
}
|
|
48
|
-
finally {
|
|
49
|
-
clearTimeout(timer);
|
|
50
|
-
}
|
|
33
|
+
}
|
|
34
|
+
attempt.tunnel = handle;
|
|
35
|
+
options.onStage?.("checking");
|
|
36
|
+
await readiness(handle.publicUrl, { signal });
|
|
37
|
+
signal.throwIfAborted();
|
|
38
|
+
return { tunnel: handle, publicUrl: handle.publicUrl, provider: providerName, failures };
|
|
39
|
+
}, signal);
|
|
40
|
+
}
|
|
41
|
+
catch (error) {
|
|
42
|
+
deadline.abort(error);
|
|
43
|
+
if (attempt.tunnel)
|
|
44
|
+
await withAbortSignal(() => attempt.tunnel.close(), AbortSignal.timeout(3_000)).catch(() => { });
|
|
45
|
+
options.signal.throwIfAborted();
|
|
46
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
47
|
+
failures.push({ provider: providerName, message });
|
|
48
|
+
options.onFailure?.(providerName, message);
|
|
49
|
+
}
|
|
50
|
+
finally {
|
|
51
|
+
clearTimeout(timer);
|
|
51
52
|
}
|
|
52
53
|
return { tunnel: null, publicUrl: options.lanUrl, provider: "lan", failures };
|
|
53
54
|
}
|
|
54
|
-
async function createProvider(name, options) {
|
|
55
|
+
async function createProvider(name, options, relayUrl) {
|
|
55
56
|
const override = options.providerFactories?.[name];
|
|
56
57
|
if (override)
|
|
57
58
|
return await override();
|
|
59
|
+
if (name === "self-hosted") {
|
|
60
|
+
if (!relayUrl)
|
|
61
|
+
throw new Error("自建 HTTPS 入口地址未配置");
|
|
62
|
+
return new SelfHostedTunnelProvider(relayUrl, options.cli.dataDir);
|
|
63
|
+
}
|
|
58
64
|
if (name === "cloudflare") {
|
|
59
65
|
const executable = await ensureCloudflared(options.target, options.cli.dataDir);
|
|
60
66
|
return new CloudflareTunnelProvider(executable);
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
import { link, readFile, unlink } from "node:fs/promises";
|
|
4
|
+
import { connect } from "node:net";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { WebSocket, createWebSocketStream } from "ws";
|
|
7
|
+
import { writePrivateText } from "../service/service-files.js";
|
|
8
|
+
const tokenPattern = /^[A-Za-z0-9_-]{43}$/;
|
|
9
|
+
export function relayOrigin(value) {
|
|
10
|
+
const url = new URL(value);
|
|
11
|
+
if (url.protocol !== "https:" || url.port || url.username || url.password || url.pathname !== "/" ||
|
|
12
|
+
url.search || url.hash || !/^(?:[a-z0-9-]+\.)+[a-z][a-z0-9-]*$/.test(url.hostname)) {
|
|
13
|
+
throw new Error("自建 HTTPS 入口需要一个 HTTPS 域名");
|
|
14
|
+
}
|
|
15
|
+
return url;
|
|
16
|
+
}
|
|
17
|
+
export function readDefaultRelayUrl() {
|
|
18
|
+
const configured = process.env.AGENTROAM_HTTPS_RELAY_URL?.trim();
|
|
19
|
+
if (configured)
|
|
20
|
+
return configured;
|
|
21
|
+
const path = new URL("../self-hosted-relay.json", import.meta.url);
|
|
22
|
+
try {
|
|
23
|
+
const url = JSON.parse(readFileSync(path, "utf8")).url;
|
|
24
|
+
return typeof url === "string" ? url : null;
|
|
25
|
+
}
|
|
26
|
+
catch (error) {
|
|
27
|
+
if (error.code !== "ENOENT")
|
|
28
|
+
throw error;
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
async function installationToken(dataDir) {
|
|
33
|
+
const path = join(dataDir, "relay", "identity");
|
|
34
|
+
const existing = await readToken(path);
|
|
35
|
+
if (existing)
|
|
36
|
+
return existing;
|
|
37
|
+
const temporary = `${path}.${randomBytes(8).toString("hex")}.pending`;
|
|
38
|
+
await writePrivateText(temporary, randomBytes(32).toString("base64url"));
|
|
39
|
+
try {
|
|
40
|
+
await link(temporary, path);
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
if (error.code !== "EEXIST")
|
|
44
|
+
throw error;
|
|
45
|
+
}
|
|
46
|
+
finally {
|
|
47
|
+
await unlink(temporary);
|
|
48
|
+
}
|
|
49
|
+
const token = await readToken(path);
|
|
50
|
+
if (!token)
|
|
51
|
+
throw new Error("自建 HTTPS 入口的本机身份未能保存");
|
|
52
|
+
return token;
|
|
53
|
+
}
|
|
54
|
+
async function readToken(path) {
|
|
55
|
+
const token = await readFile(path, "utf8").catch((error) => {
|
|
56
|
+
if (error.code === "ENOENT")
|
|
57
|
+
return null;
|
|
58
|
+
throw error;
|
|
59
|
+
});
|
|
60
|
+
if (token !== null && !tokenPattern.test(token))
|
|
61
|
+
throw new Error("自建 HTTPS 入口的本机身份文件无效");
|
|
62
|
+
return token;
|
|
63
|
+
}
|
|
64
|
+
export class SelfHostedTunnelProvider {
|
|
65
|
+
url;
|
|
66
|
+
dataDir;
|
|
67
|
+
dial;
|
|
68
|
+
constructor(url, dataDir, dial = (url, options) => new WebSocket(url, options)) {
|
|
69
|
+
this.url = url;
|
|
70
|
+
this.dataDir = dataDir;
|
|
71
|
+
this.dial = dial;
|
|
72
|
+
}
|
|
73
|
+
async start({ localUrl, signal }) {
|
|
74
|
+
const root = relayOrigin(this.url);
|
|
75
|
+
const token = await installationToken(this.dataDir);
|
|
76
|
+
const local = new URL(localUrl);
|
|
77
|
+
if (local.protocol !== "http:" || local.hostname !== "127.0.0.1" || !local.port) {
|
|
78
|
+
throw new Error("自建 HTTPS 入口只能转发本机 AgentRoam 服务");
|
|
79
|
+
}
|
|
80
|
+
const name = createHash("sha256").update(token).digest("hex").slice(0, 32);
|
|
81
|
+
const publicUrl = `https://d-${name}.${root.host}`;
|
|
82
|
+
const options = { headers: { authorization: `Bearer ${token}` }, handshakeTimeout: 8_000, maxPayload: 1024 * 1024, perMessageDeflate: false };
|
|
83
|
+
const websocket = (path) => this.dial(new URL(`wss://${root.host}${path}`), options);
|
|
84
|
+
signal.throwIfAborted();
|
|
85
|
+
const control = websocket("/v1/connect");
|
|
86
|
+
const streams = new Set();
|
|
87
|
+
const close = () => {
|
|
88
|
+
control.terminate();
|
|
89
|
+
for (const socket of streams)
|
|
90
|
+
socket.terminate();
|
|
91
|
+
};
|
|
92
|
+
const exited = new Promise((resolve) => {
|
|
93
|
+
control.once("close", code => {
|
|
94
|
+
signal.removeEventListener("abort", close);
|
|
95
|
+
for (const socket of streams)
|
|
96
|
+
socket.terminate();
|
|
97
|
+
resolve({ code, signal: null });
|
|
98
|
+
});
|
|
99
|
+
});
|
|
100
|
+
signal.addEventListener("abort", close, { once: true });
|
|
101
|
+
try {
|
|
102
|
+
await new Promise((resolve, reject) => {
|
|
103
|
+
let ready = false;
|
|
104
|
+
control.on("error", reject);
|
|
105
|
+
void exited.then(() => reject(new Error("自建 HTTPS 入口连接已断开")));
|
|
106
|
+
control.on("message", chunk => {
|
|
107
|
+
try {
|
|
108
|
+
const message = JSON.parse(String(chunk));
|
|
109
|
+
if (!ready && message?.type === "ready" && message.publicUrl === publicUrl) {
|
|
110
|
+
ready = true;
|
|
111
|
+
resolve();
|
|
112
|
+
}
|
|
113
|
+
else if (ready && message?.type === "stream" && /^[a-f0-9]{32}$/.test(message.id) && streams.size < 64) {
|
|
114
|
+
const socket = websocket(`/v1/streams/${message.id}`);
|
|
115
|
+
streams.add(socket);
|
|
116
|
+
socket.once("close", () => streams.delete(socket));
|
|
117
|
+
connectToLoopback(socket, Number(local.port));
|
|
118
|
+
}
|
|
119
|
+
else {
|
|
120
|
+
close();
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
reject(error);
|
|
125
|
+
close();
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
});
|
|
129
|
+
signal.throwIfAborted();
|
|
130
|
+
return { publicUrl, exited, close: async () => { close(); await exited; } };
|
|
131
|
+
}
|
|
132
|
+
catch (error) {
|
|
133
|
+
close();
|
|
134
|
+
throw error;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
function connectToLoopback(socket, port) {
|
|
139
|
+
const stream = createWebSocketStream(socket);
|
|
140
|
+
// The remote can send immediately after the WebSocket handshake. Buffer on
|
|
141
|
+
// the stream until the local service accepts the socket.
|
|
142
|
+
const local = connect({ host: "127.0.0.1", port });
|
|
143
|
+
stream.on("error", () => local.destroy());
|
|
144
|
+
local.on("error", () => stream.destroy());
|
|
145
|
+
stream.once("close", () => local.destroy());
|
|
146
|
+
local.once("connect", () => stream.pipe(local).pipe(stream));
|
|
147
|
+
}
|