@teamclaws/teamclaw 2026.5.0 → 2026.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/openclaw.plugin.json +1 -1
- package/package.json +2 -2
- package/src/controller/controller-service.ts +6 -0
- package/src/controller/http-server.ts +145 -1
- package/src/controller/tunnel-manager.ts +386 -0
- package/src/controller/websocket.ts +2 -1
- package/src/controller/worker-provisioning.ts +49 -1
- package/src/teamauto/schedule.ts +136 -0
- package/src/teamauto/scheduler.ts +31 -25
- package/src/ui/app.js +357 -1
- package/src/ui/index.html +6 -0
- package/src/ui/style.css +9 -0
package/openclaw.plugin.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"id": "teamclaw",
|
|
3
3
|
"name": "TeamClaw",
|
|
4
4
|
"description": "Virtual team collaboration - multiple OpenClaw instances form a virtual software company with role-based task routing.",
|
|
5
|
-
"version": "2026.
|
|
5
|
+
"version": "2026.7.0",
|
|
6
6
|
"activation": {
|
|
7
7
|
"onStartup": true
|
|
8
8
|
},
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@teamclaws/teamclaw",
|
|
3
|
-
"version": "2026.
|
|
3
|
+
"version": "2026.7.0",
|
|
4
4
|
"description": "OpenClaw virtual software team orchestration plugin",
|
|
5
5
|
"private": false,
|
|
6
6
|
"keywords": [
|
|
@@ -59,7 +59,7 @@
|
|
|
59
59
|
"devDependencies": {
|
|
60
60
|
"@types/node": "^24",
|
|
61
61
|
"@types/ws": "^8.18.2",
|
|
62
|
-
"typescript": "
|
|
62
|
+
"typescript": "5.9"
|
|
63
63
|
},
|
|
64
64
|
"publishConfig": {
|
|
65
65
|
"access": "public"
|
|
@@ -266,6 +266,12 @@ export function createControllerService(deps: ControllerServiceDeps): OpenClawPl
|
|
|
266
266
|
onTasksCreated: async () => {
|
|
267
267
|
await autoAssignPendingTasks(httpDepsForAutoAssign);
|
|
268
268
|
},
|
|
269
|
+
onActivity: (entry) => {
|
|
270
|
+
wsServer.broadcastUpdate({
|
|
271
|
+
type: "teamauto:activity",
|
|
272
|
+
data: { at: entry.at, repoId: entry.repoId, kind: entry.kind, text: entry.text },
|
|
273
|
+
});
|
|
274
|
+
},
|
|
269
275
|
});
|
|
270
276
|
await teamAutoSchedulerRef.start();
|
|
271
277
|
} catch (err) {
|
|
@@ -2,6 +2,7 @@ import fs from "node:fs";
|
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import http from "node:http";
|
|
4
4
|
import zlib from "node:zlib";
|
|
5
|
+
import { createHash } from "node:crypto";
|
|
5
6
|
import { execFileSync } from "node:child_process";
|
|
6
7
|
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
7
8
|
import type { OpenClawPluginApi, PluginLogger } from "../../api.js";
|
|
@@ -53,6 +54,7 @@ import type { WorkerProvisioningManager } from "./worker-provisioning.js";
|
|
|
53
54
|
import type { PreviewManager } from "./preview-manager.js";
|
|
54
55
|
import { createControllerPromptInjector } from "./prompt-injector.js";
|
|
55
56
|
import { getGithubAuthManager } from "./github-auth.js";
|
|
57
|
+
import { createTunnelManager, gatePageHtml, computeGateCookie, GATE_COOKIE_NAME, type TunnelManager } from "./tunnel-manager.js";
|
|
56
58
|
import { createGithubClient } from "../teamauto/github-client.js";
|
|
57
59
|
import type { TeamAutoScheduler } from "../teamauto/scheduler.js";
|
|
58
60
|
import { buildControllerNoWorkersMessage, shouldBlockControllerWithoutWorkers } from "./controller-capacity.js";
|
|
@@ -3582,6 +3584,52 @@ async function cancelTaskExecution(
|
|
|
3582
3584
|
}, deps);
|
|
3583
3585
|
}
|
|
3584
3586
|
|
|
3587
|
+
// Tunnel/CDN caches rewrite the origin's Cache-Control: no-cache into a long
|
|
3588
|
+
// browser freeze for cacheable extensions like .js (observed: Cloudflare
|
|
3589
|
+
// Browser Cache TTL max-age=14400 on tunneled UI assets). A UI update then
|
|
3590
|
+
// never reaches visitors through the tunnel. Serving content-versioned URLs
|
|
3591
|
+
// (?v=<hash>) makes every UI deploy a URL no browser or edge has ever seen,
|
|
3592
|
+
// so stale-cache behavior cannot recur.
|
|
3593
|
+
const uiAssetVersionCache = new Map<string, { mtimeMs: number; version: string }>();
|
|
3594
|
+
|
|
3595
|
+
function uiAssetVersion(uiPath: string, file: string): string {
|
|
3596
|
+
const full = path.join(uiPath, file);
|
|
3597
|
+
try {
|
|
3598
|
+
const mtimeMs = fs.statSync(full).mtimeMs;
|
|
3599
|
+
const cached = uiAssetVersionCache.get(full);
|
|
3600
|
+
if (cached && cached.mtimeMs === mtimeMs) return cached.version;
|
|
3601
|
+
const version = createHash("sha1").update(fs.readFileSync(full)).digest("hex").slice(0, 10);
|
|
3602
|
+
uiAssetVersionCache.set(full, { mtimeMs, version });
|
|
3603
|
+
return version;
|
|
3604
|
+
} catch {
|
|
3605
|
+
return String(Date.now()); // unreadable asset: bust for this request
|
|
3606
|
+
}
|
|
3607
|
+
}
|
|
3608
|
+
|
|
3609
|
+
const UI_HTML_ASSET_REFS = [
|
|
3610
|
+
"/ui/style.css",
|
|
3611
|
+
"/ui/app.js",
|
|
3612
|
+
"/ui/assets/teamclaw-app-icon.png",
|
|
3613
|
+
];
|
|
3614
|
+
|
|
3615
|
+
function serveVersionedHtml(res: ServerResponse, htmlPath: string): void {
|
|
3616
|
+
try {
|
|
3617
|
+
const uiPath = path.dirname(htmlPath);
|
|
3618
|
+
let html = fs.readFileSync(htmlPath, "utf8");
|
|
3619
|
+
for (const ref of UI_HTML_ASSET_REFS) {
|
|
3620
|
+
html = html.split(`"${ref}"`).join(`"${ref}?v=${uiAssetVersion(uiPath, ref.slice("/ui/".length))}"`);
|
|
3621
|
+
}
|
|
3622
|
+
res.writeHead(200, {
|
|
3623
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
3624
|
+
"Access-Control-Allow-Origin": "*",
|
|
3625
|
+
"Cache-Control": "no-cache",
|
|
3626
|
+
});
|
|
3627
|
+
res.end(html);
|
|
3628
|
+
} catch {
|
|
3629
|
+
sendError(res, 404, "File not found");
|
|
3630
|
+
}
|
|
3631
|
+
}
|
|
3632
|
+
|
|
3585
3633
|
function serveStaticFile(res: ServerResponse, filePath: string, contentType: string): void {
|
|
3586
3634
|
try {
|
|
3587
3635
|
const content = fs.readFileSync(filePath);
|
|
@@ -4658,6 +4706,16 @@ export async function autoAssignPendingTasks(
|
|
|
4658
4706
|
|
|
4659
4707
|
export function createControllerHttpServer(deps: ControllerHttpDeps): http.Server {
|
|
4660
4708
|
const { logger, wsServer } = deps;
|
|
4709
|
+
let tunnelManagerSingleton: TunnelManager | null = null;
|
|
4710
|
+
|
|
4711
|
+
const readFormBody = async (request: IncomingMessage): Promise<Record<string, unknown>> => {
|
|
4712
|
+
const chunks: Buffer[] = [];
|
|
4713
|
+
for await (const chunk of request) chunks.push(chunk as Buffer);
|
|
4714
|
+
const raw = Buffer.concat(chunks).toString("utf8");
|
|
4715
|
+
const out: Record<string, unknown> = {};
|
|
4716
|
+
for (const [k, v] of new URLSearchParams(raw)) out[k] = v;
|
|
4717
|
+
return out;
|
|
4718
|
+
};
|
|
4661
4719
|
|
|
4662
4720
|
const server = http.createServer(async (req: IncomingMessage, res: ServerResponse) => {
|
|
4663
4721
|
// CORS preflight
|
|
@@ -4674,6 +4732,76 @@ export function createControllerHttpServer(deps: ControllerHttpDeps): http.Serve
|
|
|
4674
4732
|
const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
|
|
4675
4733
|
const pathname = url.pathname;
|
|
4676
4734
|
|
|
4735
|
+
// Tunnel sharing: every request arriving via <user>.apps.teamclaw.dev is
|
|
4736
|
+
// gated behind the token the local web UI displays.
|
|
4737
|
+
let tunnelManager = tunnelManagerSingleton;
|
|
4738
|
+
if (!tunnelManager) {
|
|
4739
|
+
tunnelManager = tunnelManagerSingleton = createTunnelManager({ logger, localPort: deps.config.port });
|
|
4740
|
+
}
|
|
4741
|
+
const viaTunnel = tunnelManager.isTunnelRequest(typeof req.headers.host === "string" ? req.headers.host : undefined);
|
|
4742
|
+
if (viaTunnel) {
|
|
4743
|
+
if (req.method === "GET" && (pathname === "/__tunnel_gate" || pathname === "/")) {
|
|
4744
|
+
// Valid gate cookie on "/" goes straight to the dashboard; the gate
|
|
4745
|
+
// page only greets visitors who have not authenticated yet.
|
|
4746
|
+
if (pathname === "/" && tunnelManager.gateAllows(req)) {
|
|
4747
|
+
res.writeHead(302, { Location: "/ui/" });
|
|
4748
|
+
res.end();
|
|
4749
|
+
return;
|
|
4750
|
+
}
|
|
4751
|
+
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
|
|
4752
|
+
res.end(gatePageHtml(String(req.headers.host), false));
|
|
4753
|
+
return;
|
|
4754
|
+
}
|
|
4755
|
+
if (req.method === "POST" && pathname === "/__tunnel_gate/verify") {
|
|
4756
|
+
const form = await readFormBody(req);
|
|
4757
|
+
const submitted = String((form as { token?: unknown }).token ?? "").trim().toUpperCase();
|
|
4758
|
+
const st = tunnelManager.status();
|
|
4759
|
+
if (st.active && st.gateToken && submitted === st.gateToken) {
|
|
4760
|
+
const cookie = `${GATE_COOKIE_NAME}=${computeGateCookie(st.gateToken, st.tunnelId ?? "")}; Path=/; Max-Age=43200; HttpOnly; SameSite=Lax`;
|
|
4761
|
+
res.writeHead(302, { "Set-Cookie": cookie, Location: "/" });
|
|
4762
|
+
res.end();
|
|
4763
|
+
return;
|
|
4764
|
+
}
|
|
4765
|
+
res.writeHead(403, { "Content-Type": "text/html; charset=utf-8" });
|
|
4766
|
+
res.end(gatePageHtml(String(req.headers.host), true));
|
|
4767
|
+
return;
|
|
4768
|
+
}
|
|
4769
|
+
if (!tunnelManager.gateAllows(req)) {
|
|
4770
|
+
res.writeHead(403, { "Content-Type": "text/html; charset=utf-8" });
|
|
4771
|
+
res.end(gatePageHtml(String(req.headers.host), false));
|
|
4772
|
+
return;
|
|
4773
|
+
}
|
|
4774
|
+
} else {
|
|
4775
|
+
if (req.method === "GET" && pathname === "/api/v1/tunnel/status") {
|
|
4776
|
+
sendJson(res, 200, tunnelManager.status());
|
|
4777
|
+
return;
|
|
4778
|
+
}
|
|
4779
|
+
if (req.method === "POST" && pathname === "/api/v1/tunnel/start") {
|
|
4780
|
+
const authStatus = await getGithubAuthManager(deps.config, logger).getStatus();
|
|
4781
|
+
const account = authStatus.account;
|
|
4782
|
+
if (!account?.login) { sendError(res, 401, "GitHub login required to share a tunnel"); return; }
|
|
4783
|
+
// Async launch: poll /tunnel/status for phase progress and the
|
|
4784
|
+
// resulting hostname/gateToken once startOp.phase === "done".
|
|
4785
|
+
const launched = tunnelManager.start(account.login);
|
|
4786
|
+
sendJson(res, 202, { launched, status: tunnelManager.status() });
|
|
4787
|
+
return;
|
|
4788
|
+
}
|
|
4789
|
+
if (req.method === "POST" && pathname === "/api/v1/tunnel/stop") {
|
|
4790
|
+
await tunnelManager.stop();
|
|
4791
|
+
sendJson(res, 200, tunnelManager.status());
|
|
4792
|
+
return;
|
|
4793
|
+
}
|
|
4794
|
+
if (req.method === "POST" && pathname === "/api/v1/tunnel/install-cloudflared") {
|
|
4795
|
+
try {
|
|
4796
|
+
const result = await tunnelManager.installCloudflared();
|
|
4797
|
+
sendJson(res, result.ok ? 200 : 500, { ...result, status: tunnelManager.status() });
|
|
4798
|
+
} catch (err) {
|
|
4799
|
+
sendError(res, 500, err instanceof Error ? err.message : "install failed");
|
|
4800
|
+
}
|
|
4801
|
+
return;
|
|
4802
|
+
}
|
|
4803
|
+
}
|
|
4804
|
+
|
|
4677
4805
|
try {
|
|
4678
4806
|
await handleRequest(req, res, pathname, deps);
|
|
4679
4807
|
} catch (err) {
|
|
@@ -4685,6 +4813,21 @@ export function createControllerHttpServer(deps: ControllerHttpDeps): http.Serve
|
|
|
4685
4813
|
// Attach WebSocket
|
|
4686
4814
|
wsServer.attach(server);
|
|
4687
4815
|
|
|
4816
|
+
// Plugin shutdown: kill the local connector and tear down the remote
|
|
4817
|
+
// tunnel so gateway exits never leak orphan cloudflared processes.
|
|
4818
|
+
server.on("close", () => {
|
|
4819
|
+
void tunnelManagerSingleton?.stop().catch(() => undefined);
|
|
4820
|
+
});
|
|
4821
|
+
|
|
4822
|
+
// Boot reconciliation: reconnect a share persisted by a previous run
|
|
4823
|
+
// (gateway restart or kill -9) so the tunnel id and gate token survive.
|
|
4824
|
+
if (!tunnelManagerSingleton) {
|
|
4825
|
+
tunnelManagerSingleton = createTunnelManager({ logger, localPort: deps.config.port });
|
|
4826
|
+
}
|
|
4827
|
+
void tunnelManagerSingleton.recover().catch((err) => {
|
|
4828
|
+
logger.warn(`TeamClaw tunnel: boot recovery failed: ${String(err)}`);
|
|
4829
|
+
});
|
|
4830
|
+
|
|
4688
4831
|
setTimeout(() => {
|
|
4689
4832
|
const state = deps.getTeamState();
|
|
4690
4833
|
const pendingCount = state
|
|
@@ -4742,6 +4885,7 @@ async function handleRequest(
|
|
|
4742
4885
|
pathname: string,
|
|
4743
4886
|
deps: ControllerHttpDeps,
|
|
4744
4887
|
): Promise<void> {
|
|
4888
|
+
void pathname;
|
|
4745
4889
|
const { config, logger, getTeamState, updateTeamState, taskRouter, messageRouter, wsServer } = deps;
|
|
4746
4890
|
const requestUrl = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
|
|
4747
4891
|
const currentState = getTeamState();
|
|
@@ -4756,7 +4900,7 @@ async function handleRequest(
|
|
|
4756
4900
|
|
|
4757
4901
|
if (req.method === "GET" && (pathname === "/ui" || pathname === "/ui/")) {
|
|
4758
4902
|
const uiPath = path.join(import.meta.dirname, "..", "ui");
|
|
4759
|
-
|
|
4903
|
+
serveVersionedHtml(res, path.join(uiPath, "index.html"));
|
|
4760
4904
|
return;
|
|
4761
4905
|
}
|
|
4762
4906
|
|
|
@@ -0,0 +1,386 @@
|
|
|
1
|
+
import { execFileSync, spawn, type ChildProcess } from "node:child_process";
|
|
2
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import type { PluginLogger } from "../../api.js";
|
|
5
|
+
import https from "node:https";
|
|
6
|
+
import os from "node:os";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
|
|
9
|
+
const TUNNEL_API_HOST = "apps.teamclaw.dev";
|
|
10
|
+
async function tunnelFetch(pathq: string, method: "POST" | "DELETE", body?: unknown): Promise<{ status: number; json: any }> {
|
|
11
|
+
const ip = await new Promise<string>((resolve, reject) => {
|
|
12
|
+
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" } as never, (res: import("node:http").IncomingMessage) => {
|
|
13
|
+
let d = ""; res.on("data", (c: Buffer) => (d += c)); res.on("end", () => {
|
|
14
|
+
try { const rec = (JSON.parse(d).Answer || []).map((x: { data: string }) => x.data).find((x: string) => /^\d+\./.test(x)); rec ? resolve(rec) : reject(new Error("DoH no A record")); } catch (e) { reject(e); }
|
|
15
|
+
});
|
|
16
|
+
});
|
|
17
|
+
r.on("error", reject); r.end();
|
|
18
|
+
});
|
|
19
|
+
return new Promise((resolve, reject) => {
|
|
20
|
+
const payload = body === undefined ? null : JSON.stringify(body);
|
|
21
|
+
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) } : {}) } } as never, (res: import("node:http").IncomingMessage) => {
|
|
22
|
+
let d = ""; res.on("data", (c: Buffer) => (d += c)); res.on("end", () => { try { resolve({ status: res.statusCode ?? 0, json: d ? JSON.parse(d) : {} }); } catch { resolve({ status: res.statusCode ?? 0, json: {} }); } });
|
|
23
|
+
});
|
|
24
|
+
req.on("error", reject);
|
|
25
|
+
if (payload) req.write(payload);
|
|
26
|
+
req.end();
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Internet tunnel sharing for the local web UI.
|
|
33
|
+
*
|
|
34
|
+
* Flow: the controller asks the TeamClaw tunnel server (a Cloudflare Worker
|
|
35
|
+
* at apps.teamclaw.dev/api) to provision a per-user Cloudflare Tunnel, then
|
|
36
|
+
* runs `cloudflared` locally with the returned connector token. Visitors hit
|
|
37
|
+
* https://<github_user>.apps.teamclaw.dev and must enter the gate token that
|
|
38
|
+
* the local web UI displays (enforced by the controller's gate middleware).
|
|
39
|
+
*/
|
|
40
|
+
|
|
41
|
+
export const TUNNEL_SERVER_URL = "https://apps.teamclaw.dev/api";
|
|
42
|
+
const TUNNEL_HOST_SUFFIX = ".teamclaw.dev";
|
|
43
|
+
const GATE_COOKIE = "tc_tunnel_gate";
|
|
44
|
+
|
|
45
|
+
export type TunnelStatus = {
|
|
46
|
+
active: boolean;
|
|
47
|
+
hostname: string | null;
|
|
48
|
+
gateToken: string | null;
|
|
49
|
+
connectorRunning: boolean;
|
|
50
|
+
tunnelId: string | null;
|
|
51
|
+
cloudflaredInstalled: boolean;
|
|
52
|
+
cloudflaredPath: string | null;
|
|
53
|
+
startOp: { running: boolean; phase: string; detail: string | null };
|
|
54
|
+
install: { running: boolean; phase: string; percent: number | null; detail: string | null };
|
|
55
|
+
error: string | null;
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
export type TunnelHandle = {
|
|
59
|
+
tunnelId: string;
|
|
60
|
+
hostname: string;
|
|
61
|
+
gateToken: string;
|
|
62
|
+
// HMAC(tunnelId) issued by the tunnel server at create time; required to
|
|
63
|
+
// delete a live tunnel (tunnel ids are public via the DNS CNAME).
|
|
64
|
+
deleteToken: string;
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
const CLOUDFLARED_CANDIDATES = [
|
|
68
|
+
"cloudflared",
|
|
69
|
+
"/opt/homebrew/bin/cloudflared",
|
|
70
|
+
"/usr/local/bin/cloudflared",
|
|
71
|
+
"/usr/bin/cloudflared",
|
|
72
|
+
];
|
|
73
|
+
function tunnelRuntimeHome(): string {
|
|
74
|
+
try {
|
|
75
|
+
const dir = path.join(os.tmpdir(), "teamclaw-cloudflared-home");
|
|
76
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
77
|
+
return dir;
|
|
78
|
+
} catch {
|
|
79
|
+
return process.env.HOME ?? "/tmp";
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export interface PersistedTunnelState {
|
|
84
|
+
tunnelId: string;
|
|
85
|
+
hostname: string;
|
|
86
|
+
gateToken: string;
|
|
87
|
+
deleteToken: string;
|
|
88
|
+
connectorToken: string;
|
|
89
|
+
pid: number | null;
|
|
90
|
+
savedAt: number;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function tunnelStatePath(): string {
|
|
94
|
+
return path.join(tunnelRuntimeHome(), "tunnel-state.json");
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function readTunnelState(): PersistedTunnelState | null {
|
|
98
|
+
try {
|
|
99
|
+
const raw = JSON.parse(fs.readFileSync(tunnelStatePath(), "utf8")) as PersistedTunnelState;
|
|
100
|
+
return raw && raw.tunnelId && raw.connectorToken ? raw : null;
|
|
101
|
+
} catch {
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function writeTunnelState(st: PersistedTunnelState): void {
|
|
107
|
+
try {
|
|
108
|
+
fs.writeFileSync(tunnelStatePath(), JSON.stringify(st), { mode: 0o600 });
|
|
109
|
+
} catch { /* best effort */ }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function clearTunnelState(): void {
|
|
113
|
+
try { fs.rmSync(tunnelStatePath(), { force: true }); } catch { /* best effort */ }
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// pid-reuse-safe liveness: only treat the pid as OUR orphan when the binary
|
|
117
|
+
// still matches cloudflared.
|
|
118
|
+
function connectorPidIsCloudflared(pid: number): boolean {
|
|
119
|
+
try {
|
|
120
|
+
const out = execFileSync("ps", ["-p", String(pid), "-o", "comm="], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
|
|
121
|
+
return out.includes("cloudflared");
|
|
122
|
+
} catch {
|
|
123
|
+
return false;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function findCloudflared(): string | null {
|
|
128
|
+
for (const bin of CLOUDFLARED_CANDIDATES) {
|
|
129
|
+
try {
|
|
130
|
+
if (fs.existsSync(bin) && fs.accessSync(bin, fs.constants.X_OK) === undefined) {
|
|
131
|
+
return bin;
|
|
132
|
+
}
|
|
133
|
+
} catch {
|
|
134
|
+
/* try next */
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return null;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function gateCookieValue(gateToken: string, tunnelId: string): string {
|
|
141
|
+
return createHash("sha256").update(`${gateToken}:${tunnelId}`).digest("hex").slice(0, 32);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export function createTunnelManager(deps: { logger: PluginLogger; localPort: number }) {
|
|
145
|
+
const { logger } = deps;
|
|
146
|
+
let child: ChildProcess | null = null;
|
|
147
|
+
let handle: TunnelHandle | null = null;
|
|
148
|
+
let lastError: string | null = null;
|
|
149
|
+
let startOp: { running: boolean; phase: string; detail: string | null } = { running: false, phase: "idle", detail: null };
|
|
150
|
+
let installState: { running: boolean; phase: string; percent: number | null; detail: string | null } = { running: false, phase: "idle", percent: null, detail: null };
|
|
151
|
+
|
|
152
|
+
function isTunnelRequest(hostHeader: string | undefined): boolean {
|
|
153
|
+
return Boolean(hostHeader && hostHeader.toLowerCase().endsWith(TUNNEL_HOST_SUFFIX));
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function gateAllows(req: { headers: Record<string, unknown> }): boolean {
|
|
157
|
+
if (!handle) return false;
|
|
158
|
+
const cookie = String(req.headers.cookie ?? "");
|
|
159
|
+
const match = cookie.match(new RegExp(`${GATE_COOKIE}=([0-9a-f]+)`));
|
|
160
|
+
return Boolean(match && match[1] === gateCookieValue(handle.gateToken, handle.tunnelId));
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function launchStart(githubUser: string): { running: boolean; phase: string } {
|
|
164
|
+
if (startOp.running) return { running: true, phase: startOp.phase };
|
|
165
|
+
startOp = { running: true, phase: "creating-tunnel", detail: null };
|
|
166
|
+
void (async () => {
|
|
167
|
+
try {
|
|
168
|
+
const h = await start(githubUser);
|
|
169
|
+
startOp = { running: false, phase: "done", detail: h.hostname };
|
|
170
|
+
} catch (e) {
|
|
171
|
+
startOp = { running: false, phase: "error", detail: e instanceof Error ? e.message : String(e) };
|
|
172
|
+
}
|
|
173
|
+
})();
|
|
174
|
+
return { running: true, phase: startOp.phase };
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
async function start(githubUser: string): Promise<TunnelHandle> {
|
|
178
|
+
if (handle && child) return handle;
|
|
179
|
+
const bin = findCloudflared();
|
|
180
|
+
if (!bin) throw new Error("cloudflared not found (brew install cloudflared)");
|
|
181
|
+
const gateToken = randomBytes(6).toString("base64url").replace(/[-_]/g, "").slice(0, 8).toUpperCase();
|
|
182
|
+
const res = await tunnelFetch("/tunnels", "POST", { github_user: githubUser, local_port: deps.localPort });
|
|
183
|
+
const body = res.json as { tunnel_id?: string; connector_token?: string; hostname?: string; delete_token?: string; error?: string };
|
|
184
|
+
if (res.status !== 201 || !body.tunnel_id || !body.connector_token || !body.hostname) {
|
|
185
|
+
throw new Error(body.error ?? `tunnel server responded ${res.status}`);
|
|
186
|
+
}
|
|
187
|
+
startOp = { running: true, phase: "starting-connector", detail: body.hostname };
|
|
188
|
+
stopConnector();
|
|
189
|
+
child = spawnConnector(bin, body.connector_token);
|
|
190
|
+
handle = { tunnelId: body.tunnel_id, hostname: body.hostname, gateToken, deleteToken: body.delete_token ?? "" };
|
|
191
|
+
writeTunnelState({ tunnelId: body.tunnel_id, hostname: body.hostname, gateToken, deleteToken: body.delete_token ?? "", connectorToken: body.connector_token, pid: child.pid ?? null, savedAt: Date.now() });
|
|
192
|
+
lastError = null;
|
|
193
|
+
logger.info(`TeamClaw tunnel: serving https://${body.hostname}`);
|
|
194
|
+
return handle;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function spawnConnector(bin: string, connectorToken: string): ChildProcess {
|
|
198
|
+
const proc = spawn(bin, ["tunnel", "--no-autoupdate", "--protocol", "http2", "run", "--token", connectorToken], {
|
|
199
|
+
stdio: ["ignore", "ignore", "pipe"],
|
|
200
|
+
detached: false,
|
|
201
|
+
// Isolate from ~/.cloudflared/cert.pem (a local origin-cert would
|
|
202
|
+
// override the remotely-managed token config) and from QUIC-blocking
|
|
203
|
+
// networks (http2 rides regular TCP 443).
|
|
204
|
+
env: { ...process.env, HOME: tunnelRuntimeHome() },
|
|
205
|
+
});
|
|
206
|
+
proc.on("exit", (code: number | null) => {
|
|
207
|
+
logger.warn(`TeamClaw tunnel: cloudflared exited (code ${code})`);
|
|
208
|
+
if (child === proc) child = null;
|
|
209
|
+
});
|
|
210
|
+
// cloudflared logs (stderr) land in a single file for diagnosis.
|
|
211
|
+
// (stdout is "ignore" in stdio above, so there is nothing to pipe.)
|
|
212
|
+
const logPath = path.join(tunnelRuntimeHome(), "cloudflared.log");
|
|
213
|
+
proc.stderr?.pipe(fs.createWriteStream(logPath, { flags: "a" }));
|
|
214
|
+
return proc;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function stopConnector(): void {
|
|
218
|
+
if (child) {
|
|
219
|
+
child.kill("SIGTERM");
|
|
220
|
+
child = null;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
async function stop(): Promise<void> {
|
|
225
|
+
stopConnector();
|
|
226
|
+
if (handle) {
|
|
227
|
+
const gone = handle;
|
|
228
|
+
handle = null;
|
|
229
|
+
await tunnelFetch(`/tunnels/${gone.tunnelId}?user=${encodeURIComponent(gone.hostname.split(".")[0]!.replace(/^team-/, ""))}&token=${encodeURIComponent(gone.deleteToken)}`, "DELETE").catch(() => undefined);
|
|
230
|
+
clearTunnelState();
|
|
231
|
+
logger.info(`TeamClaw tunnel: stopped ${gone.hostname}`);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// Boot reconciliation: reconnect the share persisted by a previous run.
|
|
236
|
+
// Reuses the SAME remotely-managed tunnel (its connector token), so the
|
|
237
|
+
// tunnel id and gate token survive gateway restarts and visitor gate
|
|
238
|
+
// cookies stay valid.
|
|
239
|
+
async function recover(): Promise<TunnelHandle | null> {
|
|
240
|
+
if (handle) return handle;
|
|
241
|
+
const st = readTunnelState();
|
|
242
|
+
if (!st) return null;
|
|
243
|
+
const bin = findCloudflared();
|
|
244
|
+
if (!bin) {
|
|
245
|
+
logger.warn("TeamClaw tunnel: previous share found but cloudflared is not installed; not recovering");
|
|
246
|
+
return null;
|
|
247
|
+
}
|
|
248
|
+
// kill -9 of the gateway leaves an orphaned connector behind (SIGKILL
|
|
249
|
+
// cannot run the close handler). Reap it before reconnecting - pid-reuse
|
|
250
|
+
// safe: only when the binary still matches.
|
|
251
|
+
if (st.pid && connectorPidIsCloudflared(st.pid)) {
|
|
252
|
+
try {
|
|
253
|
+
process.kill(st.pid, "SIGKILL");
|
|
254
|
+
logger.warn(`TeamClaw tunnel: killed orphaned connector (pid ${st.pid})`);
|
|
255
|
+
} catch { /* already gone */ }
|
|
256
|
+
}
|
|
257
|
+
startOp = { running: true, phase: "starting-connector", detail: st.hostname };
|
|
258
|
+
stopConnector();
|
|
259
|
+
child = spawnConnector(bin, st.connectorToken);
|
|
260
|
+
handle = { tunnelId: st.tunnelId, hostname: st.hostname, gateToken: st.gateToken, deleteToken: st.deleteToken };
|
|
261
|
+
writeTunnelState({ ...st, pid: child.pid ?? null, savedAt: Date.now() });
|
|
262
|
+
startOp = { running: false, phase: "done", detail: st.hostname };
|
|
263
|
+
lastError = null;
|
|
264
|
+
logger.info(`TeamClaw tunnel: recovered https://${st.hostname} (tunnel id and gate token preserved)`);
|
|
265
|
+
return handle;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
function status(): TunnelStatus {
|
|
269
|
+
return {
|
|
270
|
+
active: Boolean(handle),
|
|
271
|
+
tunnelId: handle?.tunnelId ?? null,
|
|
272
|
+
hostname: handle?.hostname ?? null,
|
|
273
|
+
gateToken: handle?.gateToken ?? null,
|
|
274
|
+
connectorRunning: Boolean(child),
|
|
275
|
+
cloudflaredInstalled: findCloudflared() !== null,
|
|
276
|
+
cloudflaredPath: findCloudflared(),
|
|
277
|
+
startOp: { ...startOp },
|
|
278
|
+
install: { ...installState },
|
|
279
|
+
error: lastError,
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* One-click cloudflared install across platforms:
|
|
285
|
+
* darwin -> brew install cloudflared (Homebrew), tarball fallback
|
|
286
|
+
* linux -> official tarball into ~/.local/bin (no sudo needed)
|
|
287
|
+
* win32 -> winget install Cloudflare.cloudflared
|
|
288
|
+
*/
|
|
289
|
+
|
|
290
|
+
function installCloudflared(): Promise<{ ok: boolean; detail: string }> {
|
|
291
|
+
if (installState.running) {
|
|
292
|
+
return Promise.resolve({ ok: false, detail: "install already in progress" });
|
|
293
|
+
}
|
|
294
|
+
const home = process.env.HOME ?? "/tmp";
|
|
295
|
+
const userBin = path.join(home, ".local", "bin");
|
|
296
|
+
const target = path.join(userBin, "cloudflared");
|
|
297
|
+
const tail = (s: string) => s.trim().split("\n").slice(-2).join(" ").slice(0, 200);
|
|
298
|
+
const setPhase = (phase: string, percent: number | null, detail: string | null) => {
|
|
299
|
+
installState = { running: true, phase, percent, detail };
|
|
300
|
+
};
|
|
301
|
+
const finish = (phase: string, detail: string) => {
|
|
302
|
+
installState = { running: false, phase, percent: phase === "done" ? 100 : null, detail };
|
|
303
|
+
};
|
|
304
|
+
const run = (cmd: string, args: string[]) =>
|
|
305
|
+
new Promise<{ code: number; out: string }>((resolve) => {
|
|
306
|
+
const proc = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"] });
|
|
307
|
+
let out = "";
|
|
308
|
+
proc.stdout?.on("data", (c) => (out += c));
|
|
309
|
+
proc.stderr?.on("data", (c) => (out += c));
|
|
310
|
+
proc.on("error", (e) => resolve({ code: 1, out: String(e) }));
|
|
311
|
+
proc.on("close", (code) => resolve({ code: code ?? 1, out }));
|
|
312
|
+
});
|
|
313
|
+
|
|
314
|
+
const job = (async (): Promise<{ ok: boolean; detail: string }> => {
|
|
315
|
+
const plat = process.platform + ":" + process.arch;
|
|
316
|
+
logger.info("TeamClaw tunnel: installing cloudflared for " + plat);
|
|
317
|
+
setPhase("installing", null, plat);
|
|
318
|
+
if (process.platform === "win32") {
|
|
319
|
+
const w = await run("winget", ["install", "--id", "Cloudflare.cloudflared", "--accept-source-agreements", "--accept-package-agreements"]);
|
|
320
|
+
return w.code === 0 ? { ok: true, detail: "installed via winget" } : { ok: false, detail: "winget: " + tail(w.out) };
|
|
321
|
+
}
|
|
322
|
+
if (process.platform === "darwin") {
|
|
323
|
+
setPhase("brew", 30, "Homebrew");
|
|
324
|
+
const brew = await run("brew", ["install", "cloudflared"]);
|
|
325
|
+
if (brew.code === 0) return { ok: true, detail: "installed via Homebrew" };
|
|
326
|
+
}
|
|
327
|
+
const arch = process.arch === "arm64" ? "arm64" : process.arch === "ia32" ? "386" : "amd64";
|
|
328
|
+
const name = process.platform === "darwin" ? "cloudflared-darwin-" + arch + ".tgz" : "cloudflared-linux-" + arch + ".tgz";
|
|
329
|
+
fs.mkdirSync(userBin, { recursive: true });
|
|
330
|
+
const tgz = path.join(userBin, name);
|
|
331
|
+
const url = "https://github.com/cloudflare/cloudflared/releases/latest/download/" + name;
|
|
332
|
+
let total = 0;
|
|
333
|
+
try {
|
|
334
|
+
const head = await new Promise<import("node:http").IncomingMessage>((resolve, reject) => {
|
|
335
|
+
const r = https.request(url, { method: "HEAD" } as never, resolve as never);
|
|
336
|
+
r.on("error", reject); r.end();
|
|
337
|
+
});
|
|
338
|
+
total = Number(head.headers["content-length"] ?? 0);
|
|
339
|
+
} catch { total = 0; }
|
|
340
|
+
setPhase("downloading", 0, url);
|
|
341
|
+
const timer = setInterval(() => {
|
|
342
|
+
try {
|
|
343
|
+
const size = fs.statSync(tgz).size;
|
|
344
|
+
if (total > 0) setPhase("downloading", Math.min(99, Math.floor((size / total) * 100)), null);
|
|
345
|
+
} catch { /* file not created yet */ }
|
|
346
|
+
}, 500);
|
|
347
|
+
const dl = await run("curl", ["-fsSL", "--retry", "3", "-o", tgz, url]);
|
|
348
|
+
clearInterval(timer);
|
|
349
|
+
if (dl.code !== 0) return { ok: false, detail: "download: " + tail(dl.out) };
|
|
350
|
+
setPhase("extracting", 99, null);
|
|
351
|
+
const ex = await run("tar", ["xzf", tgz, "-C", userBin]);
|
|
352
|
+
fs.rmSync(tgz, { force: true });
|
|
353
|
+
if (ex.code !== 0) return { ok: false, detail: "extract: " + tail(ex.out) };
|
|
354
|
+
fs.chmodSync(target, 0o755);
|
|
355
|
+
return { ok: true, detail: "installed to " + target };
|
|
356
|
+
})();
|
|
357
|
+
|
|
358
|
+
job.then(
|
|
359
|
+
(r) => finish(r.ok ? "done" : "error", r.detail),
|
|
360
|
+
(e) => finish("error", String(e)),
|
|
361
|
+
);
|
|
362
|
+
return job;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
return { start: launchStart, stop, recover, status, installCloudflared, isTunnelRequest, gateAllows };
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
export type TunnelManager = ReturnType<typeof createTunnelManager>;
|
|
370
|
+
|
|
371
|
+
export function gatePageHtml(hostname: string, wrong: boolean): string {
|
|
372
|
+
return `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>TeamClaw Tunnel</title>
|
|
373
|
+
<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}
|
|
374
|
+
.card{background:#1a1917;border:1px solid #2d2b27;border-radius:12px;padding:32px;width:min(360px,90vw);text-align:center}
|
|
375
|
+
h1{font-size:16px;margin:0 0 6px}p{font-size:12.5px;color:#a8a49a;margin:0 0 18px}
|
|
376
|
+
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}
|
|
377
|
+
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}
|
|
378
|
+
.err{color:#c96f5e;font-size:12px;margin-top:10px}</style></head>
|
|
379
|
+
<body><div class="card"><h1>TeamClaw</h1><p>${hostname} is protected by a gate token. Ask the owner for it.</p>
|
|
380
|
+
<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>`;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
export const GATE_COOKIE_NAME = GATE_COOKIE;
|
|
384
|
+
export function computeGateCookie(gateToken: string, tunnelId: string): string {
|
|
385
|
+
return gateCookieValue(gateToken, tunnelId);
|
|
386
|
+
}
|
|
@@ -19,7 +19,8 @@ export type WsEvent =
|
|
|
19
19
|
| { type: "message:deleted"; data: unknown }
|
|
20
20
|
| { type: "project:deleted"; data: unknown }
|
|
21
21
|
| { type: "requirement:complete"; data: unknown }
|
|
22
|
-
| { type: "report:ready"; data: unknown }
|
|
22
|
+
| { type: "report:ready"; data: unknown }
|
|
23
|
+
| { type: "teamauto:activity"; data: unknown };
|
|
23
24
|
|
|
24
25
|
export class TeamWebSocketServer {
|
|
25
26
|
private wss: WebSocketServer | null = null;
|