From 6ccbfb0e1506adf829dd1da541de7f332d1c39f1 Mon Sep 17 00:00:00 2001 From: Rizon Date: Wed, 25 Nov 2026 22:58:50 +0000 Subject: [PATCH] feat(agent): add debug mode --- apps/agent/src/http/router.ts | 18 +++++++++++++++--- apps/agent/src/index.ts | 13 ++++++++++--- apps/agent/src/log.ts | 27 ++++++++++++++++++++++++--- apps/agent/src/panel.ts | 14 +++++++++++--- 4 files changed, 60 insertions(+), 12 deletions(-) diff --git a/apps/agent/src/http/router.ts b/apps/agent/src/http/router.ts index 02182e3..0b982a4 100644 --- a/apps/agent/src/http/router.ts +++ b/apps/agent/src/http/router.ts @@ -23,7 +23,7 @@ import type { DaemonServerDetails, SystemInfo } from "@bytepanel/protocol"; import type { Config } from "../config"; import { COMMIT, VERSION } from "../config"; import type { Docker } from "../docker"; -import { errorMessage, logger } from "../log"; +import { errorMessage, logger, redactUrl, debugEnabled } from "../log"; import type { Backups } from "../server/backups"; import { FilesystemError } from "../server/filesystem"; import type { ServerManager } from "../server/manager"; @@ -280,8 +280,7 @@ export const createFetchHandler = (deps: Deps) => { throw new HttpError(404, "route not found"); }; - return async (req: Request, bun: BunServer): Promise => { - const url = new URL(req.url); + const handle = async (req: Request, url: URL, bun: BunServer): Promise => { if (LONG_RUNNING.test(url.pathname)) { bun.timeout(req, 0); } @@ -369,4 +368,17 @@ export const createFetchHandler = (deps: Deps) => { return json({ error: errorMessage(error) }, status, cors(req)); } }; + + return async (req: Request, bun: BunServer): Promise => { + const url = new URL(req.url); + if (!debugEnabled()) { + return handle(req, url, bun); + } + const started = performance.now(); + const res = await handle(req, url, bun); + const ip = bun.requestIP(req)?.address ?? "unknown"; + const ms = Math.round(performance.now() - started); + log.debug(`${req.method} ${redactUrl(url)} -> ${res?.status ?? 101} (${ms}ms) from ${ip}`); + return res; + }; }; diff --git a/apps/agent/src/index.ts b/apps/agent/src/index.ts index 4f8e741..e660fd0 100644 --- a/apps/agent/src/index.ts +++ b/apps/agent/src/index.ts @@ -5,7 +5,7 @@ import { Docker } from "./docker"; import { createFetchHandler } from "./http/router"; import type { SocketData } from "./http/websocket"; import { websocketHandlers } from "./http/websocket"; -import { logger } from "./log"; +import { logger, debugEnabled, enableDebug } from "./log"; import { ActivityBuffer, PanelClient } from "./panel"; import { Backups } from "./server/backups"; import { ServerManager } from "./server/manager"; @@ -38,10 +38,17 @@ const configure = async (args: string[]) => { console.log(`Configuration for node ${saved.uuid} written to ${values.config}`); }; -const run = async () => { +const run = async (args: string[]) => { + const { values } = parseArgs({ args, options: { debug: { type: "boolean" } } }); + if (values.debug) { + enableDebug(); + } const config = await loadConfig(); await ensureDirectories(config); log.info(`BytePanel daemon v${VERSION} starting for node ${config.uuid}`); + if (debugEnabled()) { + log.warn("debug mode on: logging every API call (headers, bodies and tokens are never logged)"); + } const docker = new Docker(config.docker.socket); const dockerVersion = await docker.version(); @@ -108,7 +115,7 @@ try { break; } case "run": { - await run(); + await run(rest); break; } default: { diff --git a/apps/agent/src/log.ts b/apps/agent/src/log.ts index d14aedb..319f648 100644 --- a/apps/agent/src/log.ts +++ b/apps/agent/src/log.ts @@ -2,9 +2,18 @@ type Level = "debug" | "info" | "warn" | "error"; const LEVELS: Record = { debug: 10, error: 40, info: 20, warn: 30 }; -const threshold = - LEVELS[(process.env.BYTEPANEL_LOG_LEVEL as Level | undefined) ?? "info"] ?? - LEVELS.info; +const truthy = (value: string | undefined) => value === "1" || value?.toLowerCase() === "true"; + +let debug = truthy(process.env.BYTEPANEL_DEBUG); + +let threshold = debug ? LEVELS.debug : (LEVELS[(process.env.BYTEPANEL_LOG_LEVEL as Level | undefined) ?? "info"] ?? LEVELS.info); + +export const enableDebug = () => { + debug = true; + threshold = LEVELS.debug; +}; + +export const debugEnabled = () => debug; const write = (level: Level, scope: string, message: string, extra?: unknown) => { if (LEVELS[level] < threshold) { @@ -28,3 +37,15 @@ export const logger = (scope: string) => ({ export const errorMessage = (error: unknown): string => error instanceof Error ? error.message : String(error); + +const SENSITIVE_PARAM = /token|secret|password|key|signature|auth/iu; + +export const redactUrl = (url: URL): string => { + if (url.search === "") { + return url.pathname; + } + const params = [...url.searchParams].map(([name, value]) => + `${name}=${SENSITIVE_PARAM.test(name) ? "[redacted]" : value}`, + ); + return `${url.pathname}?${params.join("&")}`; +}; diff --git a/apps/agent/src/panel.ts b/apps/agent/src/panel.ts index bc337a8..6a772ab 100644 --- a/apps/agent/src/panel.ts +++ b/apps/agent/src/panel.ts @@ -16,7 +16,7 @@ import type { SftpAuthResponse, } from "@bytepanel/protocol"; import type { Config } from "./config"; -import { logger } from "./log"; +import { logger, redactUrl, errorMessage } from "./log"; const log = logger("panel"); @@ -41,6 +41,9 @@ export class PanelClient { const url = new URL(path, this.config.remote); let lastError: unknown; for (let attempt = 1; attempt <= attempts; attempt += 1) { + const started = performance.now(); + const tag = () => + `${method} ${redactUrl(url)}${attempt > 1 ? ` (attempt ${attempt}/${attempts})` : ""}`; try { const res = await fetch(url, { body: body === undefined ? undefined : JSON.stringify(body), @@ -53,6 +56,7 @@ export class PanelClient { method, signal: AbortSignal.timeout(30_000), }); + log.debug(`${tag()} -> ${res.status} (${Math.round(performance.now() - started)}ms)`); if (res.status === 204) { return null; } @@ -70,8 +74,12 @@ export class PanelClient { return text.length > 0 ? JSON.parse(text) : null; } } catch (error) { - if (error instanceof PanelError && error.status < 500) { - throw error; + if (error instanceof PanelError) { + if (error.status < 500) { + throw error; + } + } else { + log.debug(`${tag()} failed: ${errorMessage(error)}`); } lastError = error; }