@teamclaws/teamclaw 2026.8.0 → 2026.11.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/cli.mjs +46 -15
- package/dist/api.js +1 -0
- package/dist/index.js +325 -0
- package/dist/src/config.js +412 -0
- package/dist/src/controller/clarification-routes.js +315 -0
- package/dist/src/controller/controller-capacity.js +14 -0
- package/dist/src/controller/controller-intake.js +895 -0
- package/dist/src/controller/controller-planning.js +813 -0
- package/dist/src/controller/controller-runs.js +175 -0
- package/dist/src/controller/controller-service.js +624 -0
- package/dist/src/controller/controller-tools.js +587 -0
- package/dist/src/controller/delivery-report.js +458 -0
- package/dist/src/controller/github-auth.js +564 -0
- package/dist/src/controller/http-server.js +284 -0
- package/dist/src/controller/kickoff-orchestrator.js +246 -0
- package/dist/src/controller/managed-gateway-process.js +286 -0
- package/dist/src/controller/message-delivery.js +28 -0
- package/dist/src/controller/message-router.js +38 -0
- package/dist/src/controller/message-routes.js +114 -0
- package/dist/src/controller/orchestration-manifest.js +151 -0
- package/dist/src/controller/preview-manager.js +586 -0
- package/dist/src/controller/preview-proxy.js +98 -0
- package/dist/src/controller/profile-switch.js +289 -0
- package/dist/src/controller/project-registry.js +294 -0
- package/dist/src/controller/prompt-injector.js +197 -0
- package/dist/src/controller/repo-routes.js +63 -0
- package/dist/src/controller/role-inference.js +246 -0
- package/dist/src/controller/route-table.js +1353 -0
- package/dist/src/controller/task-assignment.js +508 -0
- package/dist/src/controller/task-cleanup.js +258 -0
- package/dist/src/controller/task-execution.js +240 -0
- package/dist/src/controller/task-results.js +461 -0
- package/dist/src/controller/task-router.js +137 -0
- package/dist/src/controller/task-routes.js +703 -0
- package/dist/src/controller/teamauto-routes.js +124 -0
- package/dist/src/controller/tunnel-manager.js +548 -0
- package/dist/src/controller/ui-assets.js +68 -0
- package/dist/src/controller/websocket.js +42 -0
- package/dist/src/controller/worker-provisioning.js +1674 -0
- package/dist/src/controller/worker-routes.js +188 -0
- package/dist/src/discovery.js +86 -0
- package/dist/src/git-collaboration.js +694 -0
- package/dist/src/identity.js +132 -0
- package/dist/src/install-defaults.js +1 -0
- package/dist/src/interaction-contracts.js +531 -0
- package/dist/src/networking.js +91 -0
- package/dist/src/openclaw-workspace.js +925 -0
- package/dist/src/profile-loader.js +486 -0
- package/dist/src/profiles/banking.json +178 -0
- package/dist/src/profiles/crossborder-ecom.json +253 -0
- package/dist/src/profiles/insurance.json +157 -0
- package/dist/src/profiles/knowledge/hs-structure.md +97 -0
- package/dist/src/profiles/knowledge/incoterms-2020.md +188 -0
- package/dist/src/profiles/knowledge/vat-principles.md +85 -0
- package/dist/src/profiles/schema.json +201 -0
- package/dist/src/profiles/securities.json +137 -0
- package/dist/src/profiles/software-rd.json +264 -0
- package/dist/src/profiles/trading-co.json +200 -0
- package/dist/src/prompt-policy.js +386 -0
- package/dist/src/protocol.js +58 -0
- package/dist/src/role-ids.js +29 -0
- package/dist/src/roles.js +390 -0
- package/dist/src/session-roles.js +14 -0
- package/dist/src/state.js +361 -0
- package/dist/src/task-executor.js +1023 -0
- package/dist/src/teamauto/github-client.js +210 -0
- package/dist/src/teamauto/norms.js +85 -0
- package/dist/src/teamauto/repo-sync.js +423 -0
- package/dist/src/teamauto/scanner.js +207 -0
- package/dist/src/teamauto/schedule.js +123 -0
- package/dist/src/teamauto/scheduler.js +907 -0
- package/dist/src/teamauto/store.js +133 -0
- package/dist/src/types.js +290 -0
- package/dist/src/ui/app.js +4860 -0
- package/dist/src/ui/assets/teamclaw-app-icon.png +0 -0
- package/dist/src/ui/github-login.html +296 -0
- package/dist/src/ui/index.html +447 -0
- package/dist/src/ui/style.css +2805 -0
- package/dist/src/worker/http-handler.js +146 -0
- package/dist/src/worker/message-queue.js +24 -0
- package/dist/src/worker/prompt-injector.js +78 -0
- package/dist/src/worker/skill-installer.js +255 -0
- package/dist/src/worker/tools.js +541 -0
- package/dist/src/worker/worker-service.js +307 -0
- package/dist/src/workspace-browser.js +269 -0
- package/openclaw.plugin.json +28 -1
- package/package.json +3 -2
- package/src/config.ts +33 -2
- package/src/controller/clarification-routes.ts +404 -0
- package/src/controller/controller-intake.ts +1113 -0
- package/src/controller/controller-planning.ts +1029 -0
- package/src/controller/controller-runs.ts +239 -0
- package/src/controller/controller-service.ts +295 -41
- package/src/controller/controller-tools.ts +11 -7
- package/src/controller/http-server.ts +294 -6971
- package/src/controller/kickoff-orchestrator.ts +70 -7
- package/src/controller/message-delivery.ts +49 -0
- package/src/controller/message-routes.ts +137 -0
- package/src/controller/orchestration-manifest.ts +6 -29
- package/src/controller/preview-proxy.ts +127 -0
- package/src/controller/profile-switch.ts +366 -0
- package/src/controller/project-registry.ts +361 -0
- package/src/controller/prompt-injector.ts +23 -8
- package/src/controller/repo-routes.ts +91 -0
- package/src/controller/role-inference.ts +260 -22
- package/src/controller/route-table.ts +1616 -0
- package/src/controller/task-assignment.ts +618 -0
- package/src/controller/task-cleanup.ts +344 -0
- package/src/controller/task-execution.ts +356 -0
- package/src/controller/task-results.ts +544 -0
- package/src/controller/task-router.ts +98 -6
- package/src/controller/task-routes.ts +812 -0
- package/src/controller/teamauto-routes.ts +121 -0
- package/src/controller/ui-assets.ts +70 -0
- package/src/controller/websocket.ts +13 -1
- package/src/controller/worker-provisioning.ts +32 -4
- package/src/controller/worker-routes.ts +241 -0
- package/src/identity.ts +3 -2
- package/src/interaction-contracts.ts +7 -7
- package/src/openclaw-workspace.ts +44 -18
- package/src/profile-loader.ts +650 -0
- package/src/profiles/banking.json +178 -0
- package/src/profiles/crossborder-ecom.json +253 -0
- package/src/profiles/insurance.json +157 -0
- package/src/profiles/knowledge/hs-structure.md +97 -0
- package/src/profiles/knowledge/incoterms-2020.md +188 -0
- package/src/profiles/knowledge/vat-principles.md +85 -0
- package/src/profiles/schema.json +201 -0
- package/src/profiles/securities.json +137 -0
- package/src/profiles/software-rd.json +264 -0
- package/src/profiles/trading-co.json +200 -0
- package/src/prompt-policy.ts +27 -13
- package/src/role-ids.ts +31 -0
- package/src/roles.ts +60 -14
- package/src/session-roles.ts +14 -0
- package/src/state.ts +236 -9
- package/src/task-executor.ts +7 -18
- package/src/teamauto/github-client.ts +21 -0
- package/src/teamauto/repo-sync.ts +246 -6
- package/src/teamauto/scanner.ts +47 -13
- package/src/teamauto/scheduler.ts +259 -16
- package/src/teamauto/store.ts +12 -0
- package/src/types.ts +133 -16
- package/src/ui/app.js +592 -24
- package/src/ui/index.html +44 -11
- package/src/ui/style.css +194 -0
- package/src/worker/prompt-injector.ts +48 -8
- package/src/worker/skill-installer.ts +3 -1
- package/src/worker/worker-service.ts +83 -3
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { parseJsonBody, sendJson, sendError } from "../protocol.js";
|
|
2
|
+
import { getGithubAuthManager } from "./github-auth.js";
|
|
3
|
+
import { createGithubClient } from "../teamauto/github-client.js";
|
|
4
|
+
export async function handleTeamAutoActivityRequest(deps, res) {
|
|
5
|
+
const teamAuto = deps.getTeamAutoScheduler?.() ?? null;
|
|
6
|
+
if (!teamAuto) {
|
|
7
|
+
sendError(res, 503, "TeamAuto scheduler is not running");
|
|
8
|
+
return;
|
|
9
|
+
}
|
|
10
|
+
try {
|
|
11
|
+
const activity = await teamAuto.getActivity();
|
|
12
|
+
sendJson(res, 200, { activity });
|
|
13
|
+
}
|
|
14
|
+
catch (err) {
|
|
15
|
+
sendError(res, 500, err instanceof Error ? err.message : "failed to load activity");
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
export async function handleTeamAutoReposListRequest(deps, res) {
|
|
19
|
+
const teamAuto = deps.getTeamAutoScheduler?.() ?? null;
|
|
20
|
+
if (!teamAuto) {
|
|
21
|
+
sendError(res, 503, "TeamAuto scheduler is not running");
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
try {
|
|
25
|
+
sendJson(res, 200, await teamAuto.getStatus());
|
|
26
|
+
}
|
|
27
|
+
catch (err) {
|
|
28
|
+
sendError(res, 500, err instanceof Error ? err.message : "failed to read TeamAuto status");
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
// Selectable repos for the bind picker (the logged-in GitHub account's).
|
|
32
|
+
export async function handleTeamAutoRepoCandidatesRequest(deps, res) {
|
|
33
|
+
try {
|
|
34
|
+
const auth = getGithubAuthManager(deps.config, deps.logger);
|
|
35
|
+
const candidates = await createGithubClient(auth).listUserRepos();
|
|
36
|
+
sendJson(res, 200, { candidates });
|
|
37
|
+
}
|
|
38
|
+
catch (err) {
|
|
39
|
+
sendError(res, 400, err instanceof Error ? err.message : "failed to list repositories");
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
export async function handleTeamAutoRepoBindRequest(deps, req, res) {
|
|
43
|
+
const teamAuto = deps.getTeamAutoScheduler?.() ?? null;
|
|
44
|
+
if (!teamAuto) {
|
|
45
|
+
sendError(res, 503, "TeamAuto scheduler is not running");
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
let body = {};
|
|
49
|
+
try {
|
|
50
|
+
body = await parseJsonBody(req);
|
|
51
|
+
}
|
|
52
|
+
catch { /* empty body */ }
|
|
53
|
+
const repo = typeof body.repo === "string" ? body.repo : "";
|
|
54
|
+
if (!repo) {
|
|
55
|
+
sendError(res, 400, "repo (owner/name) is required");
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
try {
|
|
59
|
+
const created = await teamAuto.addRepo(repo, {
|
|
60
|
+
schedule: typeof body.schedule === "string" ? body.schedule : undefined,
|
|
61
|
+
keywordInclude: Array.isArray(body.keywordInclude) ? body.keywordInclude.filter((k) => typeof k === "string") : undefined,
|
|
62
|
+
keywordExclude: Array.isArray(body.keywordExclude) ? body.keywordExclude.filter((k) => typeof k === "string") : undefined,
|
|
63
|
+
});
|
|
64
|
+
sendJson(res, 201, created);
|
|
65
|
+
}
|
|
66
|
+
catch (err) {
|
|
67
|
+
sendError(res, 400, err instanceof Error ? err.message : "failed to bind repo");
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Per-repo actions under /api/v1/teamauto/repos/:id (DELETE unbind / PATCH
|
|
72
|
+
* update / POST :id/sweep). Returns false when the method does not match any
|
|
73
|
+
* action, leaving the request to fall through to the dispatcher's 404 exactly
|
|
74
|
+
* as the inline block did.
|
|
75
|
+
*/
|
|
76
|
+
export async function handleTeamAutoRepoItemRequest(deps, req, res, pathname) {
|
|
77
|
+
const teamAuto = deps.getTeamAutoScheduler?.() ?? null;
|
|
78
|
+
if (!teamAuto) {
|
|
79
|
+
sendError(res, 503, "TeamAuto scheduler is not running");
|
|
80
|
+
return true;
|
|
81
|
+
}
|
|
82
|
+
const repoId = decodeURIComponent(pathname.slice("/api/v1/teamauto/repos/".length).replace(/\/sweep$/, ""));
|
|
83
|
+
const isSweep = pathname.endsWith("/sweep");
|
|
84
|
+
if (req.method === "DELETE" && !isSweep) {
|
|
85
|
+
try {
|
|
86
|
+
await teamAuto.removeRepo(repoId);
|
|
87
|
+
sendJson(res, 200, { ok: true });
|
|
88
|
+
}
|
|
89
|
+
catch (err) {
|
|
90
|
+
sendError(res, 400, err instanceof Error ? err.message : "failed to unbind");
|
|
91
|
+
}
|
|
92
|
+
return true;
|
|
93
|
+
}
|
|
94
|
+
if (req.method === "PATCH" && !isSweep) {
|
|
95
|
+
let body = {};
|
|
96
|
+
try {
|
|
97
|
+
body = await parseJsonBody(req);
|
|
98
|
+
}
|
|
99
|
+
catch { /* empty */ }
|
|
100
|
+
try {
|
|
101
|
+
const updated = await teamAuto.updateRepo(repoId, {
|
|
102
|
+
schedule: typeof body.schedule === "string" ? body.schedule : undefined,
|
|
103
|
+
maxTasksPerSweep: typeof body.maxTasksPerSweep === "number" ? body.maxTasksPerSweep : undefined,
|
|
104
|
+
fullReview: body.fullReview === "off" || body.fullReview === "weekly" || body.fullReview === "daily" ? body.fullReview : undefined,
|
|
105
|
+
takeOwnership: typeof body.takeOwnership === "boolean" ? body.takeOwnership : undefined,
|
|
106
|
+
});
|
|
107
|
+
sendJson(res, 200, updated);
|
|
108
|
+
}
|
|
109
|
+
catch (err) {
|
|
110
|
+
sendError(res, 400, err instanceof Error ? err.message : "failed to update");
|
|
111
|
+
}
|
|
112
|
+
return true;
|
|
113
|
+
}
|
|
114
|
+
if (req.method === "POST" && isSweep) {
|
|
115
|
+
try {
|
|
116
|
+
sendJson(res, 200, { summary: await teamAuto.runSweepNow(repoId, true) });
|
|
117
|
+
}
|
|
118
|
+
catch (err) {
|
|
119
|
+
sendError(res, 400, err instanceof Error ? err.message : "sweep failed");
|
|
120
|
+
}
|
|
121
|
+
return true;
|
|
122
|
+
}
|
|
123
|
+
return false;
|
|
124
|
+
}
|
|
@@ -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
|
+
}
|