Compare commits

..
Author SHA1 Message Date
Peter Steinberger 2ce267400c fix: allow token auth without device identity (#1314) (thanks @dbhurley) 2026-01-21 02:44:28 +00:00
David HurleyandClaude Opus 4.5 d353db42ba fix: allow token auth to bypass device identity requirement
The device identity check was rejecting connections before token
authentication could be attempted. This broke the control-ui (web UI)
which uses token-based authentication via URL parameter.

Changes:
- Skip device identity requirement when a token is provided
- Guard device token verification to only run when device is present

Fixes control-ui showing "device identity required" error when
connecting with a valid token.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-21 02:20:56 +00:00
6 changed files with 84 additions and 229 deletions

No files matched your search

+1 -1
View File
@@ -29,6 +29,7 @@ Docs: https://docs.clawd.bot
- Model catalog: avoid caching import failures, log transient discovery errors, and keep partial results. (#1332) — thanks @dougvk. - Model catalog: avoid caching import failures, log transient discovery errors, and keep partial results. (#1332) — thanks @dougvk.
- Doctor: clarify plugin auto-enable hint text in the startup banner. - Doctor: clarify plugin auto-enable hint text in the startup banner.
- Gateway: clarify unauthorized handshake responses with token/password mismatch guidance. - Gateway: clarify unauthorized handshake responses with token/password mismatch guidance.
- Gateway: allow token-auth Control UI connections without device identity. (#1314) — thanks @dbhurley.
- Gateway: preserve restart wake routing + thread replies across restarts. (#1337) — thanks @John-Rood. - Gateway: preserve restart wake routing + thread replies across restarts. (#1337) — thanks @John-Rood.
- Gateway: reschedule per-agent heartbeats on config hot reload without restarting the runner. - Gateway: reschedule per-agent heartbeats on config hot reload without restarting the runner.
- Config: log invalid config issues once per run and keep invalid-config errors stackless. - Config: log invalid config issues once per run and keep invalid-config errors stackless.
@@ -39,7 +40,6 @@ Docs: https://docs.clawd.bot
- TUI: keep thinking blocks ordered before content during streaming and isolate per-run assembly. (#1202) — thanks @aaronveklabs. - TUI: keep thinking blocks ordered before content during streaming and isolate per-run assembly. (#1202) — thanks @aaronveklabs.
- TUI: align custom editor initialization with the latest pi-tui API. (#1298) — thanks @sibbl. - TUI: align custom editor initialization with the latest pi-tui API. (#1298) — thanks @sibbl.
- CLI: avoid duplicating --profile/--dev flags when formatting commands. - CLI: avoid duplicating --profile/--dev flags when formatting commands.
- CLI: make `clawdbot logs --follow` output stable, keep spinners, and surface closed pipes. (#1318) — thanks @sebslight.
- Status: route native `/status` to the active agent so model selection reflects the correct profile. (#1301) - Status: route native `/status` to the active agent so model selection reflects the correct profile. (#1301)
- Exec: prefer bash when fish is default shell, falling back to sh if bash is missing. (#1297) — thanks @ysqander. - Exec: prefer bash when fish is default shell, falling back to sh if bash is missing. (#1297) — thanks @ysqander.
- Exec: merge login-shell PATH for host=gateway exec while keeping daemon PATH minimal. (#1304) - Exec: merge login-shell PATH for host=gateway exec while keeping daemon PATH minimal. (#1304)
-85
View File
@@ -1,85 +0,0 @@
import { Command } from "commander";
import { afterEach, describe, expect, it, vi } from "vitest";
const callGatewayFromCli = vi.fn();
vi.mock("./gateway-rpc.js", async () => {
const actual = await vi.importActual<typeof import("./gateway-rpc.js")>("./gateway-rpc.js");
return {
...actual,
callGatewayFromCli: (...args: unknown[]) => callGatewayFromCli(...args),
};
});
describe("logs cli", () => {
afterEach(() => {
callGatewayFromCli.mockReset();
});
it("writes output directly to stdout/stderr", async () => {
callGatewayFromCli.mockResolvedValueOnce({
file: "/tmp/clawdbot.log",
cursor: 1,
size: 123,
lines: ["raw line"],
truncated: true,
reset: true,
});
const stdoutWrites: string[] = [];
const stderrWrites: string[] = [];
const stdoutSpy = vi.spyOn(process.stdout, "write").mockImplementation((chunk: unknown) => {
stdoutWrites.push(String(chunk));
return true;
});
const stderrSpy = vi.spyOn(process.stderr, "write").mockImplementation((chunk: unknown) => {
stderrWrites.push(String(chunk));
return true;
});
const { registerLogsCli } = await import("./logs-cli.js");
const program = new Command();
program.exitOverride();
registerLogsCli(program);
await program.parseAsync(["logs"], { from: "user" });
stdoutSpy.mockRestore();
stderrSpy.mockRestore();
expect(stdoutWrites.join("")).toContain("Log file:");
expect(stdoutWrites.join("")).toContain("raw line");
expect(stderrWrites.join("")).toContain("Log tail truncated");
expect(stderrWrites.join("")).toContain("Log cursor reset");
});
it("warns when the output pipe closes", async () => {
callGatewayFromCli.mockResolvedValueOnce({
file: "/tmp/clawdbot.log",
lines: ["line one"],
});
const stderrWrites: string[] = [];
const stdoutSpy = vi.spyOn(process.stdout, "write").mockImplementation(() => {
const err = new Error("EPIPE") as NodeJS.ErrnoException;
err.code = "EPIPE";
throw err;
});
const stderrSpy = vi.spyOn(process.stderr, "write").mockImplementation((chunk: unknown) => {
stderrWrites.push(String(chunk));
return true;
});
const { registerLogsCli } = await import("./logs-cli.js");
const program = new Command();
program.exitOverride();
registerLogsCli(program);
await program.parseAsync(["logs"], { from: "user" });
stdoutSpy.mockRestore();
stderrSpy.mockRestore();
expect(stderrWrites.join("")).toContain("output stdout closed");
});
});
+43 -133
View File
@@ -2,8 +2,8 @@ import { setTimeout as delay } from "node:timers/promises";
import type { Command } from "commander"; import type { Command } from "commander";
import { buildGatewayConnectionDetails } from "../gateway/call.js"; import { buildGatewayConnectionDetails } from "../gateway/call.js";
import { parseLogLine } from "../logging/parse-log-line.js"; import { parseLogLine } from "../logging/parse-log-line.js";
import { defaultRuntime } from "../runtime.js";
import { formatDocsLink } from "../terminal/links.js"; import { formatDocsLink } from "../terminal/links.js";
import { clearActiveProgressLine } from "../terminal/progress-line.js";
import { colorize, isRich, theme } from "../terminal/theme.js"; import { colorize, isRich, theme } from "../terminal/theme.js";
import { formatCliCommand } from "./command-format.js"; import { formatCliCommand } from "./command-format.js";
import { addGatewayClientOptions, callGatewayFromCli } from "./gateway-rpc.js"; import { addGatewayClientOptions, callGatewayFromCli } from "./gateway-rpc.js";
@@ -104,68 +104,10 @@ function formatLogLine(
return [head, messageValue].filter(Boolean).join(" ").trim(); return [head, messageValue].filter(Boolean).join(" ").trim();
} }
let outputClosed = false; function emitJsonLine(payload: Record<string, unknown>, toStdErr = false) {
let outputClosedNotice = false;
function isBrokenPipeError(err: unknown): err is NodeJS.ErrnoException {
const code = (err as NodeJS.ErrnoException)?.code;
return code === "EPIPE" || code === "EIO";
}
function noteOutputClosed(err: NodeJS.ErrnoException, stream: NodeJS.WriteStream) {
if (outputClosedNotice) return;
outputClosedNotice = true;
const code = err.code ?? "EPIPE";
const target = stream === process.stdout ? "stdout" : "stderr";
const message = `clawdbot logs: output ${target} closed (${code}). Stopping tail.`;
try {
clearActiveProgressLine();
process.stderr.write(`${message}\n`);
} catch {
// ignore secondary failures while reporting the broken pipe
}
}
function handleWriteError(err: unknown, stream: NodeJS.WriteStream): boolean {
if (!isBrokenPipeError(err)) {
throw err;
}
outputClosed = true;
noteOutputClosed(err, stream);
return false;
}
function writeText(text: string, stream: NodeJS.WriteStream): boolean {
if (outputClosed) return false;
try {
clearActiveProgressLine();
} catch (err) {
if (!handleWriteError(err, process.stderr)) return false;
}
try {
stream.write(text);
return true;
} catch (err) {
return handleWriteError(err, stream);
}
}
function writeLine(text: string, stream: NodeJS.WriteStream): boolean {
// Avoid feeding CLI output back into the log file via console capture.
return writeText(`${text}\n`, stream);
}
function logLine(text: string): boolean {
return writeLine(text, process.stdout);
}
function errorLine(text: string): boolean {
return writeLine(text, process.stderr);
}
function emitJsonLine(payload: Record<string, unknown>, toStdErr = false): boolean {
const text = `${JSON.stringify(payload)}\n`; const text = `${JSON.stringify(payload)}\n`;
return writeText(text, toStdErr ? process.stderr : process.stdout); if (toStdErr) process.stderr.write(text);
else process.stdout.write(text);
} }
function emitGatewayError( function emitGatewayError(
@@ -180,26 +122,22 @@ function emitGatewayError(
const errorText = err instanceof Error ? err.message : String(err); const errorText = err instanceof Error ? err.message : String(err);
if (mode === "json") { if (mode === "json") {
if ( emitJsonLine(
!emitJsonLine( {
{ type: "error",
type: "error", message,
message, error: errorText,
error: errorText, details,
details, hint,
hint, },
}, true,
true, );
)
) {
return;
}
return; return;
} }
if (!errorLine(colorize(rich, theme.error, message))) return; defaultRuntime.error(colorize(rich, theme.error, message));
if (!errorLine(details.message)) return; defaultRuntime.error(details.message);
errorLine(colorize(rich, theme.muted, hint)); defaultRuntime.error(colorize(rich, theme.muted, hint));
} }
export function registerLogsCli(program: Command) { export function registerLogsCli(program: Command) {
@@ -221,8 +159,6 @@ export function registerLogsCli(program: Command) {
addGatewayClientOptions(logs); addGatewayClientOptions(logs);
logs.action(async (opts: LogsCliOptions) => { logs.action(async (opts: LogsCliOptions) => {
outputClosed = false;
outputClosedNotice = false;
const interval = parsePositiveInt(opts.interval, 1000); const interval = parsePositiveInt(opts.interval, 1000);
let cursor: number | undefined; let cursor: number | undefined;
let first = true; let first = true;
@@ -236,83 +172,57 @@ export function registerLogsCli(program: Command) {
payload = await fetchLogs(opts, cursor); payload = await fetchLogs(opts, cursor);
} catch (err) { } catch (err) {
emitGatewayError(err, opts, jsonMode ? "json" : "text", rich); emitGatewayError(err, opts, jsonMode ? "json" : "text", rich);
process.exit(1); defaultRuntime.exit(1);
return; return;
} }
const lines = Array.isArray(payload.lines) ? payload.lines : []; const lines = Array.isArray(payload.lines) ? payload.lines : [];
if (jsonMode) { if (jsonMode) {
if (first) { if (first) {
if ( emitJsonLine({
!emitJsonLine({ type: "meta",
type: "meta", file: payload.file,
file: payload.file, cursor: payload.cursor,
cursor: payload.cursor, size: payload.size,
size: payload.size, });
})
) {
return;
}
} }
for (const line of lines) { for (const line of lines) {
const parsed = parseLogLine(line); const parsed = parseLogLine(line);
if (parsed) { if (parsed) {
if (!emitJsonLine({ type: "log", ...parsed })) { emitJsonLine({ type: "log", ...parsed });
return;
}
} else { } else {
if (!emitJsonLine({ type: "raw", raw: line })) { emitJsonLine({ type: "raw", raw: line });
return;
}
} }
} }
if (payload.truncated) { if (payload.truncated) {
if ( emitJsonLine({
!emitJsonLine({ type: "notice",
type: "notice", message: "Log tail truncated (increase --max-bytes).",
message: "Log tail truncated (increase --max-bytes).", });
})
) {
return;
}
} }
if (payload.reset) { if (payload.reset) {
if ( emitJsonLine({
!emitJsonLine({ type: "notice",
type: "notice", message: "Log cursor reset (file rotated).",
message: "Log cursor reset (file rotated).", });
})
) {
return;
}
} }
} else { } else {
if (first && payload.file) { if (first && payload.file) {
const prefix = pretty ? colorize(rich, theme.muted, "Log file:") : "Log file:"; const prefix = pretty ? colorize(rich, theme.muted, "Log file:") : "Log file:";
if (!logLine(`${prefix} ${payload.file}`)) { defaultRuntime.log(`${prefix} ${payload.file}`);
return;
}
} }
for (const line of lines) { for (const line of lines) {
if ( defaultRuntime.log(
!logLine( formatLogLine(line, {
formatLogLine(line, { pretty,
pretty, rich,
rich, }),
}), );
)
) {
return;
}
} }
if (payload.truncated) { if (payload.truncated) {
if (!errorLine("Log tail truncated (increase --max-bytes).")) { defaultRuntime.error("Log tail truncated (increase --max-bytes).");
return;
}
} }
if (payload.reset) { if (payload.reset) {
if (!errorLine("Log cursor reset (file rotated).")) { defaultRuntime.error("Log cursor reset (file rotated).");
return;
}
} }
} }
cursor = cursor =
+27
View File
@@ -102,6 +102,33 @@ describe("gateway server auth/connect", () => {
} }
}); });
test("accepts token auth without device identity", async () => {
const { server, ws, prevToken } = await startServerWithClient("secret");
const res = await connectReq(ws, { token: "secret", device: null });
expect(res.ok).toBe(true);
ws.close();
await server.close();
if (prevToken === undefined) {
delete process.env.CLAWDBOT_GATEWAY_TOKEN;
} else {
process.env.CLAWDBOT_GATEWAY_TOKEN = prevToken;
}
});
test("requires device identity when auth mode is none", async () => {
const { server, ws, prevToken } = await startServerWithClient();
const res = await connectReq(ws, { device: null });
expect(res.ok).toBe(false);
expect(res.error?.message ?? "").toContain("device identity required");
ws.close();
await server.close();
if (prevToken === undefined) {
delete process.env.CLAWDBOT_GATEWAY_TOKEN;
} else {
process.env.CLAWDBOT_GATEWAY_TOKEN = prevToken;
}
});
test("accepts password auth when configured", async () => { test("accepts password auth when configured", async () => {
testState.gatewayAuth = { mode: "password", password: "secret" }; testState.gatewayAuth = { mode: "password", password: "secret" };
const port = await getFreePort(); const port = await getFreePort();
@@ -290,9 +290,18 @@ export function attachGatewayWsMessageHandler(params: {
connectParams.role = role; connectParams.role = role;
connectParams.scopes = scopes; connectParams.scopes = scopes;
const authResult = await authorizeGatewayConnect({
auth: resolvedAuth,
connectAuth: connectParams.auth,
req: upgradeReq,
});
let authOk = authResult.ok;
let authMethod = authResult.method ?? "none";
const allowsDeviceOptional = authOk && authMethod === "token";
const device = connectParams.device; const device = connectParams.device;
let devicePublicKey: string | null = null; let devicePublicKey: string | null = null;
if (!device) { if (!device && !allowsDeviceOptional) {
setHandshakeState("failed"); setHandshakeState("failed");
setCloseCause("device-required", { setCloseCause("device-required", {
client: connectParams.client.id, client: connectParams.client.id,
@@ -458,14 +467,7 @@ export function attachGatewayWsMessageHandler(params: {
} }
} }
const authResult = await authorizeGatewayConnect({ if (!authOk && connectParams.auth?.token && device) {
auth: resolvedAuth,
connectAuth: connectParams.auth,
req: upgradeReq,
});
let authOk = authResult.ok;
let authMethod = authResult.method ?? "none";
if (!authOk && connectParams.auth?.token) {
const tokenCheck = await verifyDeviceToken({ const tokenCheck = await verifyDeviceToken({
deviceId: device.id, deviceId: device.id,
token: connectParams.auth.token, token: connectParams.auth.token,
+2 -1
View File
@@ -280,7 +280,7 @@ export async function connectReq(
signature: string; signature: string;
signedAt: number; signedAt: number;
nonce?: string; nonce?: string;
}; } | null;
}, },
): Promise<ConnectResponse> { ): Promise<ConnectResponse> {
const { randomUUID } = await import("node:crypto"); const { randomUUID } = await import("node:crypto");
@@ -294,6 +294,7 @@ export async function connectReq(
const role = opts?.role ?? "operator"; const role = opts?.role ?? "operator";
const requestedScopes = Array.isArray(opts?.scopes) ? opts?.scopes : []; const requestedScopes = Array.isArray(opts?.scopes) ? opts?.scopes : [];
const device = (() => { const device = (() => {
if (opts?.device === null) return undefined;
if (opts?.device) return opts.device; if (opts?.device) return opts.device;
const identity = loadOrCreateDeviceIdentity(); const identity = loadOrCreateDeviceIdentity();
const signedAtMs = Date.now(); const signedAtMs = Date.now();