@teamclaws/teamclaw 2026.8.0 → 2026.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/api.js +1 -0
  2. package/dist/index.js +325 -0
  3. package/dist/src/config.js +381 -0
  4. package/dist/src/controller/controller-capacity.js +14 -0
  5. package/dist/src/controller/controller-service.js +393 -0
  6. package/dist/src/controller/controller-tools.js +582 -0
  7. package/dist/src/controller/delivery-report.js +458 -0
  8. package/dist/src/controller/github-auth.js +564 -0
  9. package/dist/src/controller/http-server.js +6032 -0
  10. package/dist/src/controller/kickoff-orchestrator.js +220 -0
  11. package/dist/src/controller/managed-gateway-process.js +286 -0
  12. package/dist/src/controller/message-router.js +38 -0
  13. package/dist/src/controller/orchestration-manifest.js +173 -0
  14. package/dist/src/controller/preview-manager.js +586 -0
  15. package/dist/src/controller/prompt-injector.js +187 -0
  16. package/dist/src/controller/role-inference.js +35 -0
  17. package/dist/src/controller/task-router.js +67 -0
  18. package/dist/src/controller/tunnel-manager.js +548 -0
  19. package/dist/src/controller/websocket.js +42 -0
  20. package/dist/src/controller/worker-provisioning.js +1648 -0
  21. package/dist/src/discovery.js +86 -0
  22. package/dist/src/git-collaboration.js +694 -0
  23. package/dist/src/identity.js +131 -0
  24. package/dist/src/install-defaults.js +1 -0
  25. package/dist/src/interaction-contracts.js +531 -0
  26. package/dist/src/networking.js +91 -0
  27. package/dist/src/openclaw-workspace.js +903 -0
  28. package/dist/src/prompt-policy.js +373 -0
  29. package/dist/src/protocol.js +58 -0
  30. package/dist/src/roles.js +349 -0
  31. package/dist/src/state.js +183 -0
  32. package/dist/src/task-executor.js +1033 -0
  33. package/dist/src/teamauto/github-client.js +192 -0
  34. package/dist/src/teamauto/norms.js +85 -0
  35. package/dist/src/teamauto/repo-sync.js +201 -0
  36. package/dist/src/teamauto/scanner.js +179 -0
  37. package/dist/src/teamauto/schedule.js +123 -0
  38. package/dist/src/teamauto/scheduler.js +688 -0
  39. package/dist/src/teamauto/store.js +133 -0
  40. package/dist/src/types.js +243 -0
  41. package/dist/src/ui/app.js +4292 -0
  42. package/dist/src/ui/assets/teamclaw-app-icon.png +0 -0
  43. package/dist/src/ui/github-login.html +296 -0
  44. package/dist/src/ui/index.html +414 -0
  45. package/dist/src/ui/style.css +2611 -0
  46. package/dist/src/worker/http-handler.js +146 -0
  47. package/dist/src/worker/message-queue.js +24 -0
  48. package/dist/src/worker/prompt-injector.js +42 -0
  49. package/dist/src/worker/skill-installer.js +253 -0
  50. package/dist/src/worker/tools.js +541 -0
  51. package/dist/src/worker/worker-service.js +234 -0
  52. package/dist/src/workspace-browser.js +269 -0
  53. package/openclaw.plugin.json +1 -1
  54. package/package.json +1 -1
@@ -0,0 +1,548 @@
1
+ import { execFileSync, spawn } from "node:child_process";
2
+ import { createHash, randomBytes } from "node:crypto";
3
+ import fs from "node:fs";
4
+ import https from "node:https";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ const TUNNEL_API_HOST = "apps.teamclaw.dev";
8
+ async function tunnelFetch(pathq, method, body) {
9
+ const ip = await new Promise((resolve, reject) => {
10
+ const r = https.request({ host: "1.1.1.1", path: `/dns-query?name=${TUNNEL_API_HOST}&type=A`, method: "GET", headers: { accept: "application/dns-json" }, servername: "cloudflare-dns.com" }, (res) => {
11
+ let d = "";
12
+ res.on("data", (c) => (d += c));
13
+ res.on("end", () => {
14
+ try {
15
+ const rec = (JSON.parse(d).Answer || []).map((x) => x.data).find((x) => /^\d+\./.test(x));
16
+ rec ? resolve(rec) : reject(new Error("DoH no A record"));
17
+ }
18
+ catch (e) {
19
+ reject(e);
20
+ }
21
+ });
22
+ });
23
+ r.on("error", reject);
24
+ r.end();
25
+ });
26
+ return new Promise((resolve, reject) => {
27
+ const payload = body === undefined ? null : JSON.stringify(body);
28
+ const req = https.request({ host: ip, servername: TUNNEL_API_HOST, path: `/api${pathq}`, method, headers: { host: TUNNEL_API_HOST, "Content-Type": "application/json", ...(payload ? { "Content-Length": Buffer.byteLength(payload) } : {}) } }, (res) => {
29
+ let d = "";
30
+ res.on("data", (c) => (d += c));
31
+ res.on("end", () => { try {
32
+ resolve({ status: res.statusCode ?? 0, json: d ? JSON.parse(d) : {} });
33
+ }
34
+ catch {
35
+ resolve({ status: res.statusCode ?? 0, json: {} });
36
+ } });
37
+ });
38
+ req.on("error", reject);
39
+ if (payload)
40
+ req.write(payload);
41
+ req.end();
42
+ });
43
+ }
44
+ /**
45
+ * Internet tunnel sharing for the local web UI.
46
+ *
47
+ * Flow: the controller asks the TeamClaw tunnel server (a Cloudflare Worker
48
+ * at apps.teamclaw.dev/api) to provision a per-user Cloudflare Tunnel, then
49
+ * runs `cloudflared` locally with the returned connector token. Visitors hit
50
+ * https://<github_user>.apps.teamclaw.dev and must enter the gate token that
51
+ * the local web UI displays (enforced by the controller's gate middleware).
52
+ */
53
+ export const TUNNEL_SERVER_URL = "https://apps.teamclaw.dev/api";
54
+ const TUNNEL_HOST_SUFFIX = ".teamclaw.dev";
55
+ const GATE_COOKIE = "tc_tunnel_gate";
56
+ /** Env var that injects a user-owned Cloudflare connector token. When set,
57
+ * the UI skips the token input and offers direct one-click start. */
58
+ export const SELF_HOSTED_TOKEN_ENV = "TEAMCLAW_TUNNEL_TOKEN";
59
+ export function selfHostedTokenFromEnv() {
60
+ const v = process.env[SELF_HOSTED_TOKEN_ENV]?.trim();
61
+ return v ? v : null;
62
+ }
63
+ const CLOUDFLARED_CANDIDATES = [
64
+ "/opt/homebrew/bin/cloudflared",
65
+ "/usr/local/bin/cloudflared",
66
+ "/usr/bin/cloudflared",
67
+ ];
68
+ function cloudflaredInstallTarget() {
69
+ // Keep in sync with installCloudflared(): the one-click install drops the
70
+ // binary at $HOME/.local/bin/cloudflared (no sudo needed, non-root friendly
71
+ // in containers where HOME is writable but /usr/local/bin is not).
72
+ const home = process.env.HOME ?? "/tmp";
73
+ return path.join(home, ".local", "bin", "cloudflared");
74
+ }
75
+ // curl-less download fallback (distroless images): plain https.get with
76
+ // redirect following. GitHub release URLs 302 to objects.githubusercontent.com.
77
+ function nativeDownload(url, dest, redirects = 0) {
78
+ return new Promise((resolve, reject) => {
79
+ if (redirects > 5)
80
+ return reject(new Error("too many redirects"));
81
+ const req = https.get(url, (res) => {
82
+ if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
83
+ res.resume();
84
+ nativeDownload(res.headers.location, dest, redirects + 1).then(resolve, reject);
85
+ return;
86
+ }
87
+ if (res.statusCode !== 200) {
88
+ res.resume();
89
+ reject(new Error("HTTP " + res.statusCode));
90
+ return;
91
+ }
92
+ const file = fs.createWriteStream(dest);
93
+ res.pipe(file);
94
+ file.on("finish", () => file.close((err) => (err ? reject(err) : resolve())));
95
+ file.on("error", reject);
96
+ });
97
+ req.on("error", reject);
98
+ });
99
+ }
100
+ function tunnelRuntimeHome() {
101
+ try {
102
+ const dir = path.join(os.tmpdir(), "teamclaw-cloudflared-home");
103
+ fs.mkdirSync(dir, { recursive: true });
104
+ return dir;
105
+ }
106
+ catch {
107
+ return process.env.HOME ?? "/tmp";
108
+ }
109
+ }
110
+ function tunnelStatePath() {
111
+ return path.join(tunnelRuntimeHome(), "tunnel-state.json");
112
+ }
113
+ function readTunnelState() {
114
+ try {
115
+ const raw = JSON.parse(fs.readFileSync(tunnelStatePath(), "utf8"));
116
+ return raw && raw.tunnelId && raw.connectorToken ? raw : null;
117
+ }
118
+ catch {
119
+ return null;
120
+ }
121
+ }
122
+ function writeTunnelState(st) {
123
+ try {
124
+ fs.writeFileSync(tunnelStatePath(), JSON.stringify(st), { mode: 0o600 });
125
+ }
126
+ catch { /* best effort */ }
127
+ }
128
+ function clearTunnelState() {
129
+ try {
130
+ fs.rmSync(tunnelStatePath(), { force: true });
131
+ }
132
+ catch { /* best effort */ }
133
+ }
134
+ // pid-reuse-safe liveness: only treat the pid as OUR orphan when the binary
135
+ // still matches cloudflared.
136
+ function connectorPidIsCloudflared(pid) {
137
+ try {
138
+ const out = execFileSync("ps", ["-p", String(pid), "-o", "comm="], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
139
+ return out.includes("cloudflared");
140
+ }
141
+ catch {
142
+ return false;
143
+ }
144
+ }
145
+ function findCloudflared() {
146
+ // The install target first: installCloudflared() puts the binary in
147
+ // $HOME/.local/bin, which is on PATH in stock images (Debian node images
148
+ // prepend it) but must be found even when PATH is minimal (K8s pods).
149
+ const candidates = [cloudflaredInstallTarget(), ...CLOUDFLARED_CANDIDATES];
150
+ // Real PATH scan. (fs.existsSync("cloudflared") checks CWD, not PATH -
151
+ // the old behavior missed every PATH-resolvable install.)
152
+ const pathDirs = (process.env.PATH ?? "").split(path.delimiter).filter(Boolean);
153
+ for (const dir of pathDirs)
154
+ candidates.push(path.join(dir, "cloudflared"));
155
+ for (const bin of candidates) {
156
+ try {
157
+ if (fs.existsSync(bin) && fs.accessSync(bin, fs.constants.X_OK) === undefined) {
158
+ return bin;
159
+ }
160
+ }
161
+ catch {
162
+ /* try next */
163
+ }
164
+ }
165
+ return null;
166
+ }
167
+ function gateCookieValue(gateToken, tunnelId) {
168
+ return createHash("sha256").update(`${gateToken}:${tunnelId}`).digest("hex").slice(0, 32);
169
+ }
170
+ export function createTunnelManager(deps) {
171
+ const { logger } = deps;
172
+ let child = null;
173
+ let handle = null;
174
+ let lastError = null;
175
+ // True while stop()/a restart path intentionally kills the connector; the
176
+ // cloudflared exit handler uses this to distinguish planned teardown from
177
+ // an unexpected crash (which must clear the active state so /tunnel/status
178
+ // never reports a dead tunnel as live).
179
+ let userStopping = false;
180
+ let startOp = { running: false, phase: "idle", detail: null };
181
+ let installState = { running: false, phase: "idle", percent: null, detail: null };
182
+ function isTunnelRequest(hostHeader) {
183
+ return Boolean(hostHeader && hostHeader.toLowerCase().endsWith(TUNNEL_HOST_SUFFIX));
184
+ }
185
+ function gateAllows(req) {
186
+ if (!handle)
187
+ return false;
188
+ const cookie = String(req.headers.cookie ?? "");
189
+ const match = cookie.match(new RegExp(`${GATE_COOKIE}=([0-9a-f]+)`));
190
+ return Boolean(match && match[1] === gateCookieValue(handle.gateToken, handle.tunnelId));
191
+ }
192
+ function launchStart(githubUser) {
193
+ if (startOp.running)
194
+ return { running: true, phase: startOp.phase };
195
+ startOp = { running: true, phase: "creating-tunnel", detail: null };
196
+ void (async () => {
197
+ try {
198
+ const h = await start(githubUser);
199
+ startOp = { running: false, phase: "done", detail: h.hostname };
200
+ }
201
+ catch (e) {
202
+ startOp = { running: false, phase: "error", detail: e instanceof Error ? e.message : String(e) };
203
+ }
204
+ })();
205
+ return { running: true, phase: startOp.phase };
206
+ }
207
+ async function start(githubUser) {
208
+ if (handle && child)
209
+ return handle;
210
+ const bin = findCloudflared();
211
+ if (!bin)
212
+ throw new Error("cloudflared not found (brew install cloudflared)");
213
+ const gateToken = randomBytes(6).toString("base64url").replace(/[-_]/g, "").slice(0, 8).toUpperCase();
214
+ const res = await tunnelFetch("/tunnels", "POST", { github_user: githubUser, local_port: deps.localPort });
215
+ const body = res.json;
216
+ if (res.status !== 201 || !body.tunnel_id || !body.connector_token || !body.hostname) {
217
+ throw new Error(body.error ?? `tunnel server responded ${res.status}`);
218
+ }
219
+ startOp = { running: true, phase: "starting-connector", detail: body.hostname };
220
+ stopConnector();
221
+ child = spawnConnector(bin, body.connector_token);
222
+ handle = { tunnelId: body.tunnel_id, hostname: body.hostname, gateToken, deleteToken: body.delete_token ?? "" };
223
+ writeTunnelState({ tunnelId: body.tunnel_id, hostname: body.hostname, gateToken, deleteToken: body.delete_token ?? "", connectorToken: body.connector_token, pid: child.pid ?? null, savedAt: Date.now() });
224
+ lastError = null;
225
+ logger.info(`TeamClaw tunnel: serving https://${body.hostname}`);
226
+ return handle;
227
+ }
228
+ /** Start a user-owned Cloudflare tunnel from a connector token (Zero Trust
229
+ * dashboard -> Tunnels -> <tunnel> -> copy token). The public hostname lives
230
+ * in the user's own CF zone, so it does NOT pass the .teamclaw.dev gate -
231
+ * protect it with Cloudflare Access if needed. Returns immediately; poll
232
+ * status() for connectorRunning. */
233
+ function startSelfHosted(rawToken) {
234
+ const token = rawToken.trim();
235
+ if (!token)
236
+ return { launched: false, error: "empty connector token" };
237
+ if (token.length < 40 || !/^[A-Za-z0-9_\-=]+$/.test(token)) {
238
+ return { launched: false, error: "not a Cloudflare connector token (expected a long base64url string from the Zero Trust dashboard)" };
239
+ }
240
+ if (handle && child)
241
+ return { launched: true, error: null };
242
+ const bin = findCloudflared();
243
+ if (!bin)
244
+ return { launched: false, error: "cloudflared not found (brew install cloudflared)" };
245
+ startOp = { running: true, phase: "starting-connector", detail: "self-hosted tunnel" };
246
+ stopConnector();
247
+ child = spawnConnector(bin, token);
248
+ handle = { tunnelId: "self-hosted", hostname: "", gateToken: "", deleteToken: "" };
249
+ writeTunnelState({ tunnelId: "self-hosted", hostname: "", gateToken: "", deleteToken: "", connectorToken: token, pid: child.pid ?? null, savedAt: Date.now() });
250
+ startOp = { running: false, phase: "done", detail: "self-hosted tunnel" };
251
+ lastError = null;
252
+ logger.info("TeamClaw tunnel: self-hosted Cloudflare tunnel connector started");
253
+ return { launched: true, error: null };
254
+ }
255
+ /** Anonymous one-off tunnel: `cloudflared tunnel --url`, no Cloudflare
256
+ * account, no token, no platform server. Cloudflare assigns a random
257
+ * trycloudflare.com URL (printed on stderr) which dies with the process -
258
+ * it is NOT recovered on restart and must not be treated as stable. No
259
+ * TeamClaw gate: anyone with the URL can reach the dashboard. */
260
+ function startQuick() {
261
+ if (handle && child)
262
+ return { launched: true, error: null };
263
+ const bin = findCloudflared();
264
+ if (!bin)
265
+ return { launched: false, error: "cloudflared not found (brew install cloudflared)" };
266
+ startOp = { running: true, phase: "starting-connector", detail: "quick tunnel" };
267
+ stopConnector();
268
+ const proc = spawn(bin, ["tunnel", "--no-autoupdate", "--url", "http://127.0.0.1:" + deps.localPort], {
269
+ stdio: ["ignore", "ignore", "pipe"],
270
+ detached: false,
271
+ env: { ...process.env, HOME: tunnelRuntimeHome() },
272
+ });
273
+ child = proc;
274
+ handle = { tunnelId: "quick", hostname: "", gateToken: "", deleteToken: "" };
275
+ lastError = null;
276
+ // The trycloudflare.com URL appears on stderr once the edge assigns it.
277
+ let announced = false;
278
+ const urlRe = /https:\/\/([a-z0-9-]+\.trycloudflare\.com)/i;
279
+ const timer = setTimeout(() => {
280
+ if (!announced) {
281
+ lastError = "quick tunnel did not announce its URL within 20s";
282
+ startOp = { running: false, phase: "error", detail: lastError };
283
+ }
284
+ }, 20000);
285
+ proc.stderr?.on("data", (c) => {
286
+ const m = c.toString().match(urlRe);
287
+ if (m && !announced) {
288
+ announced = true;
289
+ clearTimeout(timer);
290
+ if (handle)
291
+ handle.hostname = m[1];
292
+ startOp = { running: false, phase: "done", detail: m[1] };
293
+ logger.info(`TeamClaw tunnel: quick tunnel live at https://${m[1]}`);
294
+ }
295
+ try {
296
+ fs.appendFileSync(path.join(tunnelRuntimeHome(), "cloudflared.log"), c);
297
+ }
298
+ catch { /* best effort */ }
299
+ });
300
+ // Quick tunnels are one-off: no persistent state, no recovery - but the
301
+ // connector-exit contract still applies: a dead connector must clear the
302
+ // active state so status() never reports a dead tunnel as live.
303
+ proc.on("exit", (code) => {
304
+ clearTimeout(timer);
305
+ logger.warn(`TeamClaw tunnel: cloudflared exited (code ${code})`);
306
+ if (child !== proc)
307
+ return;
308
+ child = null;
309
+ if (!userStopping && handle) {
310
+ handle = null;
311
+ lastError = `tunnel connector exited unexpectedly (code ${code ?? "null"})`;
312
+ startOp = { running: false, phase: "error", detail: lastError };
313
+ clearTunnelState();
314
+ logger.warn("TeamClaw tunnel: state cleared after unexpected exit (quick)");
315
+ }
316
+ });
317
+ return { launched: true, error: null };
318
+ }
319
+ function spawnConnector(bin, connectorToken) {
320
+ const proc = spawn(bin, ["tunnel", "--no-autoupdate", "--protocol", "http2", "run", "--token", connectorToken], {
321
+ stdio: ["ignore", "ignore", "pipe"],
322
+ detached: false,
323
+ // Isolate from ~/.cloudflared/cert.pem (a local origin-cert would
324
+ // override the remotely-managed token config) and from QUIC-blocking
325
+ // networks (http2 rides regular TCP 443).
326
+ env: { ...process.env, HOME: tunnelRuntimeHome() },
327
+ });
328
+ proc.on("exit", (code) => {
329
+ logger.warn(`TeamClaw tunnel: cloudflared exited (code ${code})`);
330
+ if (child !== proc)
331
+ return;
332
+ child = null;
333
+ // Unexpected exit (crash, network loss, cloudflared auto-kill): tear
334
+ // the logical state down too, otherwise status() keeps reporting
335
+ // active=true and the UI shows a dead tunnel as live forever.
336
+ if (!userStopping && handle) {
337
+ const gone = handle;
338
+ handle = null;
339
+ lastError = `tunnel connector exited unexpectedly (code ${code ?? "null"})`;
340
+ startOp = { running: false, phase: "error", detail: lastError };
341
+ if (gone.tunnelId !== "self-hosted" && gone.tunnelId !== "quick") {
342
+ void tunnelFetch(`/tunnels/${gone.tunnelId}?user=${encodeURIComponent(gone.hostname.split(".")[0].replace(/^team-/, ""))}&token=${encodeURIComponent(gone.deleteToken)}`, "DELETE").catch(() => undefined);
343
+ }
344
+ clearTunnelState();
345
+ logger.warn(`TeamClaw tunnel: state cleared after unexpected exit (${gone.tunnelId})`);
346
+ }
347
+ });
348
+ // cloudflared logs (stderr) land in a single file for diagnosis.
349
+ // (stdout is "ignore" in stdio above, so there is nothing to pipe.)
350
+ const logPath = path.join(tunnelRuntimeHome(), "cloudflared.log");
351
+ proc.stderr?.pipe(fs.createWriteStream(logPath, { flags: "a" }));
352
+ return proc;
353
+ }
354
+ function stopConnector() {
355
+ if (child) {
356
+ child.kill("SIGTERM");
357
+ child = null;
358
+ }
359
+ }
360
+ async function stop() {
361
+ userStopping = true;
362
+ stopConnector();
363
+ if (handle) {
364
+ const gone = handle;
365
+ handle = null;
366
+ // Self-hosted tunnels live in the user's CF account - nothing to
367
+ // delete server-side; the connector stop is the whole teardown.
368
+ if (gone.tunnelId !== "self-hosted" && gone.tunnelId !== "quick") {
369
+ await tunnelFetch(`/tunnels/${gone.tunnelId}?user=${encodeURIComponent(gone.hostname.split(".")[0].replace(/^team-/, ""))}&token=${encodeURIComponent(gone.deleteToken)}`, "DELETE").catch(() => undefined);
370
+ }
371
+ clearTunnelState();
372
+ logger.info(gone.tunnelId === "self-hosted" || gone.tunnelId === "quick" ? "TeamClaw tunnel: connector stopped" : `TeamClaw tunnel: stopped ${gone.hostname}`);
373
+ }
374
+ userStopping = false;
375
+ }
376
+ // Boot reconciliation: reconnect the share persisted by a previous run.
377
+ // Reuses the SAME remotely-managed tunnel (its connector token), so the
378
+ // tunnel id and gate token survive gateway restarts and visitor gate
379
+ // cookies stay valid.
380
+ async function recover() {
381
+ if (handle)
382
+ return handle;
383
+ const st = readTunnelState();
384
+ if (!st || st.tunnelId === "quick")
385
+ return null; // one-off, not recoverable
386
+ const bin = findCloudflared();
387
+ if (!bin) {
388
+ logger.warn("TeamClaw tunnel: previous share found but cloudflared is not installed; not recovering");
389
+ return null;
390
+ }
391
+ if (st.pid && connectorPidIsCloudflared(st.pid)) {
392
+ try {
393
+ process.kill(st.pid, "SIGKILL");
394
+ logger.warn(`TeamClaw tunnel: killed orphaned connector (pid ${st.pid})`);
395
+ }
396
+ catch { /* already gone */ }
397
+ }
398
+ startOp = { running: true, phase: "starting-connector", detail: st.hostname || "self-hosted tunnel" };
399
+ stopConnector();
400
+ child = spawnConnector(bin, st.connectorToken);
401
+ const selfHosted = st.tunnelId === "self-hosted";
402
+ handle = selfHosted
403
+ ? { tunnelId: "self-hosted", hostname: "", gateToken: "", deleteToken: "" }
404
+ : { tunnelId: st.tunnelId, hostname: st.hostname, gateToken: st.gateToken, deleteToken: st.deleteToken };
405
+ writeTunnelState({ ...st, pid: child.pid ?? null, savedAt: Date.now() });
406
+ startOp = { running: false, phase: "done", detail: st.hostname || "self-hosted tunnel" };
407
+ lastError = null;
408
+ logger.info(selfHosted ? "TeamClaw tunnel: recovered self-hosted Cloudflare tunnel" : `TeamClaw tunnel: recovered https://${st.hostname} (tunnel id and gate token preserved)`);
409
+ return handle;
410
+ }
411
+ function status() {
412
+ return {
413
+ active: Boolean(handle),
414
+ mode: handle ? (handle.tunnelId === "self-hosted" ? "self-hosted" : handle.tunnelId === "quick" ? "quick" : "managed") : null,
415
+ hostname: handle?.hostname || null,
416
+ gateToken: handle?.gateToken || null,
417
+ connectorRunning: Boolean(child),
418
+ tunnelId: handle?.tunnelId ?? null,
419
+ cloudflaredInstalled: findCloudflared() !== null,
420
+ cloudflaredPath: findCloudflared(),
421
+ envTokenDetected: selfHostedTokenFromEnv() !== null,
422
+ startOp: { ...startOp },
423
+ install: { ...installState },
424
+ error: lastError,
425
+ };
426
+ }
427
+ /**
428
+ * One-click cloudflared install across platforms:
429
+ * darwin -> brew install cloudflared (Homebrew), tarball fallback
430
+ * linux -> official RAW binary into ~/.local/bin (no sudo needed;
431
+ * cloudflared ships NO .tgz asset for linux - only darwin
432
+ * has tgz packages, and the binary is statically linked so
433
+ * it runs on any distro without glibc concerns)
434
+ * win32 -> winget install Cloudflare.cloudflared
435
+ */
436
+ function installCloudflared() {
437
+ if (installState.running) {
438
+ return Promise.resolve({ ok: false, detail: "install already in progress" });
439
+ }
440
+ const home = process.env.HOME ?? "/tmp";
441
+ const userBin = path.join(home, ".local", "bin");
442
+ const target = path.join(userBin, "cloudflared");
443
+ const tail = (s) => s.trim().split("\n").slice(-2).join(" ").slice(0, 200);
444
+ const setPhase = (phase, percent, detail) => {
445
+ installState = { running: true, phase, percent, detail };
446
+ };
447
+ const finish = (phase, detail) => {
448
+ installState = { running: false, phase, percent: phase === "done" ? 100 : null, detail };
449
+ };
450
+ const run = (cmd, args) => new Promise((resolve) => {
451
+ const proc = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"] });
452
+ let out = "";
453
+ proc.stdout?.on("data", (c) => (out += c));
454
+ proc.stderr?.on("data", (c) => (out += c));
455
+ proc.on("error", (e) => resolve({ code: 1, out: String(e) }));
456
+ proc.on("close", (code) => resolve({ code: code ?? 1, out }));
457
+ });
458
+ const job = (async () => {
459
+ const plat = process.platform + ":" + process.arch;
460
+ logger.info("TeamClaw tunnel: installing cloudflared for " + plat);
461
+ setPhase("installing", null, plat);
462
+ if (process.platform === "win32") {
463
+ const w = await run("winget", ["install", "--id", "Cloudflare.cloudflared", "--accept-source-agreements", "--accept-package-agreements"]);
464
+ return w.code === 0 ? { ok: true, detail: "installed via winget" } : { ok: false, detail: "winget: " + tail(w.out) };
465
+ }
466
+ if (process.platform === "darwin") {
467
+ setPhase("brew", 30, "Homebrew");
468
+ const brew = await run("brew", ["install", "cloudflared"]);
469
+ if (brew.code === 0)
470
+ return { ok: true, detail: "installed via Homebrew" };
471
+ }
472
+ const arch = process.arch === "arm64" ? "arm64" : process.arch === "ia32" ? "386" : "amd64";
473
+ const isDarwin = process.platform === "darwin";
474
+ // Linux assets are RAW binaries (no .tgz exists for linux - verified
475
+ // against the official release page; the old .tgz URL 404s there).
476
+ const name = isDarwin ? "cloudflared-darwin-" + arch + ".tgz" : "cloudflared-linux-" + arch;
477
+ fs.mkdirSync(userBin, { recursive: true });
478
+ const tgz = path.join(userBin, name);
479
+ const url = "https://github.com/cloudflare/cloudflared/releases/latest/download/" + name;
480
+ let total = 0;
481
+ try {
482
+ const head = await new Promise((resolve, reject) => {
483
+ const r = https.request(url, { method: "HEAD" }, resolve);
484
+ r.on("error", reject);
485
+ r.end();
486
+ });
487
+ total = Number(head.headers["content-length"] ?? 0);
488
+ }
489
+ catch {
490
+ total = 0;
491
+ }
492
+ setPhase("downloading", 0, url);
493
+ const watch = (file) => {
494
+ const timer = setInterval(() => {
495
+ try {
496
+ const size = fs.statSync(file).size;
497
+ if (total > 0)
498
+ setPhase("downloading", Math.min(99, Math.floor((size / total) * 100)), null);
499
+ }
500
+ catch { /* file not created yet */ }
501
+ }, 500);
502
+ return () => clearInterval(timer);
503
+ };
504
+ // curl first (resume/retry flags), native https fallback for images
505
+ // without curl (distroless etc.). GitHub releases redirect - follow them.
506
+ const dlPath = isDarwin ? tgz : target;
507
+ const stopWatch = watch(dlPath);
508
+ const dl = await run("curl", ["-fsSL", "--retry", "3", "-o", dlPath, url]);
509
+ stopWatch();
510
+ if (dl.code !== 0) {
511
+ setPhase("downloading", null, "native https fallback");
512
+ try {
513
+ await nativeDownload(url, dlPath);
514
+ }
515
+ catch (e) {
516
+ return { ok: false, detail: "download: " + (e instanceof Error ? e.message : String(e)) };
517
+ }
518
+ }
519
+ if (isDarwin) {
520
+ setPhase("extracting", 99, null);
521
+ const ex = await run("tar", ["xzf", tgz, "-C", userBin]);
522
+ fs.rmSync(tgz, { force: true });
523
+ if (ex.code !== 0)
524
+ return { ok: false, detail: "extract: " + tail(ex.out) };
525
+ }
526
+ fs.chmodSync(target, 0o755);
527
+ return { ok: true, detail: "installed to " + target };
528
+ })();
529
+ job.then((r) => finish(r.ok ? "done" : "error", r.detail), (e) => finish("error", String(e)));
530
+ return job;
531
+ }
532
+ return { start: launchStart, startSelfHosted, startQuick, stop, recover, status, installCloudflared, isTunnelRequest, gateAllows };
533
+ }
534
+ export function gatePageHtml(hostname, wrong) {
535
+ return `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>TeamClaw Tunnel</title>
536
+ <style>body{font-family:-apple-system,system-ui,sans-serif;background:#121110;color:#ecebe6;display:flex;align-items:center;justify-content:center;height:100vh;margin:0}
537
+ .card{background:#1a1917;border:1px solid #2d2b27;border-radius:12px;padding:32px;width:min(360px,90vw);text-align:center}
538
+ h1{font-size:16px;margin:0 0 6px}p{font-size:12.5px;color:#a8a49a;margin:0 0 18px}
539
+ input{width:100%;padding:10px 12px;border-radius:8px;border:1px solid #3a3731;background:#232120;color:#ecebe6;font-size:16px;letter-spacing:.2em;text-align:center;text-transform:uppercase;box-sizing:border-box}
540
+ button{margin-top:12px;width:100%;padding:10px;border:none;border-radius:8px;background:#d9a664;color:#1a1510;font-weight:600;font-size:14px;cursor:pointer}
541
+ .err{color:#c96f5e;font-size:12px;margin-top:10px}</style></head>
542
+ <body><div class="card"><h1>TeamClaw</h1><p>${hostname} is protected by a gate token. Ask the owner for it.</p>
543
+ <form method="POST" action="/__tunnel_gate/verify"><input name="token" placeholder="GATE TOKEN" autofocus autocomplete="off"><button type="submit">Enter</button>${wrong ? '<div class="err">Wrong token, try again.</div>' : ""}</form></div></body></html>`;
544
+ }
545
+ export const GATE_COOKIE_NAME = GATE_COOKIE;
546
+ export function computeGateCookie(gateToken, tunnelId) {
547
+ return gateCookieValue(gateToken, tunnelId);
548
+ }
@@ -0,0 +1,42 @@
1
+ import { WebSocketServer, WebSocket } from "ws";
2
+ export class TeamWebSocketServer {
3
+ wss = null;
4
+ logger;
5
+ constructor(logger) {
6
+ this.logger = logger;
7
+ }
8
+ attach(server) {
9
+ this.wss = new WebSocketServer({ server, path: "/ws" });
10
+ this.wss.on("connection", (ws) => {
11
+ this.logger.info("WebSocket: client connected");
12
+ ws.on("close", () => {
13
+ this.logger.info("WebSocket: client disconnected");
14
+ });
15
+ });
16
+ this.wss.on("error", (err) => {
17
+ this.logger.warn(`WebSocket: error: ${String(err)}`);
18
+ });
19
+ }
20
+ broadcastUpdate(event) {
21
+ if (!this.wss)
22
+ return;
23
+ const data = JSON.stringify(event);
24
+ for (const client of this.wss.clients) {
25
+ if (client.readyState === WebSocket.OPEN) {
26
+ client.send(data);
27
+ }
28
+ }
29
+ }
30
+ close() {
31
+ if (this.wss) {
32
+ for (const client of this.wss.clients) {
33
+ client.close();
34
+ }
35
+ this.wss.close();
36
+ this.wss = null;
37
+ }
38
+ }
39
+ getClientCount() {
40
+ return this.wss ? this.wss.clients.size : 0;
41
+ }
42
+ }