@teamclaws/teamclaw 2026.8.1 → 2026.11.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 (184) hide show
  1. package/cli.mjs +318 -17
  2. package/dist/index.js +54 -32
  3. package/dist/src/config.js +57 -2
  4. package/dist/src/controller/auth-routes.js +129 -0
  5. package/dist/src/controller/clarification-routes.js +315 -0
  6. package/dist/src/controller/controller-intake.js +895 -0
  7. package/dist/src/controller/controller-planning.js +814 -0
  8. package/dist/src/controller/controller-routes.js +195 -0
  9. package/dist/src/controller/controller-runs.js +175 -0
  10. package/dist/src/controller/controller-service.js +338 -50
  11. package/dist/src/controller/controller-tools.js +14 -7
  12. package/dist/src/controller/github-auth.js +2 -1
  13. package/dist/src/controller/http-server.js +290 -6003
  14. package/dist/src/controller/kickoff-orchestrator.js +33 -43
  15. package/dist/src/controller/message-delivery.js +31 -0
  16. package/dist/src/controller/message-routes.js +114 -0
  17. package/dist/src/controller/orchestration-manifest.js +11 -93
  18. package/dist/src/controller/preview-manager.js +51 -3
  19. package/dist/src/controller/preview-proxy.js +98 -0
  20. package/dist/src/controller/profile-switch.js +309 -0
  21. package/dist/src/controller/project-registry.js +294 -0
  22. package/dist/src/controller/prompt-injector.js +19 -9
  23. package/dist/src/controller/provisioning/backend-contract.js +9 -0
  24. package/dist/src/controller/provisioning/container-shared.js +64 -0
  25. package/dist/src/controller/provisioning/docker.js +214 -0
  26. package/dist/src/controller/provisioning/kubernetes.js +244 -0
  27. package/dist/src/controller/provisioning/plugin-root.js +41 -0
  28. package/dist/src/controller/provisioning/process-supervisor.js +190 -0
  29. package/dist/src/controller/provisioning-config.js +239 -0
  30. package/dist/src/controller/repo-routes.js +129 -0
  31. package/dist/src/controller/report-routes.js +56 -0
  32. package/dist/src/controller/role-inference.js +231 -20
  33. package/dist/src/controller/route-table.js +375 -0
  34. package/dist/src/controller/security.js +775 -0
  35. package/dist/src/controller/status-routes.js +287 -0
  36. package/dist/src/controller/task-assignment.js +511 -0
  37. package/dist/src/controller/task-cleanup.js +258 -0
  38. package/dist/src/controller/task-execution.js +271 -0
  39. package/dist/src/controller/task-results.js +471 -0
  40. package/dist/src/controller/task-router.js +74 -4
  41. package/dist/src/controller/task-routes.js +703 -0
  42. package/dist/src/controller/teamauto-routes.js +124 -0
  43. package/dist/src/controller/tunnel-manager.js +41 -8
  44. package/dist/src/controller/tunnel-routes.js +225 -0
  45. package/dist/src/controller/ui-assets.js +68 -0
  46. package/dist/src/controller/websocket.js +6 -2
  47. package/dist/src/controller/webui-routes.js +49 -0
  48. package/dist/src/controller/worker-provisioning.js +69 -953
  49. package/dist/src/controller/worker-routes.js +188 -0
  50. package/dist/src/controller/workflow-routes.js +407 -0
  51. package/dist/src/controller/workspace-routes.js +200 -0
  52. package/dist/src/git-collaboration.js +4 -9
  53. package/dist/src/identity.js +15 -3
  54. package/dist/src/interaction-contracts.js +7 -7
  55. package/dist/src/openclaw-workspace.js +40 -18
  56. package/dist/src/profile-loader.js +604 -0
  57. package/dist/src/profiles/banking.json +202 -0
  58. package/dist/src/profiles/crossborder-ecom.json +253 -0
  59. package/dist/src/profiles/insurance.json +157 -0
  60. package/dist/src/profiles/knowledge/hs-structure.md +97 -0
  61. package/dist/src/profiles/knowledge/incoterms-2020.md +188 -0
  62. package/dist/src/profiles/knowledge/vat-principles.md +85 -0
  63. package/dist/src/profiles/schema.json +281 -0
  64. package/dist/src/profiles/securities.json +137 -0
  65. package/dist/src/profiles/software-rd.json +264 -0
  66. package/dist/src/profiles/trading-co.json +200 -0
  67. package/dist/src/prompt-policy.js +42 -17
  68. package/dist/src/protocol.js +66 -3
  69. package/dist/src/role-ids.js +29 -0
  70. package/dist/src/roles.js +54 -13
  71. package/dist/src/session-roles.js +14 -0
  72. package/dist/src/shared/clarification-schema.js +65 -0
  73. package/dist/src/shared/github-auth.js +15 -0
  74. package/dist/src/shared/kickoff-prompt.js +37 -0
  75. package/dist/src/shared/utils.js +47 -0
  76. package/dist/src/state.js +275 -11
  77. package/dist/src/task-executor.js +7 -17
  78. package/dist/src/teamauto/github-client.js +18 -0
  79. package/dist/src/teamauto/repo-sync.js +228 -6
  80. package/dist/src/teamauto/scanner.js +40 -12
  81. package/dist/src/teamauto/scheduler.js +231 -12
  82. package/dist/src/types.js +77 -16
  83. package/dist/src/ui/app.js +1434 -82
  84. package/dist/src/ui/github-login.html +1 -0
  85. package/dist/src/ui/index.html +144 -45
  86. package/dist/src/ui/style.css +194 -0
  87. package/dist/src/worker/http-handler.js +59 -0
  88. package/dist/src/worker/prompt-injector.js +44 -8
  89. package/dist/src/worker/skill-installer.js +6 -10
  90. package/dist/src/worker/tools.js +20 -10
  91. package/dist/src/worker/worker-service.js +93 -7
  92. package/index.ts +61 -32
  93. package/openclaw.plugin.json +50 -2
  94. package/package.json +3 -2
  95. package/src/config.ts +57 -2
  96. package/src/controller/auth-routes.ts +157 -0
  97. package/src/controller/clarification-routes.ts +404 -0
  98. package/src/controller/controller-intake.ts +1113 -0
  99. package/src/controller/controller-planning.ts +1037 -0
  100. package/src/controller/controller-routes.ts +237 -0
  101. package/src/controller/controller-runs.ts +239 -0
  102. package/src/controller/controller-service.ts +422 -50
  103. package/src/controller/controller-tools.ts +16 -9
  104. package/src/controller/github-auth.ts +28 -63
  105. package/src/controller/http-server.ts +336 -6964
  106. package/src/controller/kickoff-orchestrator.ts +69 -45
  107. package/src/controller/message-delivery.ts +52 -0
  108. package/src/controller/message-routes.ts +137 -0
  109. package/src/controller/orchestration-manifest.ts +14 -100
  110. package/src/controller/preview-manager.ts +53 -3
  111. package/src/controller/preview-proxy.ts +127 -0
  112. package/src/controller/profile-switch.ts +396 -0
  113. package/src/controller/project-registry.ts +361 -0
  114. package/src/controller/prompt-injector.ts +23 -8
  115. package/src/controller/provisioning/backend-contract.ts +51 -0
  116. package/src/controller/provisioning/container-shared.ts +84 -0
  117. package/src/controller/provisioning/docker.ts +260 -0
  118. package/src/controller/provisioning/kubernetes.ts +263 -0
  119. package/src/controller/provisioning/plugin-root.ts +42 -0
  120. package/src/controller/provisioning/process-supervisor.ts +214 -0
  121. package/src/controller/provisioning-config.ts +289 -0
  122. package/src/controller/repo-routes.ts +163 -0
  123. package/src/controller/report-routes.ts +64 -0
  124. package/src/controller/role-inference.ts +260 -22
  125. package/src/controller/route-table.ts +597 -0
  126. package/src/controller/security.ts +899 -0
  127. package/src/controller/status-routes.ts +354 -0
  128. package/src/controller/task-assignment.ts +622 -0
  129. package/src/controller/task-cleanup.ts +344 -0
  130. package/src/controller/task-execution.ts +399 -0
  131. package/src/controller/task-results.ts +556 -0
  132. package/src/controller/task-router.ts +98 -6
  133. package/src/controller/task-routes.ts +812 -0
  134. package/src/controller/teamauto-routes.ts +121 -0
  135. package/src/controller/tunnel-manager.ts +45 -8
  136. package/src/controller/tunnel-routes.ts +231 -0
  137. package/src/controller/ui-assets.ts +70 -0
  138. package/src/controller/websocket.ts +32 -4
  139. package/src/controller/webui-routes.ts +55 -0
  140. package/src/controller/worker-provisioning.ts +83 -1121
  141. package/src/controller/worker-routes.ts +241 -0
  142. package/src/controller/workflow-routes.ts +498 -0
  143. package/src/controller/workspace-routes.ts +222 -0
  144. package/src/git-collaboration.ts +4 -9
  145. package/src/identity.ts +16 -3
  146. package/src/interaction-contracts.ts +7 -7
  147. package/src/openclaw-workspace.ts +44 -18
  148. package/src/profile-loader.ts +816 -0
  149. package/src/profiles/banking.json +202 -0
  150. package/src/profiles/crossborder-ecom.json +253 -0
  151. package/src/profiles/insurance.json +157 -0
  152. package/src/profiles/knowledge/hs-structure.md +97 -0
  153. package/src/profiles/knowledge/incoterms-2020.md +188 -0
  154. package/src/profiles/knowledge/vat-principles.md +85 -0
  155. package/src/profiles/schema.json +281 -0
  156. package/src/profiles/securities.json +137 -0
  157. package/src/profiles/software-rd.json +264 -0
  158. package/src/profiles/trading-co.json +200 -0
  159. package/src/prompt-policy.ts +44 -17
  160. package/src/protocol.ts +72 -2
  161. package/src/role-ids.ts +31 -0
  162. package/src/roles.ts +60 -14
  163. package/src/session-roles.ts +14 -0
  164. package/src/shared/clarification-schema.ts +81 -0
  165. package/src/shared/github-auth.ts +92 -0
  166. package/src/shared/kickoff-prompt.ts +47 -0
  167. package/src/shared/utils.ts +51 -0
  168. package/src/state.ts +326 -10
  169. package/src/task-executor.ts +7 -18
  170. package/src/teamauto/github-client.ts +23 -1
  171. package/src/teamauto/repo-sync.ts +248 -7
  172. package/src/teamauto/scanner.ts +47 -13
  173. package/src/teamauto/scheduler.ts +261 -17
  174. package/src/teamauto/store.ts +12 -0
  175. package/src/types.ts +263 -17
  176. package/src/ui/app.js +1434 -82
  177. package/src/ui/github-login.html +1 -0
  178. package/src/ui/index.html +144 -45
  179. package/src/ui/style.css +194 -0
  180. package/src/worker/http-handler.ts +64 -1
  181. package/src/worker/prompt-injector.ts +48 -8
  182. package/src/worker/skill-installer.ts +6 -10
  183. package/src/worker/tools.ts +21 -10
  184. package/src/worker/worker-service.ts +101 -7
@@ -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
+ }
@@ -4,8 +4,9 @@ import fs from "node:fs";
4
4
  import https from "node:https";
5
5
  import os from "node:os";
6
6
  import path from "node:path";
7
+ import { getGithubAuthManager } from "./github-auth.js";
7
8
  const TUNNEL_API_HOST = "apps.teamclaw.dev";
8
- async function tunnelFetch(pathq, method, body) {
9
+ async function tunnelFetch(pathq, method, body, headers) {
9
10
  const ip = await new Promise((resolve, reject) => {
10
11
  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
12
  let d = "";
@@ -25,7 +26,7 @@ async function tunnelFetch(pathq, method, body) {
25
26
  });
26
27
  return new Promise((resolve, reject) => {
27
28
  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
+ const req = https.request({ host: ip, servername: TUNNEL_API_HOST, path: `/api${pathq}`, method, headers: { host: TUNNEL_API_HOST, "Content-Type": "application/json", ...(headers ?? {}), ...(payload ? { "Content-Length": Buffer.byteLength(payload) } : {}) } }, (res) => {
29
30
  let d = "";
30
31
  res.on("data", (c) => (d += c));
31
32
  res.on("end", () => { try {
@@ -180,7 +181,10 @@ export function createTunnelManager(deps) {
180
181
  let startOp = { running: false, phase: "idle", detail: null };
181
182
  let installState = { running: false, phase: "idle", percent: null, detail: null };
182
183
  function isTunnelRequest(hostHeader) {
183
- return Boolean(hostHeader && hostHeader.toLowerCase().endsWith(TUNNEL_HOST_SUFFIX));
184
+ // #255 P1-5: quick tunnels (*.trycloudflare.com) are internet-reachable
185
+ // too, so they join the same gate enforcement as *.teamclaw.dev.
186
+ const host = hostHeader?.toLowerCase() ?? "";
187
+ return host.endsWith(TUNNEL_HOST_SUFFIX) || host.endsWith(".trycloudflare.com");
184
188
  }
185
189
  function gateAllows(req) {
186
190
  if (!handle)
@@ -210,8 +214,31 @@ export function createTunnelManager(deps) {
210
214
  const bin = findCloudflared();
211
215
  if (!bin)
212
216
  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 });
217
+ // Issue #237 W3: the gate token guards an internet-reachable verify
218
+ // endpoint, so it must carry real entropy - 16 random bytes kept as
219
+ // base64url (22 case-sensitive chars = the full 128 bits). The retired
220
+ // 8-char form collapsed to ~41 effective bits and was online-guessable;
221
+ // the gate cookie stays a sha256 derivation of the token, so a longer
222
+ // token does not weaken the cookie.
223
+ const gateToken = randomBytes(16).toString("base64url");
224
+ // Issue #231: prove github_user ownership to the relay. The managed-start
225
+ // route already refuses anonymous starts ("GitHub login required"), so the
226
+ // OAuth token behind that login is obtainable here via the shared auth
227
+ // manager — the empty config resolves to the same default clientId (and
228
+ // therefore the same cached manager instance) the routes use, and the
229
+ // token store lives in the state dir regardless of config. If no token
230
+ // can be resolved (signed out between the route's check and here), the
231
+ // header is omitted: legal while the relay's ACCEPT_LEGACY_CREATE grey
232
+ // window is open; once the relay tightens, its 401 surfaces as the
233
+ // create error instead of a silent squat.
234
+ let githubToken = null;
235
+ try {
236
+ githubToken = await getGithubAuthManager({}, logger).getAccessToken();
237
+ }
238
+ catch {
239
+ githubToken = null; // not signed in / token unavailable -> legacy headerless create
240
+ }
241
+ const res = await tunnelFetch("/tunnels", "POST", { github_user: githubUser, local_port: deps.localPort }, githubToken ? { Authorization: `Bearer ${githubToken}` } : undefined);
215
242
  const body = res.json;
216
243
  if (res.status !== 201 || !body.tunnel_id || !body.connector_token || !body.hostname) {
217
244
  throw new Error(body.error ?? `tunnel server responded ${res.status}`);
@@ -255,8 +282,12 @@ export function createTunnelManager(deps) {
255
282
  /** Anonymous one-off tunnel: `cloudflared tunnel --url`, no Cloudflare
256
283
  * account, no token, no platform server. Cloudflare assigns a random
257
284
  * 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. */
285
+ * it is NOT recovered on restart and must not be treated as stable.
286
+ * #255 P1-5: the quick URL is internet-reachable, so it now gets the SAME
287
+ * per-launch gate token as managed tunnels (cookie-gated by the shared
288
+ * http-server enforcement point). The token is deliberately NOT
289
+ * persisted: quick tunnels have no recovery, and a token that dies with
290
+ * the process is strictly safer than one saved to disk. */
260
291
  function startQuick() {
261
292
  if (handle && child)
262
293
  return { launched: true, error: null };
@@ -271,7 +302,9 @@ export function createTunnelManager(deps) {
271
302
  env: { ...process.env, HOME: tunnelRuntimeHome() },
272
303
  });
273
304
  child = proc;
274
- handle = { tunnelId: "quick", hostname: "", gateToken: "", deleteToken: "" };
305
+ // #255 P1-5: same entropy class as the managed gate token (16 CSPRNG
306
+ // bytes, base64url) - the cookie check gates on it via gateAllows().
307
+ handle = { tunnelId: "quick", hostname: "", gateToken: randomBytes(16).toString("base64url"), deleteToken: "" };
275
308
  lastError = null;
276
309
  // The trycloudflare.com URL appears on stderr once the edge assigns it.
277
310
  let announced = false;
@@ -0,0 +1,225 @@
1
+ import { sendJson, sendError } from "../protocol.js";
2
+ import { getGithubAuthManager } from "./github-auth.js";
3
+ import { gatePageHtml, computeGateCookie, GATE_COOKIE_NAME, selfHostedTokenFromEnv } from "./tunnel-manager.js";
4
+ import { isLanIp, isProtectionOn, secretsEqual } from "./security.js";
5
+ async function readFormBody(request) {
6
+ const chunks = [];
7
+ for await (const chunk of request)
8
+ chunks.push(chunk);
9
+ const raw = Buffer.concat(chunks).toString("utf8");
10
+ const out = {};
11
+ for (const [k, v] of new URLSearchParams(raw))
12
+ out[k] = v;
13
+ return out;
14
+ }
15
+ // ===========================================================================
16
+ // Tunnel-side route tables (pre-PR-D http-server.ts lines 348-432, the
17
+ // outer server callback's tunnel branch). These run BEFORE handleRequest
18
+ // and are split exactly along the old viaTunnel if/else:
19
+ // - viaTunnel: the gate page routes answer; every other tunnel request
20
+ // must pass the gate cookie (403 gate page), then continues to the
21
+ // controller route table;
22
+ // - direct (non-tunnel): the tunnel management API answers, everything
23
+ // else continues to the controller route table.
24
+ // ===========================================================================
25
+ // Issue #237 W3: online-guessing throttle for POST /__tunnel_gate/verify.
26
+ // The endpoint answers on the PUBLIC tunnel URL, so repeated failures cool
27
+ // the gate down. Deliberately GLOBAL (not per-IP): every via-tunnel request
28
+ // arrives from the local cloudflared socket, so a per-IP key would collapse
29
+ // to one bucket for the whole internet anyway - this mirrors the pairing
30
+ // code throttle in security.ts (timestamps pruned against a sliding window).
31
+ const GATE_VERIFY_FAILURE_MAX = 10;
32
+ const GATE_VERIFY_COOLDOWN_MS = 60_000;
33
+ const gateVerifyFailures = [];
34
+ function gateVerifyThrottled() {
35
+ const now = Date.now();
36
+ while (gateVerifyFailures.length > 0 && now - gateVerifyFailures[0] >= GATE_VERIFY_COOLDOWN_MS) {
37
+ gateVerifyFailures.shift();
38
+ }
39
+ return gateVerifyFailures.length >= GATE_VERIFY_FAILURE_MAX;
40
+ }
41
+ function recordGateVerifyFailure() {
42
+ gateVerifyFailures.push(Date.now());
43
+ }
44
+ /** GET /__tunnel_gate + GET / + POST /__tunnel_gate/verify (via tunnel only). */
45
+ export function createTunnelGateRoutes(tunnelManager) {
46
+ return [
47
+ {
48
+ method: "GET",
49
+ path: "/__tunnel_gate",
50
+ handler: ({ res, req }) => {
51
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
52
+ res.end(gatePageHtml(String(req.headers.host), false));
53
+ },
54
+ },
55
+ {
56
+ // Valid gate cookie on "/" goes straight to the dashboard; the gate
57
+ // page only greets visitors who have not authenticated yet.
58
+ method: "GET",
59
+ path: "/",
60
+ handler: ({ res, req, pathname }) => {
61
+ if (pathname === "/" && tunnelManager.gateAllows(req)) {
62
+ res.writeHead(302, { Location: "/ui/" });
63
+ res.end();
64
+ return;
65
+ }
66
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
67
+ res.end(gatePageHtml(String(req.headers.host), false));
68
+ },
69
+ },
70
+ {
71
+ method: "POST",
72
+ path: "/__tunnel_gate/verify",
73
+ handler: async ({ res, req }) => {
74
+ // Issue #237 W3: check the throttle BEFORE touching the token - a
75
+ // cooled-down gate answers 429 without comparing anything, so
76
+ // brute-force attempts cannot outrun the cooldown.
77
+ if (gateVerifyThrottled()) {
78
+ res.setHeader("Retry-After", "60");
79
+ sendJson(res, 429, { error: "Too many gate verification attempts. Wait a minute and try again." });
80
+ return;
81
+ }
82
+ const form = await readFormBody(req);
83
+ // Issue #237 W3: gate tokens are 128-bit base64url and therefore
84
+ // case-sensitive - only surrounding whitespace is normalized (the
85
+ // old .toUpperCase() fold belonged to the retired 8-char token).
86
+ const submitted = String(form.token ?? "").trim();
87
+ const st = tunnelManager.status();
88
+ // Issue #237 W3: constant-time comparison (plain === was
89
+ // timing-leaky on this internet-reachable endpoint).
90
+ if (st.active && st.gateToken && secretsEqual(submitted, st.gateToken)) {
91
+ const cookie = `${GATE_COOKIE_NAME}=${computeGateCookie(st.gateToken, st.tunnelId ?? "")}; Path=/; Max-Age=43200; HttpOnly; SameSite=Lax`;
92
+ res.writeHead(302, { "Set-Cookie": cookie, Location: "/" });
93
+ res.end();
94
+ return;
95
+ }
96
+ recordGateVerifyFailure();
97
+ res.writeHead(403, { "Content-Type": "text/html; charset=utf-8" });
98
+ res.end(gatePageHtml(String(req.headers.host), true));
99
+ },
100
+ },
101
+ ];
102
+ }
103
+ /** /api/v1/tunnel/* management API (direct requests only, never via tunnel). */
104
+ export function createTunnelManagementRoutes(tunnelManager, deps) {
105
+ const { config, logger } = deps;
106
+ // Issue #222 (coordinated scope): creating a public tunnel is an
107
+ // internet-EXPOSURE escalation, so in L0 (protection off) the three start
108
+ // endpoints accept only loopback/LAN origins - a public-network peer that
109
+ // merely reached the port must never be able to open a share URL into
110
+ // this controller. While protection is on, the device gate in
111
+ // http-server.ts has already authenticated the caller (#23) and stays the
112
+ // governing rule: a deliberately paired device may share, including
113
+ // remotely. Loopback/LAN classification reuses the security module's
114
+ // isLanIp (via-tunnel requests never reach this table - they dispatch to
115
+ // the gate table instead - so the raw socket peer is authoritative).
116
+ const tunnelStartAllowedFrom = (req, res) => {
117
+ if (isProtectionOn(deps.getTeamState())) {
118
+ return true;
119
+ }
120
+ if (isLanIp(req.socket.remoteAddress)) {
121
+ return true;
122
+ }
123
+ sendJson(res, 403, {
124
+ error: "forbidden",
125
+ hint: "Creating a public tunnel exposes this controller to the internet. Start tunnels from the controller host (loopback or LAN), or enable device pairing (POST /api/v1/security/enable from the controller host) and share from a paired device.",
126
+ });
127
+ return false;
128
+ };
129
+ return [
130
+ {
131
+ method: "GET",
132
+ path: "/api/v1/tunnel/status",
133
+ handler: ({ res }) => {
134
+ sendJson(res, 200, tunnelManager.status());
135
+ },
136
+ },
137
+ {
138
+ method: "POST",
139
+ path: "/api/v1/tunnel/start",
140
+ handler: async ({ req, res }) => {
141
+ if (!tunnelStartAllowedFrom(req, res)) {
142
+ return;
143
+ }
144
+ const authStatus = await getGithubAuthManager(config, logger).getStatus();
145
+ const account = authStatus.account;
146
+ if (!account?.login) {
147
+ sendError(res, 401, "GitHub login required to share a tunnel");
148
+ return;
149
+ }
150
+ // Async launch: poll /tunnel/status for phase progress and the
151
+ // resulting hostname/gateToken once startOp.phase === "done".
152
+ const launched = tunnelManager.start(account.login);
153
+ sendJson(res, 202, { launched, status: tunnelManager.status() });
154
+ },
155
+ },
156
+ {
157
+ // Self-hosted: user-owned Cloudflare tunnel via connector token (no
158
+ // GitHub login, no platform tunnel server). Token from the request
159
+ // body, or the TEAMCLAW_TUNNEL_TOKEN env injection when body is empty.
160
+ method: "POST",
161
+ path: "/api/v1/tunnel/start-self-hosted",
162
+ handler: async ({ req, res }) => {
163
+ if (!tunnelStartAllowedFrom(req, res)) {
164
+ return;
165
+ }
166
+ let token = "";
167
+ try {
168
+ const body = await readFormBody(req);
169
+ token = String(body.token ?? "");
170
+ }
171
+ catch { /* fall through to env */ }
172
+ if (!token.trim()) {
173
+ const envToken = selfHostedTokenFromEnv();
174
+ if (!envToken) {
175
+ sendError(res, 400, "connector token required (or set TEAMCLAW_TUNNEL_TOKEN)");
176
+ return;
177
+ }
178
+ token = envToken;
179
+ }
180
+ const r = tunnelManager.startSelfHosted(token);
181
+ if (!r.launched) {
182
+ sendError(res, 400, r.error ?? "failed to start self-hosted tunnel");
183
+ return;
184
+ }
185
+ sendJson(res, 202, { launched: true, status: tunnelManager.status() });
186
+ },
187
+ },
188
+ {
189
+ method: "POST",
190
+ path: "/api/v1/tunnel/start-quick",
191
+ handler: ({ req, res }) => {
192
+ if (!tunnelStartAllowedFrom(req, res)) {
193
+ return;
194
+ }
195
+ const r = tunnelManager.startQuick();
196
+ if (!r.launched) {
197
+ sendError(res, 400, r.error ?? "failed to start quick tunnel");
198
+ return;
199
+ }
200
+ sendJson(res, 202, { launched: true, status: tunnelManager.status() });
201
+ },
202
+ },
203
+ {
204
+ method: "POST",
205
+ path: "/api/v1/tunnel/stop",
206
+ handler: async ({ res }) => {
207
+ await tunnelManager.stop();
208
+ sendJson(res, 200, tunnelManager.status());
209
+ },
210
+ },
211
+ {
212
+ method: "POST",
213
+ path: "/api/v1/tunnel/install-cloudflared",
214
+ handler: async ({ res }) => {
215
+ try {
216
+ const result = await tunnelManager.installCloudflared();
217
+ sendJson(res, result.ok ? 200 : 500, { ...result, status: tunnelManager.status() });
218
+ }
219
+ catch (err) {
220
+ sendError(res, 500, err instanceof Error ? err.message : "install failed");
221
+ }
222
+ },
223
+ },
224
+ ];
225
+ }
@@ -0,0 +1,68 @@
1
+ // PR-A of issue #204 (http-server monolith split): static web UI asset
2
+ // serving extracted verbatim from controller/http-server.ts. Zero behavior
3
+ // change - the route shells in http-server call these functions unchanged.
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+ import { createHash } from "node:crypto";
7
+ import { sendError } from "../protocol.js";
8
+ // Tunnel/CDN caches rewrite the origin's Cache-Control: no-cache into a long
9
+ // browser freeze for cacheable extensions like .js (observed: Cloudflare
10
+ // Browser Cache TTL max-age=14400 on tunneled UI assets). A UI update then
11
+ // never reaches visitors through the tunnel. Serving content-versioned URLs
12
+ // (?v=<hash>) makes every UI deploy a URL no browser or edge has ever seen,
13
+ // so stale-cache behavior cannot recur.
14
+ const uiAssetVersionCache = new Map();
15
+ function uiAssetVersion(uiPath, file) {
16
+ const full = path.join(uiPath, file);
17
+ try {
18
+ const mtimeMs = fs.statSync(full).mtimeMs;
19
+ const cached = uiAssetVersionCache.get(full);
20
+ if (cached && cached.mtimeMs === mtimeMs)
21
+ return cached.version;
22
+ const version = createHash("sha1").update(fs.readFileSync(full)).digest("hex").slice(0, 10);
23
+ uiAssetVersionCache.set(full, { mtimeMs, version });
24
+ return version;
25
+ }
26
+ catch {
27
+ return String(Date.now()); // unreadable asset: bust for this request
28
+ }
29
+ }
30
+ const UI_HTML_ASSET_REFS = [
31
+ "/ui/style.css",
32
+ "/ui/app.js",
33
+ "/ui/assets/teamclaw-app-icon.png",
34
+ ];
35
+ export function serveVersionedHtml(res, htmlPath) {
36
+ try {
37
+ const uiPath = path.dirname(htmlPath);
38
+ let html = fs.readFileSync(htmlPath, "utf8");
39
+ for (const ref of UI_HTML_ASSET_REFS) {
40
+ html = html.split(`"${ref}"`).join(`"${ref}?v=${uiAssetVersion(uiPath, ref.slice("/ui/".length))}"`);
41
+ }
42
+ res.writeHead(200, {
43
+ "Content-Type": "text/html; charset=utf-8",
44
+ "Access-Control-Allow-Origin": "*",
45
+ "Cache-Control": "no-cache",
46
+ });
47
+ res.end(html);
48
+ }
49
+ catch {
50
+ sendError(res, 404, "File not found");
51
+ }
52
+ }
53
+ export function serveStaticFile(res, filePath, contentType) {
54
+ try {
55
+ const content = fs.readFileSync(filePath);
56
+ res.writeHead(200, {
57
+ "Content-Type": contentType,
58
+ "Access-Control-Allow-Origin": "*",
59
+ // UI assets change with every plugin deploy on a localhost controller;
60
+ // always revalidate so browsers never stick to a stale app.js.
61
+ "Cache-Control": "no-cache",
62
+ });
63
+ res.end(content);
64
+ }
65
+ catch {
66
+ sendError(res, 404, "File not found");
67
+ }
68
+ }
@@ -5,8 +5,12 @@ export class TeamWebSocketServer {
5
5
  constructor(logger) {
6
6
  this.logger = logger;
7
7
  }
8
- attach(server) {
9
- this.wss = new WebSocketServer({ server, path: "/ws" });
8
+ attach(server, options) {
9
+ this.wss = new WebSocketServer({
10
+ server,
11
+ path: "/ws",
12
+ ...(options?.verifyUpgrade ? { verifyClient: (info) => options.verifyUpgrade(info.req) } : {}),
13
+ });
10
14
  this.wss.on("connection", (ws) => {
11
15
  this.logger.info("WebSocket: client connected");
12
16
  ws.on("close", () => {
@@ -0,0 +1,49 @@
1
+ // Issue #226 W2 (route-table carve-up): the Web UI static-serving handlers
2
+ // moved verbatim from route-table.ts (PR-D had moved them verbatim from
3
+ // http-server.ts before that) - bodies byte-identical, only the module home
4
+ // changed. route-table.ts keeps the table entries that bind these handlers.
5
+ // Like security.ts, this module imports route-table.js as TYPE ONLY
6
+ // (RouteContext), so the module graph stays acyclic.
7
+ import path from "node:path";
8
+ import { serveStaticFile, serveVersionedHtml } from "./ui-assets.js";
9
+ function webUiRootRoute(ctx) {
10
+ const { res } = ctx;
11
+ res.statusCode = 302;
12
+ res.setHeader("Location", "/ui");
13
+ res.end();
14
+ }
15
+ function webUiIndexRoute(ctx) {
16
+ const { res } = ctx;
17
+ const uiPath = path.join(import.meta.dirname, "..", "ui");
18
+ serveVersionedHtml(res, path.join(uiPath, "index.html"));
19
+ }
20
+ // Standalone GitHub device-login page (big user code + prefilled link + polling).
21
+ function webUiGithubLoginPageRoute(ctx) {
22
+ const { res } = ctx;
23
+ const uiPath = path.join(import.meta.dirname, "..", "ui");
24
+ serveStaticFile(res, path.join(uiPath, "github-login.html"), "text/html; charset=utf-8");
25
+ }
26
+ function webUiAssetsRoute(ctx) {
27
+ const { res, pathname } = ctx;
28
+ const uiPath = path.join(import.meta.dirname, "..", "ui");
29
+ const file = pathname.slice(4); // remove "/ui/"
30
+ if (file.endsWith(".css")) {
31
+ serveStaticFile(res, path.join(uiPath, file), "text/css; charset=utf-8");
32
+ }
33
+ else if (file.endsWith(".js")) {
34
+ serveStaticFile(res, path.join(uiPath, file), "application/javascript; charset=utf-8");
35
+ }
36
+ else if (file.endsWith(".png")) {
37
+ serveStaticFile(res, path.join(uiPath, file), "image/png");
38
+ }
39
+ else if (file.endsWith(".svg")) {
40
+ serveStaticFile(res, path.join(uiPath, file), "image/svg+xml; charset=utf-8");
41
+ }
42
+ else if (file.endsWith(".ico")) {
43
+ serveStaticFile(res, path.join(uiPath, file), "image/x-icon");
44
+ }
45
+ else {
46
+ serveStaticFile(res, path.join(uiPath, file), "application/octet-stream");
47
+ }
48
+ }
49
+ export { webUiRootRoute, webUiIndexRoute, webUiGithubLoginPageRoute, webUiAssetsRoute, };