@teamclaws/teamclaw 2026.11.0 → 2026.11.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli.mjs +368 -13
- package/dist/index.js +61 -32
- package/dist/src/config.js +24 -0
- package/dist/src/controller/auth-routes.js +129 -0
- package/dist/src/controller/clarification-routes.js +1 -1
- package/dist/src/controller/config-routes.js +138 -0
- package/dist/src/controller/controller-planning.js +1 -0
- package/dist/src/controller/controller-routes.js +195 -0
- package/dist/src/controller/controller-service.js +67 -10
- package/dist/src/controller/controller-tools.js +3 -1
- package/dist/src/controller/github-auth.js +2 -1
- package/dist/src/controller/http-server.js +51 -16
- package/dist/src/controller/kickoff-orchestrator.js +3 -39
- package/dist/src/controller/message-delivery.js +4 -1
- package/dist/src/controller/orchestration-manifest.js +5 -65
- package/dist/src/controller/preview-manager.js +51 -3
- package/dist/src/controller/profile-switch.js +42 -22
- package/dist/src/controller/provisioning/backend-contract.js +9 -0
- package/dist/src/controller/provisioning/container-shared.js +64 -0
- package/dist/src/controller/provisioning/docker.js +214 -0
- package/dist/src/controller/provisioning/kubernetes.js +244 -0
- package/dist/src/controller/provisioning/plugin-root.js +41 -0
- package/dist/src/controller/provisioning/process-supervisor.js +190 -0
- package/dist/src/controller/provisioning-config.js +239 -0
- package/dist/src/controller/repo-routes.js +70 -4
- package/dist/src/controller/report-routes.js +56 -0
- package/dist/src/controller/route-table.js +73 -1045
- package/dist/src/controller/security.js +775 -0
- package/dist/src/controller/status-routes.js +287 -0
- package/dist/src/controller/task-assignment.js +5 -2
- package/dist/src/controller/task-execution.js +31 -0
- package/dist/src/controller/task-results.js +10 -0
- package/dist/src/controller/tunnel-manager.js +41 -8
- package/dist/src/controller/tunnel-routes.js +225 -0
- package/dist/src/controller/websocket.js +6 -2
- package/dist/src/controller/webui-routes.js +49 -0
- package/dist/src/controller/worker-provisioning.js +39 -949
- package/dist/src/controller/workflow-routes.js +407 -0
- package/dist/src/controller/workspace-routes.js +200 -0
- package/dist/src/git-collaboration.js +4 -9
- package/dist/src/identity.js +12 -1
- package/dist/src/openclaw-workspace.js +36 -0
- package/dist/src/profile-loader.js +119 -1
- package/dist/src/profiles/banking.json +26 -2
- package/dist/src/profiles/schema.json +82 -2
- package/dist/src/prompt-policy.js +18 -6
- package/dist/src/protocol.js +66 -3
- package/dist/src/shared/clarification-schema.js +65 -0
- package/dist/src/shared/github-auth.js +15 -0
- package/dist/src/shared/kickoff-prompt.js +37 -0
- package/dist/src/shared/utils.js +47 -0
- package/dist/src/state.js +89 -3
- package/dist/src/teamauto/scanner.js +21 -2
- package/dist/src/teamauto/scheduler.js +9 -2
- package/dist/src/types.js +15 -1
- package/dist/src/ui/app.js +990 -73
- package/dist/src/ui/github-login.html +1 -0
- package/dist/src/ui/index.html +125 -36
- package/dist/src/worker/http-handler.js +59 -0
- package/dist/src/worker/skill-installer.js +3 -9
- package/dist/src/worker/tools.js +20 -10
- package/dist/src/worker/worker-service.js +17 -4
- package/index.ts +69 -32
- package/openclaw.plugin.json +23 -2
- package/package.json +1 -1
- package/src/config.ts +24 -0
- package/src/controller/auth-routes.ts +157 -0
- package/src/controller/clarification-routes.ts +1 -1
- package/src/controller/config-routes.ts +152 -0
- package/src/controller/controller-planning.ts +8 -0
- package/src/controller/controller-routes.ts +237 -0
- package/src/controller/controller-service.ts +128 -10
- package/src/controller/controller-tools.ts +5 -2
- package/src/controller/github-auth.ts +28 -63
- package/src/controller/http-server.ts +66 -17
- package/src/controller/kickoff-orchestrator.ts +3 -42
- package/src/controller/message-delivery.ts +4 -1
- package/src/controller/orchestration-manifest.ts +8 -71
- package/src/controller/preview-manager.ts +53 -3
- package/src/controller/profile-switch.ts +53 -23
- package/src/controller/provisioning/backend-contract.ts +51 -0
- package/src/controller/provisioning/container-shared.ts +84 -0
- package/src/controller/provisioning/docker.ts +260 -0
- package/src/controller/provisioning/kubernetes.ts +263 -0
- package/src/controller/provisioning/plugin-root.ts +42 -0
- package/src/controller/provisioning/process-supervisor.ts +214 -0
- package/src/controller/provisioning-config.ts +289 -0
- package/src/controller/repo-routes.ts +84 -12
- package/src/controller/report-routes.ts +64 -0
- package/src/controller/route-table.ts +139 -1152
- package/src/controller/security.ts +899 -0
- package/src/controller/status-routes.ts +354 -0
- package/src/controller/task-assignment.ts +5 -1
- package/src/controller/task-execution.ts +43 -0
- package/src/controller/task-results.ts +12 -0
- package/src/controller/tunnel-manager.ts +45 -8
- package/src/controller/tunnel-routes.ts +231 -0
- package/src/controller/websocket.ts +20 -3
- package/src/controller/webui-routes.ts +55 -0
- package/src/controller/worker-provisioning.ts +51 -1117
- package/src/controller/workflow-routes.ts +498 -0
- package/src/controller/workspace-routes.ts +222 -0
- package/src/git-collaboration.ts +4 -9
- package/src/identity.ts +13 -1
- package/src/openclaw-workspace.ts +47 -0
- package/src/profile-loader.ts +167 -1
- package/src/profiles/banking.json +26 -2
- package/src/profiles/schema.json +82 -2
- package/src/prompt-policy.ts +19 -6
- package/src/protocol.ts +72 -2
- package/src/shared/clarification-schema.ts +81 -0
- package/src/shared/github-auth.ts +92 -0
- package/src/shared/kickoff-prompt.ts +47 -0
- package/src/shared/utils.ts +51 -0
- package/src/state.ts +92 -3
- package/src/teamauto/github-client.ts +2 -1
- package/src/teamauto/repo-sync.ts +2 -1
- package/src/teamauto/scanner.ts +22 -3
- package/src/teamauto/scheduler.ts +11 -3
- package/src/teamauto/store.ts +5 -0
- package/src/types.ts +130 -1
- package/src/ui/app.js +990 -73
- package/src/ui/github-login.html +1 -0
- package/src/ui/index.html +125 -36
- package/src/worker/http-handler.ts +64 -1
- package/src/worker/skill-installer.ts +3 -9
- package/src/worker/tools.ts +21 -10
- package/src/worker/worker-service.ts +18 -4
|
@@ -0,0 +1,775 @@
|
|
|
1
|
+
// ===========================================================================
|
|
2
|
+
// Controller device-pairing security (issue #23, backend wave).
|
|
3
|
+
//
|
|
4
|
+
// Zero-friction ladder (product semantics, FIXED - do not change):
|
|
5
|
+
// L0 local - no devices persisted => zero authentication (today's
|
|
6
|
+
// behavior; a TeamState without `security` or with an empty
|
|
7
|
+
// devices array is L0)
|
|
8
|
+
// L1 LAN - LAN peers (loopback / RFC1918 / ULA / link-local) may
|
|
9
|
+
// self-pair via POST /api/v1/security/pair-auto while
|
|
10
|
+
// config.security.autoPair is true (default) - the mDNS
|
|
11
|
+
// discovery scenario, zero user input
|
|
12
|
+
// L2 exposed - one-shot 60s pairing codes (8-char uppercase base32)
|
|
13
|
+
// minted by an authenticated device or the loopback console
|
|
14
|
+
// The user NEVER configures a token and the UI NEVER shows a login page.
|
|
15
|
+
// Each paired device holds its own 32-byte token (revocation granularity);
|
|
16
|
+
// only the sha256 hash is persisted, the plaintext is returned exactly once
|
|
17
|
+
// (web UI: HttpOnly SameSite=Strict cookie; worker/desktop/cli: their own
|
|
18
|
+
// config stores - client wave).
|
|
19
|
+
//
|
|
20
|
+
// Escape hatches (deliberate, physical-access trust model):
|
|
21
|
+
// - POST /api/v1/security/enable is LOOPBACK-ONLY: the L2 console is the
|
|
22
|
+
// controller host itself. A remote caller able to "enable" would mint
|
|
23
|
+
// the FIRST device token and own the team, so remote enable is a 403.
|
|
24
|
+
// - POST /api/v1/security/reset accepts an authenticated device OR a
|
|
25
|
+
// loopback caller: whoever has physical access to the controller host
|
|
26
|
+
// can always fall back to L0 (anti-lockout hatch).
|
|
27
|
+
//
|
|
28
|
+
// Module boundaries: this module never imports http-server.ts or
|
|
29
|
+
// route-table.ts at runtime (route-table imports the handlers below;
|
|
30
|
+
// route-table/route-context back-references are TYPE ONLY), keeping the
|
|
31
|
+
// controller module graph acyclic like the PR-C domain modules.
|
|
32
|
+
// ===========================================================================
|
|
33
|
+
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
34
|
+
import net from "node:net";
|
|
35
|
+
import { parseJsonBody, sendJson } from "../protocol.js";
|
|
36
|
+
import { secretsEqual } from "../protocol.js";
|
|
37
|
+
// ---------------------------------------------------------------------------
|
|
38
|
+
// Constants
|
|
39
|
+
// ---------------------------------------------------------------------------
|
|
40
|
+
/** Session cookie set by /security/enable (and honored on every /api/v1 route). */
|
|
41
|
+
export const SESSION_COOKIE_NAME = "teamclaw_session";
|
|
42
|
+
/** Cookie lifetime: 30 days; revoking the device invalidates it regardless. */
|
|
43
|
+
export const SESSION_COOKIE_MAX_AGE_SECONDS = 30 * 24 * 60 * 60;
|
|
44
|
+
/** Pairing code entropy/shape: 8 chars of RFC 4648 base32 = 40 random bits. */
|
|
45
|
+
export const PAIRING_CODE_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
|
46
|
+
export const PAIRING_CODE_LENGTH = 8;
|
|
47
|
+
export const PAIRING_CODE_TTL_MS = 60_000;
|
|
48
|
+
/** Device token size (hex string is twice this). */
|
|
49
|
+
const TOKEN_BYTES = 32;
|
|
50
|
+
/** lastSeenAt persistence throttle: at most one state write per interval. */
|
|
51
|
+
const LAST_SEEN_PERSIST_INTERVAL_MS = 30_000;
|
|
52
|
+
/** Suggestion-signal persistence throttle (per source IP). */
|
|
53
|
+
const NON_LAN_SIGNAL_PERSIST_INTERVAL_MS = 60_000;
|
|
54
|
+
/** Online guessing throttle for POST /security/pair (defense in depth on top of the 40-bit code + 60s TTL). */
|
|
55
|
+
const PAIR_FAILURE_WINDOW_MS = 5 * 60_000;
|
|
56
|
+
const PAIR_FAILURE_MAX = 20;
|
|
57
|
+
const DEVICE_KINDS = ["web", "worker", "desktop", "cli"];
|
|
58
|
+
const DEFAULT_DEVICE_NAMES = {
|
|
59
|
+
web: "Web UI",
|
|
60
|
+
worker: "Worker",
|
|
61
|
+
desktop: "Desktop",
|
|
62
|
+
cli: "CLI",
|
|
63
|
+
};
|
|
64
|
+
/** Pairing endpoints are exempt from the bearer middleware: each enforces its OWN stricter origin rule below. */
|
|
65
|
+
const SECURITY_EXEMPT_POST_PATHS = new Set([
|
|
66
|
+
"/api/v1/security/enable",
|
|
67
|
+
"/api/v1/security/pair/start",
|
|
68
|
+
"/api/v1/security/pair",
|
|
69
|
+
"/api/v1/security/pair-auto",
|
|
70
|
+
"/api/v1/security/reset",
|
|
71
|
+
]);
|
|
72
|
+
const HEALTH_PATH = "/api/v1/health";
|
|
73
|
+
// ---------------------------------------------------------------------------
|
|
74
|
+
// Token / pairing-code primitives
|
|
75
|
+
// ---------------------------------------------------------------------------
|
|
76
|
+
/** Generates a fresh device token (64-char hex). Shown to the caller ONCE. */
|
|
77
|
+
export function generateToken() {
|
|
78
|
+
return randomBytes(TOKEN_BYTES).toString("hex");
|
|
79
|
+
}
|
|
80
|
+
/** sha256 hex of a device token - the ONLY representation persisted. */
|
|
81
|
+
export function hashToken(token) {
|
|
82
|
+
return createHash("sha256").update(token, "utf8").digest("hex");
|
|
83
|
+
}
|
|
84
|
+
/** Constant-time secret comparison lives in protocol.ts (leaf module) since
|
|
85
|
+
* the #259 dependency gate - controller/security re-exports it for its
|
|
86
|
+
* historical importers (tunnel-routes) so no external call site changes. */
|
|
87
|
+
export { secretsEqual };
|
|
88
|
+
/** 8-char uppercase base32 code from 40 random bits (5 bytes -> exactly 8 chars, no padding). */
|
|
89
|
+
export function generatePairingCode() {
|
|
90
|
+
const bytes = randomBytes(5); // 5 bytes = 40 bits = exactly PAIRING_CODE_LENGTH base32 chars
|
|
91
|
+
let out = "";
|
|
92
|
+
let bitBuf = 0;
|
|
93
|
+
let bitCount = 0;
|
|
94
|
+
for (const byte of bytes) {
|
|
95
|
+
bitBuf = (bitBuf << 8) | byte;
|
|
96
|
+
bitCount += 8;
|
|
97
|
+
while (bitCount >= 5 && out.length < PAIRING_CODE_LENGTH) {
|
|
98
|
+
bitCount -= 5;
|
|
99
|
+
out += PAIRING_CODE_ALPHABET[(bitBuf >>> bitCount) & 31];
|
|
100
|
+
}
|
|
101
|
+
if (out.length >= PAIRING_CODE_LENGTH) {
|
|
102
|
+
break;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return out;
|
|
106
|
+
}
|
|
107
|
+
function mintPairingCode() {
|
|
108
|
+
return { code: generatePairingCode(), expiresAt: Date.now() + PAIRING_CODE_TTL_MS, purpose: "device-pairing" };
|
|
109
|
+
}
|
|
110
|
+
// ---------------------------------------------------------------------------
|
|
111
|
+
// Peer classification (pure functions)
|
|
112
|
+
// ---------------------------------------------------------------------------
|
|
113
|
+
/** Lowercases, strips IPv6 zone ids and unwraps IPv4-mapped IPv6 (::ffff:a.b.c.d). */
|
|
114
|
+
export function normalizePeerIp(ip) {
|
|
115
|
+
if (typeof ip !== "string") {
|
|
116
|
+
return "";
|
|
117
|
+
}
|
|
118
|
+
let value = ip.trim().toLowerCase();
|
|
119
|
+
const zoneIndex = value.indexOf("%");
|
|
120
|
+
if (zoneIndex > 0) {
|
|
121
|
+
value = value.slice(0, zoneIndex);
|
|
122
|
+
}
|
|
123
|
+
if (value.startsWith("::ffff:")) {
|
|
124
|
+
const tail = value.slice("::ffff:".length);
|
|
125
|
+
if (net.isIPv4(tail)) {
|
|
126
|
+
value = tail;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return value;
|
|
130
|
+
}
|
|
131
|
+
/** Loopback = 127.0.0.0/8 or ::1 (the controller console itself). */
|
|
132
|
+
export function isLoopbackIp(ip) {
|
|
133
|
+
const value = normalizePeerIp(ip);
|
|
134
|
+
if (!value) {
|
|
135
|
+
return false;
|
|
136
|
+
}
|
|
137
|
+
if (value === "::1") {
|
|
138
|
+
return true;
|
|
139
|
+
}
|
|
140
|
+
return net.isIPv4(value) && value.startsWith("127.");
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* LAN = loopback, RFC1918 (10/8, 172.16/12, 192.168/16), IPv4 link-local
|
|
144
|
+
* (169.254/16), IPv6 link-local (fe80::/10) and ULA (fc00::/7). Zero-input
|
|
145
|
+
* pairing (L1) is bounded to exactly this set.
|
|
146
|
+
*/
|
|
147
|
+
export function isLanIp(ip) {
|
|
148
|
+
const value = normalizePeerIp(ip);
|
|
149
|
+
if (!value) {
|
|
150
|
+
return false;
|
|
151
|
+
}
|
|
152
|
+
if (isLoopbackIp(value)) {
|
|
153
|
+
return true;
|
|
154
|
+
}
|
|
155
|
+
if (net.isIPv4(value)) {
|
|
156
|
+
const [a, b] = value.split(".").map(Number);
|
|
157
|
+
if (a === 10)
|
|
158
|
+
return true; // 10.0.0.0/8
|
|
159
|
+
if (a === 172 && b >= 16 && b <= 31)
|
|
160
|
+
return true; // 172.16.0.0/12
|
|
161
|
+
if (a === 192 && b === 168)
|
|
162
|
+
return true; // 192.168.0.0/16
|
|
163
|
+
if (a === 169 && b === 254)
|
|
164
|
+
return true; // 169.254.0.0/16 link-local
|
|
165
|
+
return false;
|
|
166
|
+
}
|
|
167
|
+
if (net.isIPv6(value)) {
|
|
168
|
+
if (/^f[cd]/.test(value))
|
|
169
|
+
return true; // fc00::/7 ULA
|
|
170
|
+
if (/^fe[89ab]/.test(value))
|
|
171
|
+
return true; // fe80::/10 link-local
|
|
172
|
+
return false;
|
|
173
|
+
}
|
|
174
|
+
return false;
|
|
175
|
+
}
|
|
176
|
+
export function classifySecurityPeer(ip, viaTunnel) {
|
|
177
|
+
const normalized = normalizePeerIp(ip) || "unknown";
|
|
178
|
+
return {
|
|
179
|
+
ip: normalized,
|
|
180
|
+
viaTunnel,
|
|
181
|
+
loopback: !viaTunnel && isLoopbackIp(normalized),
|
|
182
|
+
lan: !viaTunnel && isLanIp(normalized),
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
// ---------------------------------------------------------------------------
|
|
186
|
+
// State helpers
|
|
187
|
+
// ---------------------------------------------------------------------------
|
|
188
|
+
/** Protection is ON iff at least one paired device exists (the ladder switch). */
|
|
189
|
+
export function isProtectionOn(state) {
|
|
190
|
+
return (state?.security?.devices?.length ?? 0) > 0;
|
|
191
|
+
}
|
|
192
|
+
function ensureSecurityState(state) {
|
|
193
|
+
state.security ??= { devices: [] };
|
|
194
|
+
return state.security;
|
|
195
|
+
}
|
|
196
|
+
// ---------------------------------------------------------------------------
|
|
197
|
+
// Token extraction / verification
|
|
198
|
+
// ---------------------------------------------------------------------------
|
|
199
|
+
function tokenFromCookieHeader(cookie) {
|
|
200
|
+
if (typeof cookie !== "string" || !cookie) {
|
|
201
|
+
return null;
|
|
202
|
+
}
|
|
203
|
+
const match = cookie.match(new RegExp(`(?:^|;\\s*)${SESSION_COOKIE_NAME}=([^\\s;]+)`));
|
|
204
|
+
const value = match?.[1];
|
|
205
|
+
return value ? value : null;
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* Device token sources, in priority order: Authorization: Bearer,
|
|
209
|
+
* X-TeamClaw-Token, then the teamclaw_session cookie. All three compare
|
|
210
|
+
* against the SAME per-device token hash set.
|
|
211
|
+
*/
|
|
212
|
+
export function extractDeviceToken(req) {
|
|
213
|
+
const authorization = req.headers.authorization;
|
|
214
|
+
if (typeof authorization === "string" && authorization.startsWith("Bearer ")) {
|
|
215
|
+
const token = authorization.slice("Bearer ".length).trim();
|
|
216
|
+
if (token) {
|
|
217
|
+
return token;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
const header = req.headers["x-teamclaw-token"];
|
|
221
|
+
if (typeof header === "string" && header.trim()) {
|
|
222
|
+
return header.trim();
|
|
223
|
+
}
|
|
224
|
+
const cookie = tokenFromCookieHeader(typeof req.headers.cookie === "string" ? req.headers.cookie : undefined);
|
|
225
|
+
return cookie && cookie.trim() ? cookie.trim() : null;
|
|
226
|
+
}
|
|
227
|
+
/** Timing-safe token verification against every stored device hash. */
|
|
228
|
+
export function authenticateDeviceToken(state, token) {
|
|
229
|
+
if (!state?.security || !token) {
|
|
230
|
+
return null;
|
|
231
|
+
}
|
|
232
|
+
const tokenHash = hashToken(token);
|
|
233
|
+
for (const device of state.security.devices) {
|
|
234
|
+
if (secretsEqual(device.tokenHash, tokenHash)) {
|
|
235
|
+
return { device };
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
return null;
|
|
239
|
+
}
|
|
240
|
+
// ---------------------------------------------------------------------------
|
|
241
|
+
// CORS policy (issue #23: narrowed while protection is on)
|
|
242
|
+
// ---------------------------------------------------------------------------
|
|
243
|
+
/** True when the request's Origin matches the Host it was addressed to (the UI's own origin). */
|
|
244
|
+
export function isSameOriginRequest(req) {
|
|
245
|
+
const origin = req.headers.origin;
|
|
246
|
+
const host = req.headers.host;
|
|
247
|
+
if (typeof origin !== "string" || !origin || typeof host !== "string" || !host.trim()) {
|
|
248
|
+
return false;
|
|
249
|
+
}
|
|
250
|
+
try {
|
|
251
|
+
return new URL(origin).host.toLowerCase() === host.trim().toLowerCase();
|
|
252
|
+
}
|
|
253
|
+
catch {
|
|
254
|
+
return false;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* Preflight policy. Protection OFF: byte-identical to the historical
|
|
259
|
+
* wildcard preflight (L0 zero drift). Protection ON: same-origin origins
|
|
260
|
+
* are echoed (with the auth headers whitelisted so paired UIs can send
|
|
261
|
+
* them), a foreign Origin gets an explicit 403 (the browser blocks the
|
|
262
|
+
* actual request), and requests without an Origin header (non-browser
|
|
263
|
+
* clients) answer plainly.
|
|
264
|
+
*/
|
|
265
|
+
export function corsPreflightDecision(req, protectionOn) {
|
|
266
|
+
if (!protectionOn) {
|
|
267
|
+
return {
|
|
268
|
+
status: 200,
|
|
269
|
+
headers: {
|
|
270
|
+
"Access-Control-Allow-Origin": "*",
|
|
271
|
+
"Access-Control-Allow-Methods": "GET, POST, PATCH, DELETE, OPTIONS",
|
|
272
|
+
"Access-Control-Allow-Headers": "Content-Type",
|
|
273
|
+
},
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
const methods = "GET, POST, PATCH, DELETE, OPTIONS";
|
|
277
|
+
const allowHeaders = "Content-Type, Authorization, X-TeamClaw-Token";
|
|
278
|
+
const origin = typeof req.headers.origin === "string" ? req.headers.origin : "";
|
|
279
|
+
if (!origin) {
|
|
280
|
+
return { status: 200, headers: { "Access-Control-Allow-Methods": methods, "Access-Control-Allow-Headers": allowHeaders } };
|
|
281
|
+
}
|
|
282
|
+
if (!isSameOriginRequest(req)) {
|
|
283
|
+
return { status: 403, headers: { Vary: "Origin" } };
|
|
284
|
+
}
|
|
285
|
+
return {
|
|
286
|
+
status: 200,
|
|
287
|
+
headers: {
|
|
288
|
+
"Access-Control-Allow-Origin": origin,
|
|
289
|
+
"Access-Control-Allow-Methods": methods,
|
|
290
|
+
"Access-Control-Allow-Headers": allowHeaders,
|
|
291
|
+
Vary: "Origin",
|
|
292
|
+
},
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* Narrows the Access-Control-Allow-Origin of every response while
|
|
297
|
+
* protection is on, by pinning the header BEFORE dispatch: same-origin
|
|
298
|
+
* requests echo their origin; foreign origins get an explicit empty value
|
|
299
|
+
* (protocol.sendJson honors a pinned header, so no route can widen it back
|
|
300
|
+
* to the L0 wildcard); requests without an Origin header (non-browser
|
|
301
|
+
* clients) need no CORS headers at all. Protection OFF: no-op (wildcard
|
|
302
|
+
* behavior everywhere, unchanged).
|
|
303
|
+
*/
|
|
304
|
+
export function applyResponseCorsPolicy(req, res, protectionOn) {
|
|
305
|
+
if (!protectionOn) {
|
|
306
|
+
return;
|
|
307
|
+
}
|
|
308
|
+
const origin = typeof req.headers.origin === "string" ? req.headers.origin : "";
|
|
309
|
+
if (!origin) {
|
|
310
|
+
return;
|
|
311
|
+
}
|
|
312
|
+
if (!isSameOriginRequest(req)) {
|
|
313
|
+
res.setHeader("Access-Control-Allow-Origin", "");
|
|
314
|
+
res.setHeader("Vary", "Origin");
|
|
315
|
+
return;
|
|
316
|
+
}
|
|
317
|
+
res.setHeader("Access-Control-Allow-Origin", origin);
|
|
318
|
+
res.setHeader("Vary", "Origin");
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* True when the request path must NOT be blocked by the device gate:
|
|
322
|
+
* health (liveness probes), UI static assets and the tunnel gate pages
|
|
323
|
+
* (every non-/api path - static UI code carries no team data and the
|
|
324
|
+
* unpaired browser still needs to load the page that DISPLAYS the pairing
|
|
325
|
+
* hint), and the five pairing endpoints which each enforce a stricter
|
|
326
|
+
* rule of their own (enable/reset: loopback-or-authenticated;
|
|
327
|
+
* pair/start: authenticated-or-loopback; pair: one-shot code;
|
|
328
|
+
* pair-auto: LAN peer + config switch).
|
|
329
|
+
*/
|
|
330
|
+
export function isSecurityExemptPath(method, pathname) {
|
|
331
|
+
if (!pathname.startsWith("/api/")) {
|
|
332
|
+
return true;
|
|
333
|
+
}
|
|
334
|
+
if (pathname === HEALTH_PATH) {
|
|
335
|
+
return true;
|
|
336
|
+
}
|
|
337
|
+
return method === "POST" && SECURITY_EXEMPT_POST_PATHS.has(pathname);
|
|
338
|
+
}
|
|
339
|
+
function sendUnauthorized(res) {
|
|
340
|
+
sendJson(res, 401, {
|
|
341
|
+
error: "unauthorized",
|
|
342
|
+
hint: "This TeamClaw controller requires paired devices. From a LAN host: POST /api/v1/security/pair-auto {\"kind\":\"cli\",\"name\":\"...\"}. Otherwise ask the controller owner for a pairing code and POST /api/v1/security/pair {\"code\",\"kind\",\"name\"}.",
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* Suggestion signal (protection off): remember the latest non-LAN peer so
|
|
347
|
+
* /api/v1/team/status can recommend enabling protection. Throttled per
|
|
348
|
+
* source IP to keep scanners from turning it into a write storm (at most
|
|
349
|
+
* one persisted observation per peer per interval; the recorded path is
|
|
350
|
+
* simply the most recent one seen).
|
|
351
|
+
*/
|
|
352
|
+
function recordNonLanPeerSignal(deps, state, peer, pathname) {
|
|
353
|
+
if (!state || peer.lan || !pathname.startsWith("/api/")) {
|
|
354
|
+
return;
|
|
355
|
+
}
|
|
356
|
+
const now = Date.now();
|
|
357
|
+
const last = state.security?.lastNonLanPeer;
|
|
358
|
+
if (last && last.ip === peer.ip && now - last.at < NON_LAN_SIGNAL_PERSIST_INTERVAL_MS) {
|
|
359
|
+
return;
|
|
360
|
+
}
|
|
361
|
+
const observation = { ip: peer.ip, at: now, path: pathname };
|
|
362
|
+
deps.updateTeamState((s) => {
|
|
363
|
+
ensureSecurityState(s).lastNonLanPeer = observation;
|
|
364
|
+
});
|
|
365
|
+
}
|
|
366
|
+
/** Throttled lastSeenAt persistence: in-memory freshness, bounded write rate. */
|
|
367
|
+
function touchDeviceLastSeen(deps, deviceId) {
|
|
368
|
+
const device = deps.getTeamState()?.security?.devices.find((entry) => entry.id === deviceId);
|
|
369
|
+
if (!device) {
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
const now = Date.now();
|
|
373
|
+
if (device.lastSeenAt && now - device.lastSeenAt < LAST_SEEN_PERSIST_INTERVAL_MS) {
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
deps.updateTeamState((s) => {
|
|
377
|
+
const target = s.security?.devices.find((entry) => entry.id === deviceId);
|
|
378
|
+
if (target) {
|
|
379
|
+
target.lastSeenAt = now;
|
|
380
|
+
}
|
|
381
|
+
});
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* The device gate. Returns true to proceed. While protection is on every
|
|
385
|
+
* non-exempt /api request must present a valid device token (Bearer /
|
|
386
|
+
* X-TeamClaw-Token / session cookie); the matched device's lastSeenAt is
|
|
387
|
+
* refreshed (throttled) and unauthenticated callers get a 401 whose body
|
|
388
|
+
* points at the pairing commands instead of leaking any team detail.
|
|
389
|
+
*/
|
|
390
|
+
export function createSecurityMiddleware(deps) {
|
|
391
|
+
return function enforceDeviceAuth(req, res, pathname, peer) {
|
|
392
|
+
const state = deps.getTeamState();
|
|
393
|
+
const protectionOn = isProtectionOn(state);
|
|
394
|
+
applyResponseCorsPolicy(req, res, protectionOn);
|
|
395
|
+
if (!protectionOn) {
|
|
396
|
+
recordNonLanPeerSignal(deps, state, peer, pathname);
|
|
397
|
+
return true;
|
|
398
|
+
}
|
|
399
|
+
if (isSecurityExemptPath(req.method ?? "", pathname)) {
|
|
400
|
+
return true;
|
|
401
|
+
}
|
|
402
|
+
const auth = authenticateDeviceToken(state, extractDeviceToken(req));
|
|
403
|
+
if (!auth) {
|
|
404
|
+
deps.logger.warn(`Controller: rejected unauthenticated ${req.method ?? "?"} ${pathname} from ${peer.ip}${peer.viaTunnel ? " (via tunnel)" : ""}`);
|
|
405
|
+
sendUnauthorized(res);
|
|
406
|
+
return false;
|
|
407
|
+
}
|
|
408
|
+
touchDeviceLastSeen(deps, auth.device.id);
|
|
409
|
+
return true;
|
|
410
|
+
};
|
|
411
|
+
}
|
|
412
|
+
export function createWebSocketUpgradeGuard(deps) {
|
|
413
|
+
return function verifyUpgrade(req) {
|
|
414
|
+
const viaTunnel = deps.isTunnelHost(typeof req.headers.host === "string" ? req.headers.host : undefined);
|
|
415
|
+
const peer = classifySecurityPeer(req.socket.remoteAddress, viaTunnel);
|
|
416
|
+
const state = deps.getTeamState();
|
|
417
|
+
if (!isProtectionOn(state)) {
|
|
418
|
+
recordNonLanPeerSignal(deps, state, peer, "/ws");
|
|
419
|
+
return true;
|
|
420
|
+
}
|
|
421
|
+
let token = extractDeviceToken(req);
|
|
422
|
+
if (!token) {
|
|
423
|
+
const url = new URL(req.url ?? "/ws", `http://${req.headers.host ?? "localhost"}`);
|
|
424
|
+
const queryToken = url.searchParams.get("token");
|
|
425
|
+
if (queryToken && queryToken.trim()) {
|
|
426
|
+
token = queryToken.trim();
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
const auth = authenticateDeviceToken(state, token);
|
|
430
|
+
if (!auth) {
|
|
431
|
+
deps.logger.warn(`Controller: rejected WebSocket upgrade from ${peer.ip}${peer.viaTunnel ? " (via tunnel)" : ""}`);
|
|
432
|
+
return false;
|
|
433
|
+
}
|
|
434
|
+
touchDeviceLastSeen(deps, auth.device.id);
|
|
435
|
+
return true;
|
|
436
|
+
};
|
|
437
|
+
}
|
|
438
|
+
// ---------------------------------------------------------------------------
|
|
439
|
+
// Serialization (never leaks tokenHash / pairing code text where it is not
|
|
440
|
+
// already owned by the caller)
|
|
441
|
+
// ---------------------------------------------------------------------------
|
|
442
|
+
function serializeDevice(device) {
|
|
443
|
+
return {
|
|
444
|
+
id: device.id,
|
|
445
|
+
name: device.name,
|
|
446
|
+
kind: device.kind,
|
|
447
|
+
createdAt: device.createdAt,
|
|
448
|
+
...(device.lastSeenAt !== undefined ? { lastSeenAt: device.lastSeenAt } : {}),
|
|
449
|
+
...(device.origin !== undefined ? { origin: device.origin } : {}),
|
|
450
|
+
};
|
|
451
|
+
}
|
|
452
|
+
// ---------------------------------------------------------------------------
|
|
453
|
+
// Route handlers (registered in route-table.ts; each receives the peer
|
|
454
|
+
// classification computed by the composition root)
|
|
455
|
+
// ---------------------------------------------------------------------------
|
|
456
|
+
function newDeviceId() {
|
|
457
|
+
return `dev-${randomUUID()}`;
|
|
458
|
+
}
|
|
459
|
+
function parseDeviceKind(raw) {
|
|
460
|
+
return DEVICE_KINDS.includes(raw) ? raw : "cli";
|
|
461
|
+
}
|
|
462
|
+
function parseDeviceName(raw, kind) {
|
|
463
|
+
if (typeof raw !== "string") {
|
|
464
|
+
return DEFAULT_DEVICE_NAMES[kind];
|
|
465
|
+
}
|
|
466
|
+
const cleaned = raw.replace(/[\u0000-\u001f\u007f]/g, "").trim().slice(0, 64);
|
|
467
|
+
return cleaned || DEFAULT_DEVICE_NAMES[kind];
|
|
468
|
+
}
|
|
469
|
+
function mintDevice(kind, name, origin) {
|
|
470
|
+
const token = generateToken();
|
|
471
|
+
// lastSeenAt intentionally unset: it is stamped by the device's first
|
|
472
|
+
// AUTHENTICATED request (touchDeviceLastSeen), so a minted-but-never-used
|
|
473
|
+
// device is distinguishable in the UI from an active one.
|
|
474
|
+
const device = {
|
|
475
|
+
id: newDeviceId(),
|
|
476
|
+
name,
|
|
477
|
+
kind,
|
|
478
|
+
tokenHash: hashToken(token),
|
|
479
|
+
createdAt: Date.now(),
|
|
480
|
+
origin,
|
|
481
|
+
};
|
|
482
|
+
return { device, token };
|
|
483
|
+
}
|
|
484
|
+
// POST /api/v1/security/enable - LOOPBACK ONLY (see module header).
|
|
485
|
+
export async function handleSecurityEnableRequest(ctx) {
|
|
486
|
+
const { res, deps, peer } = ctx;
|
|
487
|
+
if (!peer || !peer.loopback) {
|
|
488
|
+
sendJson(res, 403, {
|
|
489
|
+
error: "forbidden",
|
|
490
|
+
hint: "Device protection can only be enabled from the controller host (loopback); a remote caller must never be able to mint the first device token.",
|
|
491
|
+
});
|
|
492
|
+
return;
|
|
493
|
+
}
|
|
494
|
+
if (isProtectionOn(deps.getTeamState())) {
|
|
495
|
+
sendJson(res, 409, {
|
|
496
|
+
error: "Device protection is already enabled",
|
|
497
|
+
hint: "Issue additional pairing codes with POST /api/v1/security/pair/start and pair new devices with POST /api/v1/security/pair.",
|
|
498
|
+
});
|
|
499
|
+
return;
|
|
500
|
+
}
|
|
501
|
+
const { device, token } = mintDevice("web", DEFAULT_DEVICE_NAMES.web, "loopback");
|
|
502
|
+
const pairingCode = mintPairingCode();
|
|
503
|
+
const now = Date.now();
|
|
504
|
+
deps.updateTeamState((s) => {
|
|
505
|
+
const security = ensureSecurityState(s);
|
|
506
|
+
security.devices.push(device);
|
|
507
|
+
security.enabledAt ??= now;
|
|
508
|
+
security.pairingCode = pairingCode;
|
|
509
|
+
});
|
|
510
|
+
deps.logger.info(`Controller: device protection enabled (web device ${device.id}); one-shot pairing code issued for the first external device`);
|
|
511
|
+
res.setHeader("Set-Cookie", `${SESSION_COOKIE_NAME}=${token}; Path=/api/v1; Max-Age=${SESSION_COOKIE_MAX_AGE_SECONDS}; HttpOnly; SameSite=Strict`);
|
|
512
|
+
sendJson(res, 201, {
|
|
513
|
+
protection: true,
|
|
514
|
+
device: serializeDevice(device),
|
|
515
|
+
pairingCode: { code: pairingCode.code, expiresAt: pairingCode.expiresAt, purpose: pairingCode.purpose },
|
|
516
|
+
});
|
|
517
|
+
}
|
|
518
|
+
// POST /api/v1/security/pair/start - authenticated device or loopback.
|
|
519
|
+
export async function handleSecurityPairStartRequest(ctx) {
|
|
520
|
+
const { req, res, deps, peer } = ctx;
|
|
521
|
+
const state = deps.getTeamState();
|
|
522
|
+
if (!isProtectionOn(state)) {
|
|
523
|
+
sendJson(res, 409, {
|
|
524
|
+
error: "Device protection is not enabled",
|
|
525
|
+
hint: "Enable it first from the controller host: POST /api/v1/security/enable (loopback only).",
|
|
526
|
+
});
|
|
527
|
+
return;
|
|
528
|
+
}
|
|
529
|
+
const auth = authenticateDeviceToken(state, extractDeviceToken(req));
|
|
530
|
+
if (!auth && !(peer?.loopback ?? false)) {
|
|
531
|
+
sendUnauthorized(res);
|
|
532
|
+
return;
|
|
533
|
+
}
|
|
534
|
+
const pairingCode = mintPairingCode(); // a new code invalidates the previous one by replacement
|
|
535
|
+
deps.updateTeamState((s) => {
|
|
536
|
+
ensureSecurityState(s).pairingCode = pairingCode;
|
|
537
|
+
});
|
|
538
|
+
deps.logger.info("Controller: issued a new one-shot pairing code (previous code invalidated)");
|
|
539
|
+
sendJson(res, 201, { pairingCode: { code: pairingCode.code, expiresAt: pairingCode.expiresAt, purpose: pairingCode.purpose } });
|
|
540
|
+
}
|
|
541
|
+
// In-process online-guessing throttle for POST /security/pair.
|
|
542
|
+
const pairFailureTimestamps = [];
|
|
543
|
+
function pairFailureThrottled() {
|
|
544
|
+
const now = Date.now();
|
|
545
|
+
while (pairFailureTimestamps.length > 0 && now - pairFailureTimestamps[0] >= PAIR_FAILURE_WINDOW_MS) {
|
|
546
|
+
pairFailureTimestamps.shift();
|
|
547
|
+
}
|
|
548
|
+
return pairFailureTimestamps.length >= PAIR_FAILURE_MAX;
|
|
549
|
+
}
|
|
550
|
+
function recordPairFailure() {
|
|
551
|
+
pairFailureTimestamps.push(Date.now());
|
|
552
|
+
}
|
|
553
|
+
// POST /api/v1/security/pair {code, kind, name} - one-shot code exchange.
|
|
554
|
+
export async function handleSecurityPairRequest(ctx) {
|
|
555
|
+
const { req, res, deps } = ctx;
|
|
556
|
+
const state = deps.getTeamState();
|
|
557
|
+
if (!isProtectionOn(state)) {
|
|
558
|
+
sendJson(res, 409, {
|
|
559
|
+
error: "Device protection is not enabled",
|
|
560
|
+
hint: "Pairing codes only exist while protection is on; enable it from the controller host first.",
|
|
561
|
+
});
|
|
562
|
+
return;
|
|
563
|
+
}
|
|
564
|
+
let body;
|
|
565
|
+
try {
|
|
566
|
+
body = await parseJsonBody(req);
|
|
567
|
+
}
|
|
568
|
+
catch {
|
|
569
|
+
sendJson(res, 400, "invalid JSON body");
|
|
570
|
+
return;
|
|
571
|
+
}
|
|
572
|
+
const submitted = typeof body.code === "string" ? body.code.trim().toUpperCase() : "";
|
|
573
|
+
if (!submitted) {
|
|
574
|
+
sendJson(res, 400, "code is required");
|
|
575
|
+
return;
|
|
576
|
+
}
|
|
577
|
+
if (pairFailureThrottled()) {
|
|
578
|
+
res.setHeader("Retry-After", "60");
|
|
579
|
+
sendJson(res, 429, { error: "too many failed pairing attempts", hint: "Wait and ask the controller owner for a fresh pairing code." });
|
|
580
|
+
return;
|
|
581
|
+
}
|
|
582
|
+
const kind = parseDeviceKind(body.kind);
|
|
583
|
+
const name = parseDeviceName(body.name, kind);
|
|
584
|
+
const codeShapeOk = /^[A-Z2-7]{8}$/.test(submitted);
|
|
585
|
+
const result = {
|
|
586
|
+
outcome: "invalid",
|
|
587
|
+
minted: null,
|
|
588
|
+
};
|
|
589
|
+
deps.updateTeamState((s) => {
|
|
590
|
+
const security = s.security;
|
|
591
|
+
const active = security?.pairingCode;
|
|
592
|
+
if (!security || !active || !codeShapeOk || !secretsEqual(active.code, submitted)) {
|
|
593
|
+
result.outcome = "invalid";
|
|
594
|
+
return;
|
|
595
|
+
}
|
|
596
|
+
if (active.usedAt !== undefined) {
|
|
597
|
+
result.outcome = "used";
|
|
598
|
+
return;
|
|
599
|
+
}
|
|
600
|
+
if (Date.now() >= active.expiresAt) {
|
|
601
|
+
delete security.pairingCode; // prune the dead secret
|
|
602
|
+
result.outcome = "expired";
|
|
603
|
+
return;
|
|
604
|
+
}
|
|
605
|
+
const created = mintDevice(kind, name, peerOriginLabel(ctx));
|
|
606
|
+
active.usedAt = Date.now();
|
|
607
|
+
security.devices.push(created.device);
|
|
608
|
+
result.minted = created;
|
|
609
|
+
result.outcome = "ok";
|
|
610
|
+
});
|
|
611
|
+
if (result.outcome === "ok" && result.minted) {
|
|
612
|
+
deps.logger.info(`Controller: paired new ${kind} device ${result.minted.device.id} ("${name}") via pairing code`);
|
|
613
|
+
sendJson(res, 201, {
|
|
614
|
+
token: result.minted.token,
|
|
615
|
+
deviceId: result.minted.device.id,
|
|
616
|
+
device: serializeDevice(result.minted.device),
|
|
617
|
+
});
|
|
618
|
+
return;
|
|
619
|
+
}
|
|
620
|
+
recordPairFailure();
|
|
621
|
+
const hints = {
|
|
622
|
+
ok: ["unreachable", ""],
|
|
623
|
+
invalid: ["invalid pairing code", "Ask the controller owner for the current code (it is single-use and expires 60s after issue)."],
|
|
624
|
+
used: ["pairing code already used", "Each code pairs exactly one device; ask for a fresh one."],
|
|
625
|
+
expired: ["pairing code expired", "Codes live 60 seconds; ask the controller owner to issue a new one."],
|
|
626
|
+
};
|
|
627
|
+
const [error, hint] = hints[result.outcome];
|
|
628
|
+
sendJson(res, 400, { error, hint });
|
|
629
|
+
}
|
|
630
|
+
// POST /api/v1/security/pair-auto - LAN peer + config.security.autoPair + protection on.
|
|
631
|
+
export async function handleSecurityPairAutoRequest(ctx) {
|
|
632
|
+
const { res, deps, peer } = ctx;
|
|
633
|
+
if (!isProtectionOn(deps.getTeamState())) {
|
|
634
|
+
sendJson(res, 409, {
|
|
635
|
+
error: "Device protection is not enabled",
|
|
636
|
+
hint: "Auto-pairing only applies once protection is on; enable it from the controller host first.",
|
|
637
|
+
});
|
|
638
|
+
return;
|
|
639
|
+
}
|
|
640
|
+
if (!peer || !peer.lan) {
|
|
641
|
+
sendJson(res, 403, {
|
|
642
|
+
error: "forbidden",
|
|
643
|
+
hint: "Zero-input auto-pairing is limited to LAN peers; use a pairing code instead (POST /api/v1/security/pair {\"code\",\"kind\",\"name\"}).",
|
|
644
|
+
});
|
|
645
|
+
return;
|
|
646
|
+
}
|
|
647
|
+
if ((deps.config.security?.autoPair ?? true) !== true) {
|
|
648
|
+
sendJson(res, 403, {
|
|
649
|
+
error: "auto-pairing is disabled on this controller",
|
|
650
|
+
hint: "The owner disabled security.autoPair; ask for a pairing code and POST /api/v1/security/pair {\"code\",\"kind\",\"name\"}.",
|
|
651
|
+
});
|
|
652
|
+
return;
|
|
653
|
+
}
|
|
654
|
+
let body = {};
|
|
655
|
+
try {
|
|
656
|
+
body = await parseJsonBody(ctx.req);
|
|
657
|
+
}
|
|
658
|
+
catch {
|
|
659
|
+
body = {}; // body optional for auto-pair
|
|
660
|
+
}
|
|
661
|
+
const kind = parseDeviceKind(body.kind);
|
|
662
|
+
const name = parseDeviceName(body.name, kind);
|
|
663
|
+
const { device, token } = mintDevice(kind, name, peerOriginLabel(ctx));
|
|
664
|
+
deps.updateTeamState((s) => {
|
|
665
|
+
ensureSecurityState(s).devices.push(device);
|
|
666
|
+
});
|
|
667
|
+
deps.logger.info(`Controller: paired new ${kind} device ${device.id} ("${name}") via LAN auto-pairing from ${peer.ip}`);
|
|
668
|
+
sendJson(res, 201, { token, deviceId: device.id, device: serializeDevice(device) });
|
|
669
|
+
}
|
|
670
|
+
// GET /api/v1/security - status (authenticated by the middleware while protection is on).
|
|
671
|
+
export async function handleSecurityGetRequest(ctx) {
|
|
672
|
+
const { res, deps } = ctx;
|
|
673
|
+
const state = deps.getTeamState();
|
|
674
|
+
const security = state?.security;
|
|
675
|
+
const pairingCode = security?.pairingCode;
|
|
676
|
+
const active = pairingCode && pairingCode.usedAt === undefined && Date.now() < pairingCode.expiresAt
|
|
677
|
+
? pairingCode
|
|
678
|
+
: undefined;
|
|
679
|
+
sendJson(res, 200, {
|
|
680
|
+
protection: isProtectionOn(state),
|
|
681
|
+
devices: (security?.devices ?? []).map(serializeDevice),
|
|
682
|
+
...(active ? { pairingCode: { expiresAt: active.expiresAt, purpose: active.purpose } } : {}),
|
|
683
|
+
autoPair: deps.config.security?.autoPair ?? true,
|
|
684
|
+
});
|
|
685
|
+
}
|
|
686
|
+
// DELETE /api/v1/security/devices/:id - authenticated (middleware). Revoking
|
|
687
|
+
// the caller's OWN device is allowed on purpose: the UI revoking itself
|
|
688
|
+
// simply forces that browser to re-pair.
|
|
689
|
+
export async function handleSecurityDeviceDeleteRequest(ctx) {
|
|
690
|
+
const { req, res, deps, pathname } = ctx;
|
|
691
|
+
const deviceId = decodeURIComponent(pathname.split("/").pop() ?? "");
|
|
692
|
+
const state = deps.getTeamState();
|
|
693
|
+
const devices = state?.security?.devices ?? [];
|
|
694
|
+
if (!devices.some((device) => device.id === deviceId)) {
|
|
695
|
+
sendJson(res, 404, "Device not found");
|
|
696
|
+
return;
|
|
697
|
+
}
|
|
698
|
+
const caller = authenticateDeviceToken(state, extractDeviceToken(req));
|
|
699
|
+
deps.updateTeamState((s) => {
|
|
700
|
+
if (!s.security) {
|
|
701
|
+
return;
|
|
702
|
+
}
|
|
703
|
+
s.security.devices = s.security.devices.filter((device) => device.id !== deviceId);
|
|
704
|
+
});
|
|
705
|
+
const revokedSelf = caller?.device.id === deviceId;
|
|
706
|
+
const protection = isProtectionOn(deps.getTeamState());
|
|
707
|
+
deps.logger.info(`Controller: revoked device ${deviceId}${revokedSelf ? " (self-revocation; that client must re-pair)" : ""}; protection now ${protection ? "on" : "off"}`);
|
|
708
|
+
sendJson(res, 200, { ok: true, revoked: deviceId, revokedSelf, protection });
|
|
709
|
+
}
|
|
710
|
+
// POST /api/v1/security/reset - authenticated OR loopback (anti-lockout
|
|
711
|
+
// hatch), plus an explicit confirm token (#255 P1-8): a paired device must
|
|
712
|
+
// knowingly opt in, since the reset drops protection to L0 for EVERYONE.
|
|
713
|
+
export async function handleSecurityResetRequest(ctx) {
|
|
714
|
+
const { req, res, deps, peer } = ctx;
|
|
715
|
+
const state = deps.getTeamState();
|
|
716
|
+
const auth = authenticateDeviceToken(state, extractDeviceToken(req));
|
|
717
|
+
if (!auth && !(peer?.loopback ?? false)) {
|
|
718
|
+
sendUnauthorized(res);
|
|
719
|
+
return;
|
|
720
|
+
}
|
|
721
|
+
const body = await parseJsonBody(req);
|
|
722
|
+
if (body.confirm !== "RESET") {
|
|
723
|
+
sendJson(res, 400, { error: 'security reset requires confirm:"RESET" in the body (destructive: revokes every paired device)' });
|
|
724
|
+
return;
|
|
725
|
+
}
|
|
726
|
+
deps.updateTeamState((s) => {
|
|
727
|
+
delete s.security; // back to L0: no devices, no codes, no signal history
|
|
728
|
+
// #255 P1-8 audit: broadcast through the existing team message channel
|
|
729
|
+
// so every UI surface sees the protection-level drop. (ws push would need
|
|
730
|
+
// a deps surface security.ts does not own; the message + log line are the
|
|
731
|
+
// minimal in-scope audit trail.)
|
|
732
|
+
s.messages.push({
|
|
733
|
+
id: `security-reset-${Date.now().toString(36)}`,
|
|
734
|
+
from: "controller",
|
|
735
|
+
type: "broadcast",
|
|
736
|
+
content: `Device protection reset by ${auth ? `device ${auth.device.id}` : `loopback peer ${peer?.ip ?? "unknown"}`} (confirm:"RESET") - all paired devices revoked, protection level L0.`,
|
|
737
|
+
createdAt: Date.now(),
|
|
738
|
+
});
|
|
739
|
+
});
|
|
740
|
+
deps.logger.info("Controller: device protection reset (all devices revoked, confirm received) - controller is back to unpaired L0");
|
|
741
|
+
sendJson(res, 200, { ok: true, protection: false });
|
|
742
|
+
}
|
|
743
|
+
function peerOriginLabel(ctx) {
|
|
744
|
+
const peer = ctx.peer;
|
|
745
|
+
if (!peer) {
|
|
746
|
+
return "unknown";
|
|
747
|
+
}
|
|
748
|
+
if (peer.viaTunnel) {
|
|
749
|
+
return "tunnel";
|
|
750
|
+
}
|
|
751
|
+
return peer.ip;
|
|
752
|
+
}
|
|
753
|
+
/**
|
|
754
|
+
* The `security` sub-object of GET /api/v1/team/status: protection state,
|
|
755
|
+
* whether enabling protection is SUGGESTED (a non-LAN peer was observed
|
|
756
|
+
* while L0), a human-readable reason, and the device count. Zero route
|
|
757
|
+
* changes beyond attaching this field at the assembly point.
|
|
758
|
+
*/
|
|
759
|
+
export function buildTeamStatusSecurity(state) {
|
|
760
|
+
const protection = isProtectionOn(state);
|
|
761
|
+
const observation = state?.security?.lastNonLanPeer;
|
|
762
|
+
const suggested = !protection && Boolean(observation);
|
|
763
|
+
const reason = protection
|
|
764
|
+
? "Device pairing protection is active."
|
|
765
|
+
: observation
|
|
766
|
+
? `A non-LAN peer (${observation.ip}) recently reached ${observation.path}; enable device pairing to require per-device tokens.`
|
|
767
|
+
: "";
|
|
768
|
+
return {
|
|
769
|
+
protection,
|
|
770
|
+
suggested,
|
|
771
|
+
reason,
|
|
772
|
+
deviceCount: state?.security?.devices.length ?? 0,
|
|
773
|
+
...(observation ? { lastNonLanPeer: observation } : {}),
|
|
774
|
+
};
|
|
775
|
+
}
|