@teamclaws/teamclaw 2026.11.7 → 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.
@@ -60,7 +60,7 @@ import { controllerRouteTable, createTunnelGateRoutes, createTunnelManagementRou
60
60
  // pairing handlers (registered via route-table.ts). This file only wires
61
61
  // them into the pipeline below - all pathname/method policy lives in
62
62
  // security.ts.
63
- import { classifySecurityPeer, corsPreflightDecision, createSecurityMiddleware, createWebSocketUpgradeGuard, isProtectionOn, } from "./security.js";
63
+ import { classifySecurityPeer, corsPreflightDecision, createSecurityMiddleware, createWebSocketUpgradeGuard, hasCloudflareEdgeHeaders, isProtectionOn, } from "./security.js";
64
64
  // ===========================================================================
65
65
  // Team profile switch dispatch-layer constants (Phase 2.1,
66
66
  // vertical-team-profiles-design.md 2.3). The six-step switch machine itself
@@ -141,7 +141,15 @@ export function createControllerHttpServer(deps) {
141
141
  // paired (protection off) this is a no-op passthrough (L0, the exact
142
142
  // pre-issue behavior); once devices exist it enforces per-device tokens
143
143
  // on every non-exempt /api route (exemptions and 401 shape in security.ts).
144
- const securityGate = createSecurityMiddleware(deps);
144
+ // ClawHub security review 2026.11.7 (finding 1): self-hosted tunnels serve
145
+ // a custom hostname, so the active tunnel mode decides whether tunnel
146
+ // visitors authenticate with the gate cookie (managed/quick) or a device
147
+ // token (self-hosted). Both gates read it through this accessor; the
148
+ // Cloudflare edge headers classify traffic the Host suffix cannot.
149
+ const tunnelMode = () => tunnelManagerSingleton?.status().mode ?? null;
150
+ const viaTunnelRequest = (req) => (tunnelManagerSingleton?.isTunnelRequest(typeof req.headers.host === "string" ? req.headers.host : undefined) ?? false)
151
+ || hasCloudflareEdgeHeaders(req);
152
+ const securityGate = createSecurityMiddleware({ ...deps, tunnelMode });
145
153
  const server = http.createServer(async (req, res) => {
146
154
  // CORS preflight (issue #23: wildcard while protection is off - the
147
155
  // historical bytes - and narrowed to the UI's own origin once on).
@@ -170,7 +178,7 @@ export function createControllerHttpServer(deps) {
170
178
  const tunnelCtx = {
171
179
  req, res, requestUrl: url, pathname, deps, currentState: null,
172
180
  };
173
- const viaTunnel = tunnelManager.isTunnelRequest(typeof req.headers.host === "string" ? req.headers.host : undefined);
181
+ const viaTunnel = viaTunnelRequest(req);
174
182
  // ==================== Device auth gate (issue #23) ====================
175
183
  // Runs BEFORE the tunnel gate tables, the transition matrix and the
176
184
  // capability gates so none of those surfaces answer - or leak response
@@ -186,7 +194,9 @@ export function createControllerHttpServer(deps) {
186
194
  if (await dispatchRoutes(tunnelRoutesSingleton.gate, tunnelCtx)) {
187
195
  return;
188
196
  }
189
- if (!tunnelManager.gateAllows(req)) {
197
+ // Self-hosted tunnels have no gate token: their visitors were already
198
+ // authenticated by the device gate above (2026.11.7 finding 1).
199
+ if (tunnelMode() !== "self-hosted" && !tunnelManager.gateAllows(req)) {
190
200
  res.writeHead(403, { "Content-Type": "text/html; charset=utf-8" });
191
201
  res.end(gatePageHtml(String(req.headers.host), false));
192
202
  return;
@@ -212,7 +222,9 @@ export function createControllerHttpServer(deps) {
212
222
  verifyUpgrade: createWebSocketUpgradeGuard({
213
223
  ...deps,
214
224
  isTunnelHost: (host) => tunnelManagerSingleton?.isTunnelRequest(host) ?? false,
225
+ viaTunnelRequest,
215
226
  gateAllows: (req) => tunnelManagerSingleton?.gateAllows(req) ?? false,
227
+ tunnelMode,
216
228
  }),
217
229
  });
218
230
  // Plugin shutdown: kill the local connector and tear down the remote
@@ -9,6 +9,30 @@
9
9
  import http from "node:http";
10
10
  import zlib from "node:zlib";
11
11
  import { sendJson } from "../protocol.js";
12
+ /**
13
+ * Headers the preview proxy never forwards to the untrusted preview
14
+ * subprocess (ClawHub security review 2026.11.7 finding 2): every
15
+ * credential channel the controller itself accepts, plus routing headers
16
+ * the proxy re-derives below.
17
+ */
18
+ export const STRIPPED_PREVIEW_REQUEST_HEADERS = new Set([
19
+ "cookie",
20
+ "authorization",
21
+ "x-teamclaw-token",
22
+ "host",
23
+ "connection",
24
+ "keep-alive",
25
+ "proxy-authorization",
26
+ "proxy-connection",
27
+ "te",
28
+ "trailer",
29
+ "transfer-encoding",
30
+ "upgrade",
31
+ "accept-encoding",
32
+ "x-forwarded-for",
33
+ "x-forwarded-host",
34
+ "x-forwarded-proto",
35
+ ]);
12
36
  /**
13
37
  * /api/v1/previews/:id/* - proxy to the preview subprocess. `pathname` starts
14
38
  * with "/api/v1/previews/"; `requestUrl` is the parsed request URL (query
@@ -29,20 +53,38 @@ export function handlePreviewProxyRequest(deps, req, res, requestUrl, pathname)
29
53
  return;
30
54
  }
31
55
  const proxyPathPrefix = `/api/v1/previews/${encodeURIComponent(previewId)}`;
56
+ // ClawHub security review 2026.11.7 (finding 2): the preview subprocess runs
57
+ // UNTRUSTED project code, yet the proxy used to forward every incoming
58
+ // header - including the controller session cookie, Authorization bearer
59
+ // and X-TeamClaw-Token - so a preview page could read the owner's device
60
+ // credential and replay it against the controller API. Strip every
61
+ // credential-bearing header (and hop-by-hop / host-routing headers that
62
+ // the proxy re-derives) before the request leaves this process. Preview
63
+ // apps that need their own cookies must set them on their own origin.
64
+ const forwardedHeaders = {};
65
+ for (const [name, value] of Object.entries(req.headers)) {
66
+ if (value === undefined)
67
+ continue;
68
+ if (STRIPPED_PREVIEW_REQUEST_HEADERS.has(name.toLowerCase()))
69
+ continue;
70
+ forwardedHeaders[name] = value;
71
+ }
72
+ Object.assign(forwardedHeaders, {
73
+ host: `127.0.0.1:${preview.targetPort}`,
74
+ "accept-encoding": "identity",
75
+ "x-forwarded-for": req.socket.remoteAddress ?? "",
76
+ "x-forwarded-host": req.headers.host ?? "",
77
+ "x-forwarded-proto": "http",
78
+ });
32
79
  const proxyReq = http.request({
33
80
  hostname: "127.0.0.1",
34
81
  port: preview.targetPort,
35
82
  path: subPath + (requestUrl.search || ""),
36
83
  method: req.method,
37
- headers: {
38
- ...req.headers,
39
- host: `127.0.0.1:${preview.targetPort}`,
40
- "accept-encoding": "identity",
41
- "x-forwarded-for": req.socket.remoteAddress ?? "",
42
- "x-forwarded-host": req.headers.host ?? "",
43
- "x-forwarded-proto": "http",
44
- },
84
+ headers: forwardedHeaders,
45
85
  }, (proxyRes) => {
86
+ // Same review: never let the preview plant cookies on the controller origin.
87
+ delete proxyRes.headers["set-cookie"];
46
88
  const contentType = (proxyRes.headers["content-type"] ?? "").toLowerCase();
47
89
  if (proxyRes.statusCode !== 200 && proxyRes.statusCode !== 201 && proxyRes.statusCode !== 301 && proxyRes.statusCode !== 302 && proxyRes.statusCode !== 304) {
48
90
  res.writeHead(proxyRes.statusCode ?? 502, proxyRes.headers);
@@ -78,6 +120,11 @@ export function handlePreviewProxyRequest(deps, req, res, requestUrl, pathname)
78
120
  // We've decoded and rewritten the body — remove upstream encoding headers.
79
121
  delete resHeaders["content-encoding"];
80
122
  delete resHeaders["transfer-encoding"];
123
+ // Preview HTML executes under the controller origin (the proxy path),
124
+ // so give it the same opaque-origin sandbox the raw workspace route
125
+ // uses (2026.11.6 finding 6): scripts run, but cannot read the
126
+ // controller session or call /api/v1/* same-origin.
127
+ resHeaders["content-security-policy"] = "sandbox allow-scripts allow-forms";
81
128
  resHeaders["content-length"] = String(Buffer.byteLength(rewritten, "utf-8"));
82
129
  res.writeHead(proxyRes.statusCode ?? 200, resHeaders);
83
130
  res.end(rewritten);
@@ -182,6 +182,39 @@ export function classifySecurityPeer(ip, viaTunnel) {
182
182
  lan: !viaTunnel && isLanIp(normalized),
183
183
  };
184
184
  }
185
+ /**
186
+ * ClawHub security review 2026.11.7 (finding 1): every request that rode
187
+ * through the Cloudflare edge carries CF-Connecting-IP / CF-Ray (added by
188
+ * the edge, not by cloudflared or the client). The managed tunnel suffixes
189
+ * in tunnel-manager catch *.teamclaw.dev / *.trycloudflare.com by Host,
190
+ * but a SELF-HOSTED tunnel serves a custom hostname, so its traffic used to
191
+ * classify as a plain loopback peer and inherit trusted-host access even
192
+ * while device protection was on. Treating edge-marked requests as tunnel
193
+ * traffic closes that: a forged CF header only ever DOWNGRADES the caller
194
+ * (tunnel peers are never loopback/LAN), never grants anything.
195
+ */
196
+ export function hasCloudflareEdgeHeaders(req) {
197
+ const h = req.headers;
198
+ return Boolean(h["cf-connecting-ip"] || h["cf-ray"] || h["cf-worker"]);
199
+ }
200
+ /** Origin policy for browser WebSocket upgrades (review 2026.11.7 finding 3). */
201
+ export function isAllowedWebSocketOrigin(req) {
202
+ const origin = req.headers.origin;
203
+ if (typeof origin !== "string" || !origin.trim()) {
204
+ return true; // non-browser clients (CLI, workers, curl) send no Origin
205
+ }
206
+ const host = typeof req.headers.host === "string" ? req.headers.host : "";
207
+ if (!host) {
208
+ return false;
209
+ }
210
+ try {
211
+ const u = new URL(origin);
212
+ return (u.protocol === "http:" || u.protocol === "https:") && u.host.toLowerCase() === host.toLowerCase();
213
+ }
214
+ catch {
215
+ return false;
216
+ }
217
+ }
185
218
  // ---------------------------------------------------------------------------
186
219
  // State helpers
187
220
  // ---------------------------------------------------------------------------
@@ -417,7 +450,13 @@ export function createSecurityMiddleware(deps) {
417
450
  // visitor can never obtain a pairing code, so protection-on would just
418
451
  // kill the tunnel with an unanswerable 401 (user design ruling
419
452
  // 2026-11-12). LAN peers remain the pairing boundary.
420
- if (peer.loopback || peer.viaTunnel) {
453
+ // ClawHub security review 2026.11.7 (finding 1): that exemption only
454
+ // holds for GATED tunnels (*.teamclaw.dev / quick tunnels whose visitors
455
+ // carry the gate cookie). A SELF-HOSTED tunnel has no gate token and a
456
+ // custom hostname, so its visitors must authenticate like any other
457
+ // remote peer - otherwise "protection on" protected nothing there.
458
+ const selfHostedTunnel = peer.viaTunnel && deps.tunnelMode?.() === "self-hosted";
459
+ if ((peer.loopback || peer.viaTunnel) && !selfHostedTunnel) {
421
460
  const authAny = authenticateDeviceToken(state, extractDeviceToken(req));
422
461
  if (authAny)
423
462
  touchDeviceLastSeen(deps, authAny.device.id);
@@ -435,9 +474,21 @@ export function createSecurityMiddleware(deps) {
435
474
  }
436
475
  export function createWebSocketUpgradeGuard(deps) {
437
476
  return function verifyUpgrade(req) {
438
- const viaTunnel = deps.isTunnelHost(typeof req.headers.host === "string" ? req.headers.host : undefined);
477
+ const viaTunnel = deps.viaTunnelRequest
478
+ ? deps.viaTunnelRequest(req)
479
+ : deps.isTunnelHost(typeof req.headers.host === "string" ? req.headers.host : undefined);
439
480
  const peer = classifySecurityPeer(req.socket.remoteAddress, viaTunnel);
440
481
  const state = deps.getTeamState();
482
+ // ClawHub security review 2026.11.7 (finding 3): browsers always send
483
+ // Origin on WebSocket upgrades; a cross-site page could otherwise open
484
+ // /ws with the victim's session cookie and read the live event stream.
485
+ // Only the controller's own origin (same host) may upgrade; non-browser
486
+ // clients without an Origin header are unaffected.
487
+ if (!isAllowedWebSocketOrigin(req)) {
488
+ deps.logger.warn(`Controller: rejected WebSocket upgrade from ${peer.ip} with cross-site Origin ${String(req.headers.origin)}`);
489
+ return false;
490
+ }
491
+ const selfHostedTunnel = peer.viaTunnel && deps.tunnelMode?.() === "self-hosted";
441
492
  // ClawHub security review 2026.11.6 (finding 3): the tunnel gate must
442
493
  // run BEFORE the protection-off allowance. The HTTP path enforces
443
494
  // gateAllows for every tunnel request regardless of device protection
@@ -445,7 +496,9 @@ export function createWebSocketUpgradeGuard(deps) {
445
496
  // surface - but this guard used to return true first, which left /ws as
446
497
  // the one tunnel surface a gate-cookie-less visitor could subscribe to
447
498
  // (task/message/clarification event stream). Same layering as HTTP now.
448
- if (peer.viaTunnel) {
499
+ // Self-hosted tunnels (2026.11.7 finding 1) have no gate cookie: their
500
+ // visitors fall through to the device-token check below instead.
501
+ if (peer.viaTunnel && !selfHostedTunnel) {
449
502
  if (!deps.gateAllows || !deps.gateAllows(req)) {
450
503
  deps.logger.warn(`Controller: rejected WebSocket upgrade from ${peer.ip} (via tunnel, no gate cookie)`);
451
504
  return false;
@@ -464,8 +517,8 @@ export function createWebSocketUpgradeGuard(deps) {
464
517
  if (peer.loopback) {
465
518
  return true;
466
519
  }
467
- // Tunnel-origin upgrades were handled above (gate cookie, never a pairing
468
- // token - a device token here would be an unanswerable wall, 8b03ed6).
520
+ // Gated-tunnel upgrades were handled above (gate cookie). Self-hosted
521
+ // tunnel upgrades land here and authenticate with a device token.
469
522
  let token = extractDeviceToken(req);
470
523
  if (!token) {
471
524
  const url = new URL(req.url ?? "/ws", `http://${req.headers.host ?? "localhost"}`);
@@ -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). Self-hosted domains skip the TeamClaw gate, so device pairing must be enabled before the tunnel can start, and Cloudflare Access is still recommended.",
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 + 文档中所示的控制器端口)。自托管域名不走 TeamClaw 门禁,因此必须先启用设备配对才能启动隧道;仍建议用 Cloudflare Access 保护。",
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)",
@@ -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.7",
5
+ "version": "2026.11.8",
6
6
  "activation": {
7
7
  "onStartup": true
8
8
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@teamclaws/teamclaw",
3
- "version": "2026.11.7",
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": [
@@ -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
@@ -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
 
@@ -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);
@@ -211,6 +211,40 @@ export function classifySecurityPeer(ip: string | undefined, viaTunnel: boolean)
211
211
  };
212
212
  }
213
213
 
214
+ /**
215
+ * ClawHub security review 2026.11.7 (finding 1): every request that rode
216
+ * through the Cloudflare edge carries CF-Connecting-IP / CF-Ray (added by
217
+ * the edge, not by cloudflared or the client). The managed tunnel suffixes
218
+ * in tunnel-manager catch *.teamclaw.dev / *.trycloudflare.com by Host,
219
+ * but a SELF-HOSTED tunnel serves a custom hostname, so its traffic used to
220
+ * classify as a plain loopback peer and inherit trusted-host access even
221
+ * while device protection was on. Treating edge-marked requests as tunnel
222
+ * traffic closes that: a forged CF header only ever DOWNGRADES the caller
223
+ * (tunnel peers are never loopback/LAN), never grants anything.
224
+ */
225
+ export function hasCloudflareEdgeHeaders(req: { headers: Record<string, unknown> }): boolean {
226
+ const h = req.headers;
227
+ return Boolean(h["cf-connecting-ip"] || h["cf-ray"] || h["cf-worker"]);
228
+ }
229
+
230
+ /** Origin policy for browser WebSocket upgrades (review 2026.11.7 finding 3). */
231
+ export function isAllowedWebSocketOrigin(req: { headers: Record<string, unknown> }): boolean {
232
+ const origin = req.headers.origin;
233
+ if (typeof origin !== "string" || !origin.trim()) {
234
+ return true; // non-browser clients (CLI, workers, curl) send no Origin
235
+ }
236
+ const host = typeof req.headers.host === "string" ? req.headers.host : "";
237
+ if (!host) {
238
+ return false;
239
+ }
240
+ try {
241
+ const u = new URL(origin);
242
+ return (u.protocol === "http:" || u.protocol === "https:") && u.host.toLowerCase() === host.toLowerCase();
243
+ } catch {
244
+ return false;
245
+ }
246
+ }
247
+
214
248
  // ---------------------------------------------------------------------------
215
249
  // State helpers
216
250
  // ---------------------------------------------------------------------------
@@ -370,6 +404,8 @@ export type SecurityMiddlewareDeps = {
370
404
  logger: PluginLogger;
371
405
  getTeamState: () => TeamState | null;
372
406
  updateTeamState: (updater: (state: TeamState) => void) => TeamState;
407
+ /** Active tunnel mode ("self-hosted" means tunnel visitors must hold a device token, not a gate cookie). */
408
+ tunnelMode?: () => "managed" | "self-hosted" | "quick" | null;
373
409
  };
374
410
 
375
411
  export type SecurityMiddleware = (req: IncomingMessage, res: ServerResponse, pathname: string, peer: SecurityPeer) => boolean;
@@ -487,7 +523,13 @@ export function createSecurityMiddleware(deps: SecurityMiddlewareDeps): Security
487
523
  // visitor can never obtain a pairing code, so protection-on would just
488
524
  // kill the tunnel with an unanswerable 401 (user design ruling
489
525
  // 2026-11-12). LAN peers remain the pairing boundary.
490
- if (peer.loopback || peer.viaTunnel) {
526
+ // ClawHub security review 2026.11.7 (finding 1): that exemption only
527
+ // holds for GATED tunnels (*.teamclaw.dev / quick tunnels whose visitors
528
+ // carry the gate cookie). A SELF-HOSTED tunnel has no gate token and a
529
+ // custom hostname, so its visitors must authenticate like any other
530
+ // remote peer - otherwise "protection on" protected nothing there.
531
+ const selfHostedTunnel = peer.viaTunnel && deps.tunnelMode?.() === "self-hosted";
532
+ if ((peer.loopback || peer.viaTunnel) && !selfHostedTunnel) {
491
533
  const authAny = authenticateDeviceToken(state, extractDeviceToken(req));
492
534
  if (authAny) touchDeviceLastSeen(deps, authAny.device.id);
493
535
  return true;
@@ -517,13 +559,27 @@ export function createSecurityMiddleware(deps: SecurityMiddlewareDeps): Security
517
559
  export type WebSocketUpgradeGuardDeps = SecurityMiddlewareDeps & {
518
560
  isTunnelHost: (host: string | undefined) => boolean;
519
561
  gateAllows?: (req: { headers: Record<string, unknown> }) => boolean;
562
+ /** Full-request tunnel classification (Host suffix OR Cloudflare edge headers); wins over isTunnelHost. */
563
+ viaTunnelRequest?: (req: { headers: Record<string, unknown> }) => boolean;
520
564
  };
521
565
 
522
566
  export function createWebSocketUpgradeGuard(deps: WebSocketUpgradeGuardDeps): (req: IncomingMessage) => boolean {
523
567
  return function verifyUpgrade(req: IncomingMessage): boolean {
524
- const viaTunnel = deps.isTunnelHost(typeof req.headers.host === "string" ? req.headers.host : undefined);
568
+ const viaTunnel = deps.viaTunnelRequest
569
+ ? deps.viaTunnelRequest(req)
570
+ : deps.isTunnelHost(typeof req.headers.host === "string" ? req.headers.host : undefined);
525
571
  const peer = classifySecurityPeer(req.socket.remoteAddress, viaTunnel);
526
572
  const state = deps.getTeamState();
573
+ // ClawHub security review 2026.11.7 (finding 3): browsers always send
574
+ // Origin on WebSocket upgrades; a cross-site page could otherwise open
575
+ // /ws with the victim's session cookie and read the live event stream.
576
+ // Only the controller's own origin (same host) may upgrade; non-browser
577
+ // clients without an Origin header are unaffected.
578
+ if (!isAllowedWebSocketOrigin(req)) {
579
+ deps.logger.warn(`Controller: rejected WebSocket upgrade from ${peer.ip} with cross-site Origin ${String(req.headers.origin)}`);
580
+ return false;
581
+ }
582
+ const selfHostedTunnel = peer.viaTunnel && deps.tunnelMode?.() === "self-hosted";
527
583
  // ClawHub security review 2026.11.6 (finding 3): the tunnel gate must
528
584
  // run BEFORE the protection-off allowance. The HTTP path enforces
529
585
  // gateAllows for every tunnel request regardless of device protection
@@ -531,7 +587,9 @@ export function createWebSocketUpgradeGuard(deps: WebSocketUpgradeGuardDeps): (r
531
587
  // surface - but this guard used to return true first, which left /ws as
532
588
  // the one tunnel surface a gate-cookie-less visitor could subscribe to
533
589
  // (task/message/clarification event stream). Same layering as HTTP now.
534
- if (peer.viaTunnel) {
590
+ // Self-hosted tunnels (2026.11.7 finding 1) have no gate cookie: their
591
+ // visitors fall through to the device-token check below instead.
592
+ if (peer.viaTunnel && !selfHostedTunnel) {
535
593
  if (!deps.gateAllows || !deps.gateAllows(req)) {
536
594
  deps.logger.warn(`Controller: rejected WebSocket upgrade from ${peer.ip} (via tunnel, no gate cookie)`);
537
595
  return false;
@@ -550,8 +608,8 @@ export function createWebSocketUpgradeGuard(deps: WebSocketUpgradeGuardDeps): (r
550
608
  if (peer.loopback) {
551
609
  return true;
552
610
  }
553
- // Tunnel-origin upgrades were handled above (gate cookie, never a pairing
554
- // token - a device token here would be an unanswerable wall, 8b03ed6).
611
+ // Gated-tunnel upgrades were handled above (gate cookie). Self-hosted
612
+ // tunnel upgrades land here and authenticate with a device token.
555
613
  let token = extractDeviceToken(req);
556
614
  if (!token) {
557
615
  const url = new URL(req.url ?? "/ws", `http://${req.headers.host ?? "localhost"}`);
package/src/ui/app.js CHANGED
@@ -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). Self-hosted domains skip the TeamClaw gate, so device pairing must be enabled before the tunnel can start, and Cloudflare Access is still recommended.",
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 + 文档中所示的控制器端口)。自托管域名不走 TeamClaw 门禁,因此必须先启用设备配对才能启动隧道;仍建议用 Cloudflare Access 保护。",
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)",