@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,121 @@
1
+ // PR-B of issue #204 (http-server monolith split): the TeamAuto route
2
+ // handlers extracted verbatim from controller/http-server.ts. Zero behavior
3
+ // change - the route shells in http-server keep the method+pathname matches
4
+ // and call these functions with the same deps object as before. This module
5
+ // must NEVER import http-server (the reverse edge exists:
6
+ // http-server -> teamauto-routes); the scheduler and the GitHub auth manager
7
+ // arrive through the deps slice and direct peer imports below.
8
+ import type { IncomingMessage, ServerResponse } from "node:http";
9
+ import type { PluginLogger } from "../../api.js";
10
+ import type { PluginConfig } from "../types.js";
11
+ import { parseJsonBody, sendJson, sendError } from "../protocol.js";
12
+ import { getGithubAuthManager } from "./github-auth.js";
13
+ import { createGithubClient } from "../teamauto/github-client.js";
14
+ import type { TeamAutoScheduler } from "../teamauto/scheduler.js";
15
+
16
+ /**
17
+ * Structural slice of ControllerHttpDeps (http-server.ts) covering exactly
18
+ * the fields the TeamAuto route handlers read. http-server keeps passing its
19
+ * full ControllerHttpDeps object; TypeScript structural typing accepts it,
20
+ * so no call site changes beyond the import path.
21
+ */
22
+ export type TeamAutoRouteDeps = {
23
+ config: PluginConfig;
24
+ logger: PluginLogger;
25
+ /** Late-bound TeamAuto scheduler (autonomous repo collaboration). */
26
+ getTeamAutoScheduler?: () => TeamAutoScheduler | null;
27
+ };
28
+
29
+ export async function handleTeamAutoActivityRequest(deps: TeamAutoRouteDeps, res: ServerResponse): Promise<void> {
30
+ const teamAuto = deps.getTeamAutoScheduler?.() ?? null;
31
+ if (!teamAuto) { sendError(res, 503, "TeamAuto scheduler is not running"); return; }
32
+ try {
33
+ const activity = await teamAuto.getActivity();
34
+ sendJson(res, 200, { activity });
35
+ } catch (err) {
36
+ sendError(res, 500, err instanceof Error ? err.message : "failed to load activity");
37
+ }
38
+ }
39
+
40
+ export async function handleTeamAutoReposListRequest(deps: TeamAutoRouteDeps, res: ServerResponse): Promise<void> {
41
+ const teamAuto = deps.getTeamAutoScheduler?.() ?? null;
42
+ if (!teamAuto) { sendError(res, 503, "TeamAuto scheduler is not running"); return; }
43
+ try {
44
+ sendJson(res, 200, await teamAuto.getStatus());
45
+ } catch (err) {
46
+ sendError(res, 500, err instanceof Error ? err.message : "failed to read TeamAuto status");
47
+ }
48
+ }
49
+
50
+ // Selectable repos for the bind picker (the logged-in GitHub account's).
51
+ export async function handleTeamAutoRepoCandidatesRequest(deps: TeamAutoRouteDeps, res: ServerResponse): Promise<void> {
52
+ try {
53
+ const auth = getGithubAuthManager(deps.config, deps.logger);
54
+ const candidates = await createGithubClient(auth).listUserRepos();
55
+ sendJson(res, 200, { candidates });
56
+ } catch (err) {
57
+ sendError(res, 400, err instanceof Error ? err.message : "failed to list repositories");
58
+ }
59
+ }
60
+
61
+ export async function handleTeamAutoRepoBindRequest(deps: TeamAutoRouteDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
62
+ const teamAuto = deps.getTeamAutoScheduler?.() ?? null;
63
+ if (!teamAuto) { sendError(res, 503, "TeamAuto scheduler is not running"); return; }
64
+ let body: Record<string, unknown> = {};
65
+ try { body = await parseJsonBody(req); } catch { /* empty body */ }
66
+ const repo = typeof body.repo === "string" ? body.repo : "";
67
+ if (!repo) { sendError(res, 400, "repo (owner/name) is required"); return; }
68
+ try {
69
+ const created = await teamAuto.addRepo(repo, {
70
+ schedule: typeof body.schedule === "string" ? body.schedule : undefined,
71
+ keywordInclude: Array.isArray(body.keywordInclude) ? body.keywordInclude.filter((k): k is string => typeof k === "string") : undefined,
72
+ keywordExclude: Array.isArray(body.keywordExclude) ? body.keywordExclude.filter((k): k is string => typeof k === "string") : undefined,
73
+ });
74
+ sendJson(res, 201, created);
75
+ } catch (err) {
76
+ sendError(res, 400, err instanceof Error ? err.message : "failed to bind repo");
77
+ }
78
+ }
79
+
80
+ /**
81
+ * Per-repo actions under /api/v1/teamauto/repos/:id (DELETE unbind / PATCH
82
+ * update / POST :id/sweep). Returns false when the method does not match any
83
+ * action, leaving the request to fall through to the dispatcher's 404 exactly
84
+ * as the inline block did.
85
+ */
86
+ export async function handleTeamAutoRepoItemRequest(
87
+ deps: TeamAutoRouteDeps,
88
+ req: IncomingMessage,
89
+ res: ServerResponse,
90
+ pathname: string,
91
+ ): Promise<boolean> {
92
+ const teamAuto = deps.getTeamAutoScheduler?.() ?? null;
93
+ if (!teamAuto) { sendError(res, 503, "TeamAuto scheduler is not running"); return true; }
94
+ const repoId = decodeURIComponent(pathname.slice("/api/v1/teamauto/repos/".length).replace(/\/sweep$/, ""));
95
+ const isSweep = pathname.endsWith("/sweep");
96
+ if (req.method === "DELETE" && !isSweep) {
97
+ try { await teamAuto.removeRepo(repoId); sendJson(res, 200, { ok: true }); }
98
+ catch (err) { sendError(res, 400, err instanceof Error ? err.message : "failed to unbind"); }
99
+ return true;
100
+ }
101
+ if (req.method === "PATCH" && !isSweep) {
102
+ let body: Record<string, unknown> = {};
103
+ try { body = await parseJsonBody(req); } catch { /* empty */ }
104
+ try {
105
+ const updated = await teamAuto.updateRepo(repoId, {
106
+ schedule: typeof body.schedule === "string" ? body.schedule : undefined,
107
+ maxTasksPerSweep: typeof body.maxTasksPerSweep === "number" ? body.maxTasksPerSweep : undefined,
108
+ fullReview: body.fullReview === "off" || body.fullReview === "weekly" || body.fullReview === "daily" ? body.fullReview : undefined,
109
+ takeOwnership: typeof body.takeOwnership === "boolean" ? body.takeOwnership : undefined,
110
+ });
111
+ sendJson(res, 200, updated);
112
+ } catch (err) { sendError(res, 400, err instanceof Error ? err.message : "failed to update"); }
113
+ return true;
114
+ }
115
+ if (req.method === "POST" && isSweep) {
116
+ try { sendJson(res, 200, { summary: await teamAuto.runSweepNow(repoId, true) }); }
117
+ catch (err) { sendError(res, 400, err instanceof Error ? err.message : "sweep failed"); }
118
+ return true;
119
+ }
120
+ return false;
121
+ }
@@ -5,9 +5,10 @@ import type { PluginLogger } from "../../api.js";
5
5
  import https from "node:https";
6
6
  import os from "node:os";
7
7
  import path from "node:path";
8
+ import { getGithubAuthManager } from "./github-auth.js";
8
9
 
9
10
  const TUNNEL_API_HOST = "apps.teamclaw.dev";
10
- async function tunnelFetch(pathq: string, method: "POST" | "DELETE", body?: unknown): Promise<{ status: number; json: any }> {
11
+ async function tunnelFetch(pathq: string, method: "POST" | "DELETE", body?: unknown, headers?: Record<string, string>): Promise<{ status: number; json: any }> {
11
12
  const ip = await new Promise<string>((resolve, reject) => {
12
13
  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
14
  let d = ""; res.on("data", (c: Buffer) => (d += c)); res.on("end", () => {
@@ -18,7 +19,7 @@ async function tunnelFetch(pathq: string, method: "POST" | "DELETE", body?: unkn
18
19
  });
19
20
  return new Promise((resolve, reject) => {
20
21
  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
+ 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) } : {}) } } as never, (res: import("node:http").IncomingMessage) => {
22
23
  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
  });
24
25
  req.on("error", reject);
@@ -206,7 +207,10 @@ export function createTunnelManager(deps: { logger: PluginLogger; localPort: num
206
207
  let installState: { running: boolean; phase: string; percent: number | null; detail: string | null } = { running: false, phase: "idle", percent: null, detail: null };
207
208
 
208
209
  function isTunnelRequest(hostHeader: string | undefined): boolean {
209
- return Boolean(hostHeader && hostHeader.toLowerCase().endsWith(TUNNEL_HOST_SUFFIX));
210
+ // #255 P1-5: quick tunnels (*.trycloudflare.com) are internet-reachable
211
+ // too, so they join the same gate enforcement as *.teamclaw.dev.
212
+ const host = hostHeader?.toLowerCase() ?? "";
213
+ return host.endsWith(TUNNEL_HOST_SUFFIX) || host.endsWith(".trycloudflare.com");
210
214
  }
211
215
 
212
216
  function gateAllows(req: { headers: Record<string, unknown> }): boolean {
@@ -234,8 +238,35 @@ export function createTunnelManager(deps: { logger: PluginLogger; localPort: num
234
238
  if (handle && child) return handle;
235
239
  const bin = findCloudflared();
236
240
  if (!bin) throw new Error("cloudflared not found (brew install cloudflared)");
237
- const gateToken = randomBytes(6).toString("base64url").replace(/[-_]/g, "").slice(0, 8).toUpperCase();
238
- const res = await tunnelFetch("/tunnels", "POST", { github_user: githubUser, local_port: deps.localPort });
241
+ // Issue #237 W3: the gate token guards an internet-reachable verify
242
+ // endpoint, so it must carry real entropy - 16 random bytes kept as
243
+ // base64url (22 case-sensitive chars = the full 128 bits). The retired
244
+ // 8-char form collapsed to ~41 effective bits and was online-guessable;
245
+ // the gate cookie stays a sha256 derivation of the token, so a longer
246
+ // token does not weaken the cookie.
247
+ const gateToken = randomBytes(16).toString("base64url");
248
+ // Issue #231: prove github_user ownership to the relay. The managed-start
249
+ // route already refuses anonymous starts ("GitHub login required"), so the
250
+ // OAuth token behind that login is obtainable here via the shared auth
251
+ // manager — the empty config resolves to the same default clientId (and
252
+ // therefore the same cached manager instance) the routes use, and the
253
+ // token store lives in the state dir regardless of config. If no token
254
+ // can be resolved (signed out between the route's check and here), the
255
+ // header is omitted: legal while the relay's ACCEPT_LEGACY_CREATE grey
256
+ // window is open; once the relay tightens, its 401 surfaces as the
257
+ // create error instead of a silent squat.
258
+ let githubToken: string | null = null;
259
+ try {
260
+ githubToken = await getGithubAuthManager({}, logger).getAccessToken();
261
+ } catch {
262
+ githubToken = null; // not signed in / token unavailable -> legacy headerless create
263
+ }
264
+ const res = await tunnelFetch(
265
+ "/tunnels",
266
+ "POST",
267
+ { github_user: githubUser, local_port: deps.localPort },
268
+ githubToken ? { Authorization: `Bearer ${githubToken}` } : undefined,
269
+ );
239
270
  const body = res.json as { tunnel_id?: string; connector_token?: string; hostname?: string; delete_token?: string; error?: string };
240
271
  if (res.status !== 201 || !body.tunnel_id || !body.connector_token || !body.hostname) {
241
272
  throw new Error(body.error ?? `tunnel server responded ${res.status}`);
@@ -278,8 +309,12 @@ export function createTunnelManager(deps: { logger: PluginLogger; localPort: num
278
309
  /** Anonymous one-off tunnel: `cloudflared tunnel --url`, no Cloudflare
279
310
  * account, no token, no platform server. Cloudflare assigns a random
280
311
  * trycloudflare.com URL (printed on stderr) which dies with the process -
281
- * it is NOT recovered on restart and must not be treated as stable. No
282
- * TeamClaw gate: anyone with the URL can reach the dashboard. */
312
+ * it is NOT recovered on restart and must not be treated as stable.
313
+ * #255 P1-5: the quick URL is internet-reachable, so it now gets the SAME
314
+ * per-launch gate token as managed tunnels (cookie-gated by the shared
315
+ * http-server enforcement point). The token is deliberately NOT
316
+ * persisted: quick tunnels have no recovery, and a token that dies with
317
+ * the process is strictly safer than one saved to disk. */
283
318
  function startQuick(): { launched: boolean; error: string | null } {
284
319
  if (handle && child) return { launched: true, error: null };
285
320
  const bin = findCloudflared();
@@ -292,7 +327,9 @@ export function createTunnelManager(deps: { logger: PluginLogger; localPort: num
292
327
  env: { ...process.env, HOME: tunnelRuntimeHome() },
293
328
  });
294
329
  child = proc;
295
- handle = { tunnelId: "quick", hostname: "", gateToken: "", deleteToken: "" };
330
+ // #255 P1-5: same entropy class as the managed gate token (16 CSPRNG
331
+ // bytes, base64url) - the cookie check gates on it via gateAllows().
332
+ handle = { tunnelId: "quick", hostname: "", gateToken: randomBytes(16).toString("base64url"), deleteToken: "" };
296
333
  lastError = null;
297
334
  // The trycloudflare.com URL appears on stderr once the edge assigns it.
298
335
  let announced = false;
@@ -0,0 +1,231 @@
1
+ // Issue #226 W2 (route-table carve-up): the tunnel-side route tables (the
2
+ // pre-PR-D http-server.ts outer callback's tunnel branch, moved into
3
+ // route-table.ts verbatim by PR-D) moved verbatim into this module -
4
+ // bodies byte-identical, only the module home changed. route-table.ts
5
+ // re-exports both factories so http-server.ts's imports are unchanged.
6
+ // The tunnel gate-page HTML rendering (gatePageHtml calls below) and the
7
+ // form reader live here with their only consumers. This module imports
8
+ // http-server.js as TYPE ONLY (ControllerHttpDeps), so the module graph
9
+ // stays acyclic - same discipline as security.ts.
10
+ import type { IncomingMessage, ServerResponse } from "node:http";
11
+ import { sendJson, sendError } from "../protocol.js";
12
+ import { getGithubAuthManager } from "./github-auth.js";
13
+ import { gatePageHtml, computeGateCookie, GATE_COOKIE_NAME, selfHostedTokenFromEnv, type TunnelManager } from "./tunnel-manager.js";
14
+ import { isLanIp, isProtectionOn, secretsEqual } from "./security.js";
15
+ import type { ControllerHttpDeps } from "./http-server.js";
16
+ import type { RouteDef } from "./route-table.js";
17
+
18
+ async function readFormBody(request: IncomingMessage): Promise<Record<string, unknown>> {
19
+ const chunks: Buffer[] = [];
20
+ for await (const chunk of request) chunks.push(chunk as Buffer);
21
+ const raw = Buffer.concat(chunks).toString("utf8");
22
+ const out: Record<string, unknown> = {};
23
+ for (const [k, v] of new URLSearchParams(raw)) out[k] = v;
24
+ return out;
25
+ }
26
+
27
+
28
+ // ===========================================================================
29
+ // Tunnel-side route tables (pre-PR-D http-server.ts lines 348-432, the
30
+ // outer server callback's tunnel branch). These run BEFORE handleRequest
31
+ // and are split exactly along the old viaTunnel if/else:
32
+ // - viaTunnel: the gate page routes answer; every other tunnel request
33
+ // must pass the gate cookie (403 gate page), then continues to the
34
+ // controller route table;
35
+ // - direct (non-tunnel): the tunnel management API answers, everything
36
+ // else continues to the controller route table.
37
+ // ===========================================================================
38
+
39
+ // Issue #237 W3: online-guessing throttle for POST /__tunnel_gate/verify.
40
+ // The endpoint answers on the PUBLIC tunnel URL, so repeated failures cool
41
+ // the gate down. Deliberately GLOBAL (not per-IP): every via-tunnel request
42
+ // arrives from the local cloudflared socket, so a per-IP key would collapse
43
+ // to one bucket for the whole internet anyway - this mirrors the pairing
44
+ // code throttle in security.ts (timestamps pruned against a sliding window).
45
+ const GATE_VERIFY_FAILURE_MAX = 10;
46
+ const GATE_VERIFY_COOLDOWN_MS = 60_000;
47
+ const gateVerifyFailures: number[] = [];
48
+
49
+ function gateVerifyThrottled(): boolean {
50
+ const now = Date.now();
51
+ while (gateVerifyFailures.length > 0 && now - gateVerifyFailures[0]! >= GATE_VERIFY_COOLDOWN_MS) {
52
+ gateVerifyFailures.shift();
53
+ }
54
+ return gateVerifyFailures.length >= GATE_VERIFY_FAILURE_MAX;
55
+ }
56
+
57
+ function recordGateVerifyFailure(): void {
58
+ gateVerifyFailures.push(Date.now());
59
+ }
60
+
61
+ /** GET /__tunnel_gate + GET / + POST /__tunnel_gate/verify (via tunnel only). */
62
+ export function createTunnelGateRoutes(tunnelManager: TunnelManager): readonly RouteDef[] {
63
+ return [
64
+ {
65
+ method: "GET",
66
+ path: "/__tunnel_gate",
67
+ handler: ({ res, req }) => {
68
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
69
+ res.end(gatePageHtml(String(req.headers.host), false));
70
+ },
71
+ },
72
+ {
73
+ // Valid gate cookie on "/" goes straight to the dashboard; the gate
74
+ // page only greets visitors who have not authenticated yet.
75
+ method: "GET",
76
+ path: "/",
77
+ handler: ({ res, req, pathname }) => {
78
+ if (pathname === "/" && tunnelManager.gateAllows(req)) {
79
+ res.writeHead(302, { Location: "/ui/" });
80
+ res.end();
81
+ return;
82
+ }
83
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
84
+ res.end(gatePageHtml(String(req.headers.host), false));
85
+ },
86
+ },
87
+ {
88
+ method: "POST",
89
+ path: "/__tunnel_gate/verify",
90
+ handler: async ({ res, req }) => {
91
+ // Issue #237 W3: check the throttle BEFORE touching the token - a
92
+ // cooled-down gate answers 429 without comparing anything, so
93
+ // brute-force attempts cannot outrun the cooldown.
94
+ if (gateVerifyThrottled()) {
95
+ res.setHeader("Retry-After", "60");
96
+ sendJson(res, 429, { error: "Too many gate verification attempts. Wait a minute and try again." });
97
+ return;
98
+ }
99
+ const form = await readFormBody(req);
100
+ // Issue #237 W3: gate tokens are 128-bit base64url and therefore
101
+ // case-sensitive - only surrounding whitespace is normalized (the
102
+ // old .toUpperCase() fold belonged to the retired 8-char token).
103
+ const submitted = String((form as { token?: unknown }).token ?? "").trim();
104
+ const st = tunnelManager.status();
105
+ // Issue #237 W3: constant-time comparison (plain === was
106
+ // timing-leaky on this internet-reachable endpoint).
107
+ if (st.active && st.gateToken && secretsEqual(submitted, st.gateToken)) {
108
+ const cookie = `${GATE_COOKIE_NAME}=${computeGateCookie(st.gateToken, st.tunnelId ?? "")}; Path=/; Max-Age=43200; HttpOnly; SameSite=Lax`;
109
+ res.writeHead(302, { "Set-Cookie": cookie, Location: "/" });
110
+ res.end();
111
+ return;
112
+ }
113
+ recordGateVerifyFailure();
114
+ res.writeHead(403, { "Content-Type": "text/html; charset=utf-8" });
115
+ res.end(gatePageHtml(String(req.headers.host), true));
116
+ },
117
+ },
118
+ ];
119
+ }
120
+
121
+ /** /api/v1/tunnel/* management API (direct requests only, never via tunnel). */
122
+ export function createTunnelManagementRoutes(tunnelManager: TunnelManager, deps: ControllerHttpDeps): readonly RouteDef[] {
123
+ const { config, logger } = deps;
124
+
125
+ // Issue #222 (coordinated scope): creating a public tunnel is an
126
+ // internet-EXPOSURE escalation, so in L0 (protection off) the three start
127
+ // endpoints accept only loopback/LAN origins - a public-network peer that
128
+ // merely reached the port must never be able to open a share URL into
129
+ // this controller. While protection is on, the device gate in
130
+ // http-server.ts has already authenticated the caller (#23) and stays the
131
+ // governing rule: a deliberately paired device may share, including
132
+ // remotely. Loopback/LAN classification reuses the security module's
133
+ // isLanIp (via-tunnel requests never reach this table - they dispatch to
134
+ // the gate table instead - so the raw socket peer is authoritative).
135
+ const tunnelStartAllowedFrom = (req: IncomingMessage, res: ServerResponse): boolean => {
136
+ if (isProtectionOn(deps.getTeamState())) {
137
+ return true;
138
+ }
139
+ if (isLanIp(req.socket.remoteAddress)) {
140
+ return true;
141
+ }
142
+ sendJson(res, 403, {
143
+ error: "forbidden",
144
+ 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.",
145
+ });
146
+ return false;
147
+ };
148
+
149
+ return [
150
+ {
151
+ method: "GET",
152
+ path: "/api/v1/tunnel/status",
153
+ handler: ({ res }) => {
154
+ sendJson(res, 200, tunnelManager.status());
155
+ },
156
+ },
157
+ {
158
+ method: "POST",
159
+ path: "/api/v1/tunnel/start",
160
+ handler: async ({ req, res }) => {
161
+ if (!tunnelStartAllowedFrom(req, res)) {
162
+ return;
163
+ }
164
+ const authStatus = await getGithubAuthManager(config, logger).getStatus();
165
+ const account = authStatus.account;
166
+ if (!account?.login) { sendError(res, 401, "GitHub login required to share a tunnel"); return; }
167
+ // Async launch: poll /tunnel/status for phase progress and the
168
+ // resulting hostname/gateToken once startOp.phase === "done".
169
+ const launched = tunnelManager.start(account.login);
170
+ sendJson(res, 202, { launched, status: tunnelManager.status() });
171
+ },
172
+ },
173
+ {
174
+ // Self-hosted: user-owned Cloudflare tunnel via connector token (no
175
+ // GitHub login, no platform tunnel server). Token from the request
176
+ // body, or the TEAMCLAW_TUNNEL_TOKEN env injection when body is empty.
177
+ method: "POST",
178
+ path: "/api/v1/tunnel/start-self-hosted",
179
+ handler: async ({ req, res }) => {
180
+ if (!tunnelStartAllowedFrom(req, res)) {
181
+ return;
182
+ }
183
+ let token = "";
184
+ try {
185
+ const body = await readFormBody(req) as { token?: unknown };
186
+ token = String(body.token ?? "");
187
+ } catch { /* fall through to env */ }
188
+ if (!token.trim()) {
189
+ const envToken = selfHostedTokenFromEnv();
190
+ if (!envToken) { sendError(res, 400, "connector token required (or set TEAMCLAW_TUNNEL_TOKEN)"); return; }
191
+ token = envToken;
192
+ }
193
+ const r = tunnelManager.startSelfHosted(token);
194
+ if (!r.launched) { sendError(res, 400, r.error ?? "failed to start self-hosted tunnel"); return; }
195
+ sendJson(res, 202, { launched: true, status: tunnelManager.status() });
196
+ },
197
+ },
198
+ {
199
+ method: "POST",
200
+ path: "/api/v1/tunnel/start-quick",
201
+ handler: ({ req, res }) => {
202
+ if (!tunnelStartAllowedFrom(req, res)) {
203
+ return;
204
+ }
205
+ const r = tunnelManager.startQuick();
206
+ if (!r.launched) { sendError(res, 400, r.error ?? "failed to start quick tunnel"); return; }
207
+ sendJson(res, 202, { launched: true, status: tunnelManager.status() });
208
+ },
209
+ },
210
+ {
211
+ method: "POST",
212
+ path: "/api/v1/tunnel/stop",
213
+ handler: async ({ res }) => {
214
+ await tunnelManager.stop();
215
+ sendJson(res, 200, tunnelManager.status());
216
+ },
217
+ },
218
+ {
219
+ method: "POST",
220
+ path: "/api/v1/tunnel/install-cloudflared",
221
+ handler: async ({ res }) => {
222
+ try {
223
+ const result = await tunnelManager.installCloudflared();
224
+ sendJson(res, result.ok ? 200 : 500, { ...result, status: tunnelManager.status() });
225
+ } catch (err) {
226
+ sendError(res, 500, err instanceof Error ? err.message : "install failed");
227
+ }
228
+ },
229
+ },
230
+ ];
231
+ }
@@ -0,0 +1,70 @@
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 type { ServerResponse } from "node:http";
8
+ import { sendError } from "../protocol.js";
9
+
10
+ // Tunnel/CDN caches rewrite the origin's Cache-Control: no-cache into a long
11
+ // browser freeze for cacheable extensions like .js (observed: Cloudflare
12
+ // Browser Cache TTL max-age=14400 on tunneled UI assets). A UI update then
13
+ // never reaches visitors through the tunnel. Serving content-versioned URLs
14
+ // (?v=<hash>) makes every UI deploy a URL no browser or edge has ever seen,
15
+ // so stale-cache behavior cannot recur.
16
+ const uiAssetVersionCache = new Map<string, { mtimeMs: number; version: string }>();
17
+
18
+ function uiAssetVersion(uiPath: string, file: string): string {
19
+ const full = path.join(uiPath, file);
20
+ try {
21
+ const mtimeMs = fs.statSync(full).mtimeMs;
22
+ const cached = uiAssetVersionCache.get(full);
23
+ if (cached && cached.mtimeMs === mtimeMs) return cached.version;
24
+ const version = createHash("sha1").update(fs.readFileSync(full)).digest("hex").slice(0, 10);
25
+ uiAssetVersionCache.set(full, { mtimeMs, version });
26
+ return version;
27
+ } catch {
28
+ return String(Date.now()); // unreadable asset: bust for this request
29
+ }
30
+ }
31
+
32
+ const UI_HTML_ASSET_REFS = [
33
+ "/ui/style.css",
34
+ "/ui/app.js",
35
+ "/ui/assets/teamclaw-app-icon.png",
36
+ ];
37
+
38
+ export function serveVersionedHtml(res: ServerResponse, htmlPath: string): void {
39
+ try {
40
+ const uiPath = path.dirname(htmlPath);
41
+ let html = fs.readFileSync(htmlPath, "utf8");
42
+ for (const ref of UI_HTML_ASSET_REFS) {
43
+ html = html.split(`"${ref}"`).join(`"${ref}?v=${uiAssetVersion(uiPath, ref.slice("/ui/".length))}"`);
44
+ }
45
+ res.writeHead(200, {
46
+ "Content-Type": "text/html; charset=utf-8",
47
+ "Access-Control-Allow-Origin": "*",
48
+ "Cache-Control": "no-cache",
49
+ });
50
+ res.end(html);
51
+ } catch {
52
+ sendError(res, 404, "File not found");
53
+ }
54
+ }
55
+
56
+ export function serveStaticFile(res: ServerResponse, filePath: string, contentType: string): void {
57
+ try {
58
+ const content = fs.readFileSync(filePath);
59
+ res.writeHead(200, {
60
+ "Content-Type": contentType,
61
+ "Access-Control-Allow-Origin": "*",
62
+ // UI assets change with every plugin deploy on a localhost controller;
63
+ // always revalidate so browsers never stick to a stale app.js.
64
+ "Cache-Control": "no-cache",
65
+ });
66
+ res.end(content);
67
+ } catch {
68
+ sendError(res, 404, "File not found");
69
+ }
70
+ }
@@ -1,5 +1,5 @@
1
1
  import { WebSocketServer, WebSocket } from "ws";
2
- import type { Server } from "node:http";
2
+ import type { IncomingMessage, Server } from "node:http";
3
3
  import type { PluginLogger } from "../../api.js";
4
4
 
5
5
  export type WsEvent =
@@ -20,7 +20,31 @@ export type WsEvent =
20
20
  | { type: "project:deleted"; data: unknown }
21
21
  | { type: "requirement:complete"; data: unknown }
22
22
  | { type: "report:ready"; data: unknown }
23
- | { type: "teamauto:activity"; data: unknown };
23
+ | { type: "teamauto:activity"; data: unknown }
24
+ // Phase 2.2 (design sections 2.3/4): team profile switch lifecycle. Event
25
+ // names follow the design document verbatim (dot-separated) rather than the
26
+ // colon convention used by the domain events above - they are the external
27
+ // contract UI/desktop/workers will subscribe to.
28
+ | { type: "team.switch_started"; data: { profileId: string; previousProfileId: string } }
29
+ | { type: "team.switch_completed"; data: { profileId: string } }
30
+ // Phase 2 follow-up (#201 review): the switch failed mid-flight. Broadcast
31
+ // BEFORE the transition is cleared so UI waiters see the failure instead of
32
+ // silently timing out on reconcile. `reason` states the honest worst case:
33
+ // once the step-3 archive write has landed, the team may be partially
34
+ // switched and a restart is the reliable way back to a known-good team.
35
+ | { type: "team.switch_failed"; data: { previousProfileId: string; targetProfileId: string; reason: string } };
36
+
37
+ /**
38
+ * Issue #23: optional upgrade guard. While device protection is on, the
39
+ * composition root passes a `verifyUpgrade` predicate that validates the
40
+ * upgrade request's device token (query ?token= / cookie / Bearer header,
41
+ * see controller/security.ts createWebSocketUpgradeGuard); returning false
42
+ * makes ws answer the upgrade with 401. Without the option the server is
43
+ * wide open - the pre-issue L0 behavior.
44
+ */
45
+ export type TeamWebSocketAttachOptions = {
46
+ verifyUpgrade?: (req: IncomingMessage) => boolean;
47
+ };
24
48
 
25
49
  export class TeamWebSocketServer {
26
50
  private wss: WebSocketServer | null = null;
@@ -30,8 +54,12 @@ export class TeamWebSocketServer {
30
54
  this.logger = logger;
31
55
  }
32
56
 
33
- attach(server: Server): void {
34
- this.wss = new WebSocketServer({ server, path: "/ws" });
57
+ attach(server: Server, options?: TeamWebSocketAttachOptions): void {
58
+ this.wss = new WebSocketServer({
59
+ server,
60
+ path: "/ws",
61
+ ...(options?.verifyUpgrade ? { verifyClient: (info: { req: IncomingMessage }) => options.verifyUpgrade!(info.req) } : {}),
62
+ });
35
63
 
36
64
  this.wss.on("connection", (ws) => {
37
65
  this.logger.info("WebSocket: client connected");
@@ -0,0 +1,55 @@
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 type { RouteContext } from "./route-table.js";
9
+ import { serveStaticFile, serveVersionedHtml } from "./ui-assets.js";
10
+
11
+ function webUiRootRoute(ctx: RouteContext): void {
12
+ const { res } = ctx;
13
+ res.statusCode = 302;
14
+ res.setHeader("Location", "/ui");
15
+ res.end();
16
+ }
17
+
18
+ function webUiIndexRoute(ctx: RouteContext): void {
19
+ const { res } = ctx;
20
+ const uiPath = path.join(import.meta.dirname, "..", "ui");
21
+ serveVersionedHtml(res, path.join(uiPath, "index.html"));
22
+ }
23
+
24
+ // Standalone GitHub device-login page (big user code + prefilled link + polling).
25
+ function webUiGithubLoginPageRoute(ctx: RouteContext): void {
26
+ const { res } = ctx;
27
+ const uiPath = path.join(import.meta.dirname, "..", "ui");
28
+ serveStaticFile(res, path.join(uiPath, "github-login.html"), "text/html; charset=utf-8");
29
+ }
30
+
31
+ function webUiAssetsRoute(ctx: RouteContext): void {
32
+ const { res, pathname } = ctx;
33
+ const uiPath = path.join(import.meta.dirname, "..", "ui");
34
+ const file = pathname.slice(4); // remove "/ui/"
35
+ if (file.endsWith(".css")) {
36
+ serveStaticFile(res, path.join(uiPath, file), "text/css; charset=utf-8");
37
+ } else if (file.endsWith(".js")) {
38
+ serveStaticFile(res, path.join(uiPath, file), "application/javascript; charset=utf-8");
39
+ } else if (file.endsWith(".png")) {
40
+ serveStaticFile(res, path.join(uiPath, file), "image/png");
41
+ } else if (file.endsWith(".svg")) {
42
+ serveStaticFile(res, path.join(uiPath, file), "image/svg+xml; charset=utf-8");
43
+ } else if (file.endsWith(".ico")) {
44
+ serveStaticFile(res, path.join(uiPath, file), "image/x-icon");
45
+ } else {
46
+ serveStaticFile(res, path.join(uiPath, file), "application/octet-stream");
47
+ }
48
+ }
49
+
50
+ export {
51
+ webUiRootRoute,
52
+ webUiIndexRoute,
53
+ webUiGithubLoginPageRoute,
54
+ webUiAssetsRoute,
55
+ };