@teamclaws/teamclaw 2026.11.6 → 2026.11.8

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 (43) hide show
  1. package/README.md +17 -11
  2. package/dist/src/config.js +3 -3
  3. package/dist/src/controller/http-server.js +18 -6
  4. package/dist/src/controller/managed-gateway-process.js +17 -1
  5. package/dist/src/controller/preview-proxy.js +55 -8
  6. package/dist/src/controller/provisioning/process-supervisor.js +11 -0
  7. package/dist/src/controller/route-table.js +2 -2
  8. package/dist/src/controller/security.js +85 -17
  9. package/dist/src/controller/task-assignment.js +62 -1
  10. package/dist/src/controller/task-routes.js +39 -2
  11. package/dist/src/controller/tunnel-manager.js +11 -0
  12. package/dist/src/controller/tunnel-routes.js +11 -0
  13. package/dist/src/controller/workspace-routes.js +16 -2
  14. package/dist/src/teamauto/github-client.js +19 -0
  15. package/dist/src/teamauto/repo-sync.js +96 -22
  16. package/dist/src/teamauto/scheduler.js +458 -36
  17. package/dist/src/teamauto/store.js +125 -3
  18. package/dist/src/types.js +5 -3
  19. package/dist/src/ui/app.js +2 -2
  20. package/dist/src/worker/worker-service.js +13 -1
  21. package/dist/src/workspace-browser.js +14 -0
  22. package/openclaw.plugin.json +5 -5
  23. package/package.json +4 -2
  24. package/src/config.ts +3 -3
  25. package/src/controller/http-server.ts +19 -5
  26. package/src/controller/managed-gateway-process.ts +17 -1
  27. package/src/controller/preview-proxy.ts +54 -8
  28. package/src/controller/provisioning/process-supervisor.ts +11 -0
  29. package/src/controller/route-table.ts +2 -2
  30. package/src/controller/security.ts +90 -17
  31. package/src/controller/task-assignment.ts +58 -1
  32. package/src/controller/task-routes.ts +39 -1
  33. package/src/controller/tunnel-manager.ts +12 -1
  34. package/src/controller/tunnel-routes.ts +11 -0
  35. package/src/controller/workspace-routes.ts +17 -2
  36. package/src/teamauto/github-client.ts +21 -1
  37. package/src/teamauto/repo-sync.ts +85 -21
  38. package/src/teamauto/scheduler.ts +434 -33
  39. package/src/teamauto/store.ts +133 -3
  40. package/src/types.ts +9 -7
  41. package/src/ui/app.js +2 -2
  42. package/src/worker/worker-service.ts +15 -1
  43. package/src/workspace-browser.ts +15 -0
@@ -47,6 +47,8 @@ function emptyStore() {
47
47
  failedClaimRecovery: {},
48
48
  orphanResultAlarms: {},
49
49
  deliveredResults: {},
50
+ prDeliveries: {},
51
+ undeliveredPrAlarms: {},
50
52
  fullReviewUmbrellas: {},
51
53
  budget: {
52
54
  maxTasksPerDay: 150,
@@ -86,8 +88,10 @@ export function resolveTeamAutoPaths() {
86
88
  const writeQueue = [];
87
89
  export async function loadTeamAutoStore() {
88
90
  const { storeFile } = resolveTeamAutoPaths();
91
+ let baseFingerprint = "";
89
92
  try {
90
93
  const raw = await fs.readFile(storeFile, "utf8");
94
+ baseFingerprint = staleWriteFingerprint(raw);
91
95
  const parsed = JSON.parse(raw);
92
96
  const store = emptyStore();
93
97
  if (Array.isArray(parsed.repos)) {
@@ -130,13 +134,107 @@ export async function loadTeamAutoStore() {
130
134
  if (typeof parsed.deliveredResultsInit === "boolean") {
131
135
  store.deliveredResultsInit = parsed.deliveredResultsInit;
132
136
  }
137
+ // #5785: same loader-copy discipline as the #5736 chain above - a field
138
+ // missing from this list is dropped on EVERY 20s settle reload even
139
+ // though saveTeamAutoStore writes it to disk (dropped prDeliveries =>
140
+ // healthy pruned tasks re-probe GitHub; dropped undeliveredPrAlarms =>
141
+ // the once-per-task gate resets and one incident re-alarms every pass).
142
+ if (parsed.prDeliveries && typeof parsed.prDeliveries === "object") {
143
+ store.prDeliveries = parsed.prDeliveries;
144
+ }
145
+ if (parsed.undeliveredPrAlarms && typeof parsed.undeliveredPrAlarms === "object") {
146
+ store.undeliveredPrAlarms = parsed.undeliveredPrAlarms;
147
+ }
133
148
  store.budget = { ...store.budget, ...(parsed.budget ?? {}) };
149
+ store.__baseFp = baseFingerprint;
134
150
  return store;
135
151
  }
136
152
  catch {
137
153
  return emptyStore();
138
154
  }
139
155
  }
156
+ /** #5810/#5730 short-path guard helpers (cross-process stale-write protection). */
157
+ function staleWriteFingerprint(raw) {
158
+ let h = 5381;
159
+ for (let i = 0; i < raw.length; i++)
160
+ h = ((h * 33) ^ raw.charCodeAt(i)) >>> 0;
161
+ return `${raw.length}:${h.toString(36)}`;
162
+ }
163
+ function mergeStoresOnConflict(disk, saver) {
164
+ const maxKey = (a, b) => {
165
+ const out = { ...(a ?? {}) };
166
+ for (const [k, v] of Object.entries(b ?? {}))
167
+ out[k] = Math.max(out[k] ?? 0, v);
168
+ return out;
169
+ };
170
+ const unionBy = (a, b, key, cap = 600) => {
171
+ const seen = new Set();
172
+ const out = [];
173
+ for (const x of [...(a ?? []), ...(b ?? [])]) {
174
+ const k = key(x);
175
+ if (seen.has(k))
176
+ continue;
177
+ seen.add(k);
178
+ out.push(x);
179
+ }
180
+ return out.slice(-cap);
181
+ };
182
+ const merged = { ...saver };
183
+ const dayOf = (s) => s?.dayStamp ?? "";
184
+ const diskToday = disk.budget?.tasksToday ?? 0;
185
+ const saverToday = saver.budget?.tasksToday ?? 0;
186
+ merged.budget = {
187
+ ...(disk.budget ?? saver.budget),
188
+ dayStamp: dayOf(disk.budget) !== dayOf(saver.budget) && diskToday > saverToday ? dayOf(disk.budget) : (dayOf(saver.budget) || dayOf(disk.budget)),
189
+ tasksToday: dayOf(disk.budget) === dayOf(saver.budget) ? Math.max(diskToday, saverToday) : saverToday,
190
+ maxTasksPerDay: disk.budget?.maxTasksPerDay ?? saver.budget?.maxTasksPerDay ?? 150,
191
+ };
192
+ merged.deliveredResults = maxKey(disk.deliveredResults, saver.deliveredResults);
193
+ merged.orphanResultAlarms = maxKey(disk.orphanResultAlarms, saver.orphanResultAlarms);
194
+ merged.undeliveredPrAlarms = maxKey(disk.undeliveredPrAlarms, saver.undeliveredPrAlarms);
195
+ // #5785: PR-face records are durable facts - either side's stamp is
196
+ // evidence of delivery, so union with disk winning key collisions.
197
+ merged.prDeliveries = { ...(saver.prDeliveries ?? {}), ...(disk.prDeliveries ?? {}) };
198
+ merged.failedClaimRecovery = maxKey(disk.failedClaimRecovery, saver.failedClaimRecovery);
199
+ merged.fullReviewUmbrellas = maxKey(disk.fullReviewUmbrellas, saver.fullReviewUmbrellas);
200
+ merged.activity = unionBy(disk.activity, saver.activity, (x) => `${x.at}:${String(x.text).slice(0, 60)}`);
201
+ merged.writebacks = unionBy(disk.writebacks, saver.writebacks, (w) => w.taskId, 600).map((w) => {
202
+ const d = (disk.writebacks ?? []).find((x) => x.taskId === w.taskId);
203
+ if (!d)
204
+ return w;
205
+ return { ...w, doneAt: w.doneAt ?? d.doneAt, failedAt: w.failedAt ?? d.failedAt, attempts: Math.max(w.attempts ?? 0, d.attempts ?? 0), targetId: w.targetId ?? d.targetId };
206
+ });
207
+ const repoMap = new Map();
208
+ for (const r of [...(disk.repos ?? []), ...(saver.repos ?? [])]) {
209
+ const prev = repoMap.get(r.id);
210
+ if (!prev) {
211
+ repoMap.set(r.id, r);
212
+ continue;
213
+ }
214
+ const diskSide = disk.repos?.includes(prev) ? prev : r;
215
+ const otherSide = diskSide === prev ? r : prev;
216
+ repoMap.set(r.id, {
217
+ ...diskSide,
218
+ lastSweepAt: Math.max(prev.lastSweepAt ?? 0, r.lastSweepAt ?? 0),
219
+ lastAttemptAt: Math.max(prev.lastAttemptAt ?? 0, r.lastAttemptAt ?? 0),
220
+ lastSweepErrorAt: Math.max(prev.lastSweepErrorAt ?? 0, r.lastSweepErrorAt ?? 0),
221
+ sweepFailures: Math.max(prev.sweepFailures ?? 0, r.sweepFailures ?? 0),
222
+ failedTasksSinceLastSweep: Math.max(prev.failedTasksSinceLastSweep ?? 0, r.failedTasksSinceLastSweep ?? 0),
223
+ lastSweepSummary: (prev.lastSweepAt ?? 0) >= (r.lastSweepAt ?? 0) ? prev.lastSweepSummary : r.lastSweepSummary,
224
+ sweeps: unionBy(prev.sweeps, r.sweeps, (x) => `${x.at}:${String(x.summary).slice(0, 40)}`, 40),
225
+ cursors: {
226
+ ...diskSide.cursors,
227
+ seen: maxKey(prev.cursors?.seen, otherSide.cursors?.seen),
228
+ etags: { ...(otherSide.cursors?.etags ?? {}), ...(diskSide.cursors?.etags ?? {}) },
229
+ lastIssueSince: Math.max(prev.cursors?.lastIssueSince ?? 0, r.cursors?.lastIssueSince ?? 0),
230
+ lastPrSince: Math.max(prev.cursors?.lastPrSince ?? 0, r.cursors?.lastPrSince ?? 0),
231
+ lastCommitSha: prev.cursors?.lastCommitSha ?? r.cursors?.lastCommitSha,
232
+ },
233
+ });
234
+ }
235
+ merged.repos = [...repoMap.values()];
236
+ return merged;
237
+ }
140
238
  /** #5677 (ggcode, 2026-11-15): store-level async mutex. The 20s write-back
141
239
  * reconcile re-reads the store from disk and saves the whole object; the
142
240
  * sweep transaction (registerWriteback + summary) does the same. Without
@@ -161,11 +259,35 @@ export async function withStoreLock(section) {
161
259
  export async function saveTeamAutoStore(store) {
162
260
  const { storeFile } = resolveTeamAutoPaths();
163
261
  await fs.mkdir(path.dirname(storeFile), { recursive: true });
164
- const tmp = `${storeFile}.tmp-${process.pid}-${Date.now()}`;
165
262
  const next = writeQueue.length ? writeQueue[writeQueue.length - 1].catch(() => { }) : Promise.resolve();
166
263
  const job = next.then(async () => {
167
- await fs.writeFile(tmp, JSON.stringify(store, null, 2) + "\n", { encoding: "utf8", mode: 0o600 });
168
- await fs.rename(tmp, storeFile);
264
+ let toWrite = store;
265
+ const guardDir = `${storeFile}.guard-lock`;
266
+ let tookLock = false;
267
+ try {
268
+ await fs.mkdir(guardDir, { recursive: true }).then(() => { tookLock = true; }, () => { });
269
+ if (tookLock) {
270
+ const diskRaw = await fs.readFile(storeFile, "utf8").catch(() => null);
271
+ const baseFp = store.__baseFp;
272
+ if (diskRaw !== null && baseFp && staleWriteFingerprint(diskRaw) !== baseFp) {
273
+ const diskParsed = JSON.parse(diskRaw);
274
+ const diskStore = { ...emptyStore(), ...diskParsed };
275
+ toWrite = mergeStoresOnConflict(diskStore, store);
276
+ }
277
+ }
278
+ }
279
+ catch { /* guard degraded - plain write */ }
280
+ try {
281
+ const tmp = `${storeFile}.tmp-${process.pid}-${Date.now()}`;
282
+ const raw = JSON.stringify(toWrite, (k, v) => (k === "__baseFp" ? undefined : v), 2) + "\n";
283
+ await fs.writeFile(tmp, raw, { encoding: "utf8", mode: 0o600 });
284
+ await fs.rename(tmp, storeFile);
285
+ store.__baseFp = staleWriteFingerprint(raw);
286
+ }
287
+ finally {
288
+ if (tookLock)
289
+ await fs.rm(guardDir, { recursive: true, force: true }).catch(() => { });
290
+ }
169
291
  });
170
292
  writeQueue.push(job);
171
293
  writeQueue.splice(0, Math.max(0, writeQueue.length - 20));
package/dist/src/types.js CHANGED
@@ -105,14 +105,16 @@ export function parsePluginConfig(raw = {}) {
105
105
  const agentIsolationMode = typeof raw.agentIsolationMode === "string" && (raw.agentIsolationMode === "independent" || raw.agentIsolationMode === "main")
106
106
  ? raw.agentIsolationMode
107
107
  : "independent";
108
- // Issue #23: security.autoPair defaults to true (L1 zero-input LAN
109
- // pairing); only an explicit boolean false disables pair-auto.
108
+ // Issue #23: security.autoPair defaulted to true (L1 zero-input LAN
109
+ // pairing). ClawHub security review 2026.11.6 (finding 2) flipped the
110
+ // default to false: a LAN peer must now present a pairing code unless
111
+ // the owner opts into zero-input pairing explicitly.
110
112
  const rawSecurity = raw.security;
111
113
  const rawAutoPair = rawSecurity && typeof rawSecurity === "object" && !Array.isArray(rawSecurity)
112
114
  ? rawSecurity.autoPair
113
115
  : undefined;
114
116
  const security = {
115
- autoPair: typeof rawAutoPair === "boolean" ? rawAutoPair : true,
117
+ autoPair: typeof rawAutoPair === "boolean" ? rawAutoPair : false,
116
118
  };
117
119
  // Issue #23 (client wave): the paired device token, if this instance
118
120
  // paired with a protected controller. Empty/absent keeps L0 behavior.
@@ -329,7 +329,7 @@
329
329
  "tunnel.selfHostedLabel": "Self-hosted tunnel (your own Cloudflare account/domain):",
330
330
  "tunnel.tokenPlaceholder": "Cloudflare connector token",
331
331
  "tunnel.setupHelp": "How to get a token & set up the tunnel",
332
- "tunnel.setupHelpBody": "Cloudflare Zero Trust → Networks → Tunnels → your tunnel → copy token. Point its public hostname at this machine’s URL (Service: HTTP + the controller port shown in the docs). Protect it with Cloudflare Access — self-hosted domains skip the TeamClaw gate.",
332
+ "tunnel.setupHelpBody": "Cloudflare Zero Trust → Networks → Tunnels → your tunnel → copy token. Point its public hostname at this machine’s URL (Service: HTTP + the controller port shown in the docs). Self-hosted domains skip the TeamClaw gate: device pairing must be enabled before the tunnel can start, and every visitor must pair a device (no gate page). Cloudflare Access is still recommended.",
333
333
  "tunnel.or": "— or —",
334
334
  "tunnel.requiresGithub": "requires GitHub login",
335
335
  "tunnel.startQuick": "Anonymous one-off tunnel (trycloudflare.com)",
@@ -627,7 +627,7 @@
627
627
  "tunnel.selfHostedLabel": "自托管隧道(你自己的 Cloudflare 账号/域名):",
628
628
  "tunnel.tokenPlaceholder": "Cloudflare 连接器令牌",
629
629
  "tunnel.setupHelp": "如何获取令牌并配置隧道",
630
- "tunnel.setupHelpBody": "Cloudflare Zero Trust → 网络(Networks)→ Tunnels → 你的隧道 → 复制令牌。将其公共域名指向本机 URL(Service:HTTP + 文档中所示的控制器端口)。建议用 Cloudflare Access 保护——自托管域名不走 TeamClaw 门禁。",
630
+ "tunnel.setupHelpBody": "Cloudflare Zero Trust → 网络(Networks)→ Tunnels → 你的隧道 → 复制令牌。将其公共域名指向本机 URL(Service:HTTP + 文档中所示的控制器端口)。自托管域名不走 TeamClaw 门禁:必须先启用设备配对才能启动隧道,且每位访客都要配对设备(无门禁页)。仍建议用 Cloudflare Access 保护。",
631
631
  "tunnel.or": "— 或 —",
632
632
  "tunnel.requiresGithub": "需要 GitHub 登录",
633
633
  "tunnel.startQuick": "匿名一次性隧道(trycloudflare.com)",
@@ -3,7 +3,7 @@ import http from "node:http";
3
3
  import { createHeartbeatPayload } from "../protocol.js";
4
4
  import { IdentityManager } from "../identity.js";
5
5
  import { MessageQueue } from "./message-queue.js";
6
- import { createWorkerHttpHandler } from "./http-handler.js";
6
+ import { createWorkerHttpHandler, resolveWorkerInboundTokens } from "./http-handler.js";
7
7
  import { buildTeamClawAgentSessionKey, ensureOpenClawWorkspaceMemoryDir } from "../openclaw-workspace.js";
8
8
  /**
9
9
  * Issue #27: container detection mirrors the controller's resolve step in
@@ -204,6 +204,18 @@ export function createWorkerService(deps) {
204
204
  }
205
205
  server = http.createServer(handler);
206
206
  const listenHost = resolveWorkerListenHost(config);
207
+ // ClawHub security review 2026.11.6 (finding 1): the HTTP handler's auth
208
+ // gate is conditional ("while this worker holds an expected token"), so a
209
+ // worker bound to a non-loopback address with NO token would expose task
210
+ // assignment / cancel / install to everyone who can reach the port. Fail
211
+ // closed: refuse to listen unless loopback OR a token is present. Loopback
212
+ // stays the zero-config L0 path (provisioned workers always carry
213
+ // TEAMCLAW_LAUNCH_TOKEN, so containers on 0.0.0.0 are unaffected).
214
+ if (!isLoopbackHost(listenHost) && resolveWorkerInboundTokens(config).length === 0) {
215
+ server = null;
216
+ throw new Error(`Worker: refusing to listen on ${listenHost}:${config.port} without an inbound token - the task/message/install API would be unauthenticated on the network. ` +
217
+ `Keep the loopback default, or set the securityToken plugin config (or launch via the controller, which injects TEAMCLAW_LAUNCH_TOKEN).`);
218
+ }
207
219
  await new Promise((resolve, reject) => {
208
220
  server.listen(config.port, listenHost, () => {
209
221
  logger.info(`Worker: HTTP server listening on ${listenHost}:${config.port}`);
@@ -134,6 +134,20 @@ async function resolveWorkspacePath(relativePath) {
134
134
  if (!relativeFromWorkspace || relativeFromWorkspace.startsWith("..") || path.isAbsolute(relativeFromWorkspace)) {
135
135
  throw new Error("workspace path must stay inside the workspace");
136
136
  }
137
+ // ClawHub security review 2026.11.6 (finding 5): the lexical check above
138
+ // does not follow symlinks, but every fs.* call below does - a link
139
+ // inside the workspace pointing at ~/.ssh would pass containment and be
140
+ // read straight through /api/v1/workspace/raw/. Resolve BOTH sides for
141
+ // real and re-check containment on the resolved paths. A dangling link
142
+ // surfaces ENOENT here (mapped to 404 by the routes, same as before).
143
+ // Residual: the realpath->open window is a check-to-use race; the
144
+ // controller trusts its own workspace tree against concurrent local
145
+ // tampering (an attacker who can plant links there already has the host).
146
+ const [realWorkspaceDir, realTarget] = await Promise.all([fs.realpath(workspaceDir), fs.realpath(absolutePath)]);
147
+ const relativeReal = path.relative(realWorkspaceDir, realTarget).replace(/\\/g, "/");
148
+ if (!relativeReal || relativeReal.startsWith("..") || path.isAbsolute(relativeReal)) {
149
+ throw new Error("workspace path must stay inside the workspace");
150
+ }
137
151
  return {
138
152
  workspaceDir,
139
153
  normalizedPath: relativeFromWorkspace,
@@ -2,7 +2,7 @@
2
2
  "id": "teamclaw",
3
3
  "name": "TeamClaw",
4
4
  "description": "Virtual team collaboration - multiple OpenClaw instances form a virtual software company with role-based task routing.",
5
- "version": "2026.11.6",
5
+ "version": "2026.11.8",
6
6
  "activation": {
7
7
  "onStartup": true
8
8
  },
@@ -75,7 +75,7 @@
75
75
  "maxConcurrentTasks": {
76
76
  "label": "Max Concurrent Tasks",
77
77
  "hint": "number",
78
- "help": "Maximum number of tasks that can be in 'in_progress' status at the same time (1–50)"
78
+ "help": "Maximum number of tasks that can be in 'in_progress' status at the same time (1\u201350)"
79
79
  },
80
80
  "gitEnabled": {
81
81
  "label": "Git Collaboration",
@@ -108,7 +108,7 @@
108
108
  },
109
109
  "security": {
110
110
  "label": "Device Pairing Security",
111
- "help": "Controller device-pairing options; autoPair allows LAN devices to pair with zero input (POST /api/v1/security/pair-auto), disable it to require a pairing code for every new device"
111
+ "help": "Controller device-pairing options; autoPair (off by default) allows LAN devices to pair with zero input (POST /api/v1/security/pair-auto) - enable only on a trusted private network"
112
112
  },
113
113
  "agentIsolationMode": {
114
114
  "label": "Agent Isolation Mode",
@@ -313,8 +313,8 @@
313
313
  "properties": {
314
314
  "autoPair": {
315
315
  "type": "boolean",
316
- "default": true,
317
- "description": "Allow zero-input pairing from LAN peers (POST /api/v1/security/pair-auto); disable to require a pairing code for every new device"
316
+ "default": false,
317
+ "description": "Allow zero-input pairing from LAN peers (POST /api/v1/security/pair-auto); off by default so every new device needs a pairing code - enable only on a trusted private network"
318
318
  }
319
319
  }
320
320
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@teamclaws/teamclaw",
3
- "version": "2026.11.6",
3
+ "version": "2026.11.8",
4
4
  "description": "OpenClaw virtual software team orchestration plugin - controller, role-based workers, Web UI with internet tunnel sharing",
5
5
  "private": false,
6
6
  "keywords": [
@@ -79,9 +79,11 @@
79
79
  },
80
80
  "compat": {
81
81
  "pluginApi": ">=2026.3.24",
82
- "builtWithOpenClawVersion": "2026.3.24",
83
82
  "minGatewayVersion": ">=2026.3.24"
84
83
  },
84
+ "build": {
85
+ "openclawVersion": "2026.11.6"
86
+ },
85
87
  "release": {
86
88
  "publishToNpm": true
87
89
  }
package/src/config.ts CHANGED
@@ -112,8 +112,8 @@ function buildConfigSchema() {
112
112
  properties: {
113
113
  autoPair: {
114
114
  type: "boolean" as const,
115
- default: true,
116
- description: "Allow zero-input pairing from LAN peers (POST /api/v1/security/pair-auto); disable to require a pairing code for every new device",
115
+ default: false,
116
+ description: "Allow zero-input pairing from LAN peers (POST /api/v1/security/pair-auto); off by default so every new device needs a pairing code - enable only on a trusted private network",
117
117
  },
118
118
  },
119
119
  },
@@ -331,7 +331,7 @@ function buildConfigSchema() {
331
331
  },
332
332
  security: {
333
333
  label: "Device Pairing Security",
334
- help: "Controller device-pairing options; autoPair allows LAN devices to pair with zero input (POST /api/v1/security/pair-auto), disable it to require a pairing code for every new device",
334
+ help: "Controller device-pairing options; autoPair (off by default) allows LAN devices to pair with zero input (POST /api/v1/security/pair-auto) - enable only on a trusted private network",
335
335
  },
336
336
  agentIsolationMode: {
337
337
  label: "Agent Isolation Mode",
@@ -83,6 +83,7 @@ import {
83
83
  corsPreflightDecision,
84
84
  createSecurityMiddleware,
85
85
  createWebSocketUpgradeGuard,
86
+ hasCloudflareEdgeHeaders,
86
87
  isProtectionOn,
87
88
  type SecurityPeer,
88
89
  } from "./security.js";
@@ -210,7 +211,16 @@ export function createControllerHttpServer(deps: ControllerHttpDeps): http.Serve
210
211
  // paired (protection off) this is a no-op passthrough (L0, the exact
211
212
  // pre-issue behavior); once devices exist it enforces per-device tokens
212
213
  // on every non-exempt /api route (exemptions and 401 shape in security.ts).
213
- const securityGate = createSecurityMiddleware(deps);
214
+ // ClawHub security review 2026.11.7 (finding 1): self-hosted tunnels serve
215
+ // a custom hostname, so the active tunnel mode decides whether tunnel
216
+ // visitors authenticate with the gate cookie (managed/quick) or a device
217
+ // token (self-hosted). Both gates read it through this accessor; the
218
+ // Cloudflare edge headers classify traffic the Host suffix cannot.
219
+ const tunnelMode = (): "managed" | "self-hosted" | "quick" | null => tunnelManagerSingleton?.status().mode ?? null;
220
+ const viaTunnelRequest = (req: { headers: Record<string, unknown> }): boolean =>
221
+ (tunnelManagerSingleton?.isTunnelRequest(typeof req.headers.host === "string" ? req.headers.host : undefined) ?? false)
222
+ || hasCloudflareEdgeHeaders(req);
223
+ const securityGate = createSecurityMiddleware({ ...deps, tunnelMode });
214
224
 
215
225
  const server = http.createServer(async (req: IncomingMessage, res: ServerResponse) => {
216
226
  // CORS preflight (issue #23: wildcard while protection is off - the
@@ -231,7 +241,7 @@ export function createControllerHttpServer(deps: ControllerHttpDeps): http.Serve
231
241
  // structure below is unchanged from the pre-PR-D if/else chain.
232
242
  let tunnelManager = tunnelManagerSingleton;
233
243
  if (!tunnelManager) {
234
- tunnelManager = tunnelManagerSingleton = createTunnelManager({ logger, localPort: deps.config.port });
244
+ tunnelManager = tunnelManagerSingleton = createTunnelManager({ logger, localPort: deps.config.port, isProtectionOn: () => isProtectionOn(deps.getTeamState()) });
235
245
  }
236
246
  if (!tunnelRoutesSingleton) {
237
247
  tunnelRoutesSingleton = {
@@ -242,7 +252,7 @@ export function createControllerHttpServer(deps: ControllerHttpDeps): http.Serve
242
252
  const tunnelCtx: RouteContext = {
243
253
  req, res, requestUrl: url, pathname, deps, currentState: null,
244
254
  };
245
- const viaTunnel = tunnelManager.isTunnelRequest(typeof req.headers.host === "string" ? req.headers.host : undefined);
255
+ const viaTunnel = viaTunnelRequest(req);
246
256
 
247
257
  // ==================== Device auth gate (issue #23) ====================
248
258
  // Runs BEFORE the tunnel gate tables, the transition matrix and the
@@ -260,7 +270,9 @@ export function createControllerHttpServer(deps: ControllerHttpDeps): http.Serve
260
270
  if (await dispatchRoutes(tunnelRoutesSingleton.gate, tunnelCtx)) {
261
271
  return;
262
272
  }
263
- if (!tunnelManager.gateAllows(req)) {
273
+ // Self-hosted tunnels have no gate token: their visitors were already
274
+ // authenticated by the device gate above (2026.11.7 finding 1).
275
+ if (tunnelMode() !== "self-hosted" && !tunnelManager.gateAllows(req)) {
264
276
  res.writeHead(403, { "Content-Type": "text/html; charset=utf-8" });
265
277
  res.end(gatePageHtml(String(req.headers.host), false));
266
278
  return;
@@ -286,7 +298,9 @@ export function createControllerHttpServer(deps: ControllerHttpDeps): http.Serve
286
298
  verifyUpgrade: createWebSocketUpgradeGuard({
287
299
  ...deps,
288
300
  isTunnelHost: (host) => tunnelManagerSingleton?.isTunnelRequest(host) ?? false,
301
+ viaTunnelRequest,
289
302
  gateAllows: (req) => tunnelManagerSingleton?.gateAllows(req) ?? false,
303
+ tunnelMode,
290
304
  }),
291
305
  });
292
306
 
@@ -299,7 +313,7 @@ export function createControllerHttpServer(deps: ControllerHttpDeps): http.Serve
299
313
  // Boot reconciliation: reconnect a share persisted by a previous run
300
314
  // (gateway restart or kill -9) so the tunnel id and gate token survive.
301
315
  if (!tunnelManagerSingleton) {
302
- tunnelManagerSingleton = createTunnelManager({ logger, localPort: deps.config.port });
316
+ tunnelManagerSingleton = createTunnelManager({ logger, localPort: deps.config.port, isProtectionOn: () => isProtectionOn(deps.getTeamState()) });
303
317
  }
304
318
  void tunnelManagerSingleton.recover().catch((err) => {
305
319
  logger.warn(`TeamClaw tunnel: boot recovery failed: ${String(err)}`);
@@ -34,6 +34,18 @@ export function spawnManagedGatewayProcess(options: ManagedGatewaySpawnOptions):
34
34
  }
35
35
 
36
36
  export function spawnManagedCommandProcess(options: ManagedCommandSpawnOptions): ChildProcess {
37
+ // #terminal-activation guard: previewCommand is worker-influenced input
38
+ // (#237 W1) executed through the core sh -c wrapper. A prompt-injected
39
+ // `open`/osascript command hijacks LaunchServices and activates
40
+ // Terminal.app from the headless launchd context (reported live: default
41
+ // Terminal windows intermittently activating). Reject loudly - never
42
+ // silently - so the attempt is visible in logs.
43
+ const cmd = options.command.trim();
44
+ if (/^(open|osascript)\b/i.test(cmd) || /(^|[\s;&|])osascript\b/i.test(cmd) || /(^|\s)-a\s+Terminal\b/.test(cmd)) {
45
+ const reason = `blocked Terminal-activation command (preview contract violation): ${cmd.slice(0, 120)}`;
46
+ console.error(`[teamclaw] ${reason}`);
47
+ throw new Error(`[teamclaw] ${reason}`);
48
+ }
37
49
  const cwd = options.cwd ?? process.cwd();
38
50
  const child = spawn(process.execPath, buildManagedCommandWrapperArgs(options.command), {
39
51
  ...buildManagedProcessSpawnOptions({
@@ -251,9 +263,13 @@ const shutdownSignals = process.platform === "win32"
251
263
  ? ["SIGTERM", "SIGINT", "SIGBREAK"]
252
264
  : ["SIGTERM", "SIGINT", "SIGHUP", "SIGQUIT"];
253
265
  const shell = process.platform === "win32" ? "cmd.exe" : "sh";
266
+ // -c, NOT -lc: a LOGIN shell sources the user's profiles in a headless
267
+ // launchd context. Profile init scripts are interactive-session side-effect
268
+ // machines (open/LaunchServices hooks, TTY-needing helpers) and are the
269
+ // plausible amplifier behind intermittent Terminal.app activations.
254
270
  const shellArgs = process.platform === "win32"
255
271
  ? ["/d", "/s", "/c", command]
256
- : ["-lc", command];
272
+ : ["-c", command];
257
273
 
258
274
  let shuttingDown = false;
259
275
  let parentMonitor = null;
@@ -13,6 +13,31 @@ import type { PluginLogger } from "../../api.js";
13
13
  import type { TeamState } from "../types.js";
14
14
  import { sendJson } from "../protocol.js";
15
15
 
16
+ /**
17
+ * Headers the preview proxy never forwards to the untrusted preview
18
+ * subprocess (ClawHub security review 2026.11.7 finding 2): every
19
+ * credential channel the controller itself accepts, plus routing headers
20
+ * the proxy re-derives below.
21
+ */
22
+ export const STRIPPED_PREVIEW_REQUEST_HEADERS: ReadonlySet<string> = new Set([
23
+ "cookie",
24
+ "authorization",
25
+ "x-teamclaw-token",
26
+ "host",
27
+ "connection",
28
+ "keep-alive",
29
+ "proxy-authorization",
30
+ "proxy-connection",
31
+ "te",
32
+ "trailer",
33
+ "transfer-encoding",
34
+ "upgrade",
35
+ "accept-encoding",
36
+ "x-forwarded-for",
37
+ "x-forwarded-host",
38
+ "x-forwarded-proto",
39
+ ]);
40
+
16
41
  /**
17
42
  * Structural slice of ControllerHttpDeps (http-server.ts) covering exactly
18
43
  * the fields the preview proxy reads. http-server keeps passing its full
@@ -52,22 +77,38 @@ export function handlePreviewProxyRequest(
52
77
  }
53
78
 
54
79
  const proxyPathPrefix = `/api/v1/previews/${encodeURIComponent(previewId)}`;
80
+ // ClawHub security review 2026.11.7 (finding 2): the preview subprocess runs
81
+ // UNTRUSTED project code, yet the proxy used to forward every incoming
82
+ // header - including the controller session cookie, Authorization bearer
83
+ // and X-TeamClaw-Token - so a preview page could read the owner's device
84
+ // credential and replay it against the controller API. Strip every
85
+ // credential-bearing header (and hop-by-hop / host-routing headers that
86
+ // the proxy re-derives) before the request leaves this process. Preview
87
+ // apps that need their own cookies must set them on their own origin.
88
+ const forwardedHeaders: http.OutgoingHttpHeaders = {};
89
+ for (const [name, value] of Object.entries(req.headers)) {
90
+ if (value === undefined) continue;
91
+ if (STRIPPED_PREVIEW_REQUEST_HEADERS.has(name.toLowerCase())) continue;
92
+ forwardedHeaders[name] = value;
93
+ }
94
+ Object.assign(forwardedHeaders, {
95
+ host: `127.0.0.1:${preview.targetPort}`,
96
+ "accept-encoding": "identity",
97
+ "x-forwarded-for": req.socket.remoteAddress ?? "",
98
+ "x-forwarded-host": req.headers.host ?? "",
99
+ "x-forwarded-proto": "http",
100
+ });
55
101
  const proxyReq = http.request(
56
102
  {
57
103
  hostname: "127.0.0.1",
58
104
  port: preview.targetPort,
59
105
  path: subPath + (requestUrl.search || ""),
60
106
  method: req.method,
61
- headers: {
62
- ...req.headers,
63
- host: `127.0.0.1:${preview.targetPort}`,
64
- "accept-encoding": "identity",
65
- "x-forwarded-for": req.socket.remoteAddress ?? "",
66
- "x-forwarded-host": req.headers.host ?? "",
67
- "x-forwarded-proto": "http",
68
- },
107
+ headers: forwardedHeaders,
69
108
  },
70
109
  (proxyRes: http.IncomingMessage) => {
110
+ // Same review: never let the preview plant cookies on the controller origin.
111
+ delete proxyRes.headers["set-cookie"];
71
112
  const contentType = (proxyRes.headers["content-type"] ?? "").toLowerCase();
72
113
  if (proxyRes.statusCode !== 200 && proxyRes.statusCode !== 201 && proxyRes.statusCode !== 301 && proxyRes.statusCode !== 302 && proxyRes.statusCode !== 304) {
73
114
  res.writeHead(proxyRes.statusCode ?? 502, proxyRes.headers);
@@ -107,6 +148,11 @@ export function handlePreviewProxyRequest(
107
148
  // We've decoded and rewritten the body — remove upstream encoding headers.
108
149
  delete resHeaders["content-encoding"];
109
150
  delete resHeaders["transfer-encoding"];
151
+ // Preview HTML executes under the controller origin (the proxy path),
152
+ // so give it the same opaque-origin sandbox the raw workspace route
153
+ // uses (2026.11.6 finding 6): scripts run, but cannot read the
154
+ // controller session or call /api/v1/* same-origin.
155
+ resHeaders["content-security-policy"] = "sandbox allow-scripts allow-forms";
110
156
  resHeaders["content-length"] = String(Buffer.byteLength(rewritten, "utf-8"));
111
157
  res.writeHead(proxyRes.statusCode ?? 200, resHeaders);
112
158
  res.end(rewritten);
@@ -145,6 +145,17 @@ export class ProcessProvisioner implements WorkerProvisionerBackend {
145
145
  OPENCLAW_STATE_DIR: stateDir,
146
146
  OPENCLAW_CONFIG_PATH: configPath,
147
147
  OPENCLAW_SKIP_CANVAS_HOST: "1",
148
+ // #disk-hygiene (screenshot report 2026-11-19): worker go builds can
149
+ // accumulate gigabytes of go-build/go-link dirs in the HOME tmp when
150
+ // deployments want them on a scratch volume. Opt-in ONLY - hardcoded
151
+ // paths would break any deployment without that volume. When the
152
+ // operator sets TEAMCLAW_GOCACHE / TEAMCLAW_GOTMPDIR, they are
153
+ // forwarded as GOCACHE / GOTMPDIR (an externally-set GOCACHE already
154
+ // flows through ...process.env untouched and is never overridden);
155
+ // unset -> Go defaults apply exactly as before. Kept ABOVE the
156
+ // workspaceDir spread so the contract test's env-tail shape holds.
157
+ ...(process.env.TEAMCLAW_GOCACHE && !process.env.GOCACHE ? { GOCACHE: process.env.TEAMCLAW_GOCACHE } : {}),
158
+ ...(process.env.TEAMCLAW_GOTMPDIR && !process.env.GOTMPDIR ? { GOTMPDIR: process.env.TEAMCLAW_GOTMPDIR } : {}),
148
159
  TEAMCLAW_WORKER_ID: spec.workerId,
149
160
  TEAMCLAW_LAUNCH_TOKEN: spec.launchToken,
150
161
  ...(spec.workspaceDir ? { TEAMCLAW_WORKSPACE_DIR: spec.workspaceDir } : {}),
@@ -575,8 +575,8 @@ export const controllerRouteTable: readonly RouteDef[] = [
575
575
  // pair/start- authenticated device or loopback (mints a fresh code,
576
576
  // invalidating the previous one)
577
577
  // pair - one-shot 60s code exchange -> {token, deviceId}
578
- // pair-auto - LAN peer + config.security.autoPair + protection on
579
- // reset - authenticated device or loopback (anti-lockout hatch)
578
+ // pair-auto - LAN peer + config.security.autoPair (opt-in) + protection on
579
+ // reset - loopback only (anti-lockout hatch; controller host action)
580
580
  // GET /security and DELETE /security/devices/:id are NOT exempt: the
581
581
  // middleware itself guarantees the caller holds a valid device token.
582
582
  { method: "POST", path: "/api/v1/security/enable", handler: handleSecurityEnableRequest },