Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions src/app/api/tools/agent-bridge/diagnose/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/**
* GET /api/tools/agent-bridge/diagnose
*
* Capture-pipeline self-test (Gap 12). Runs the independent checks that
* determine whether interception can work — server running, server reachable on
* its port, cert generated, cert trusted by the OS store, target hosts spoofed
* in DNS — and returns an actionable report (per-failure hints + a single
* `healthy` verdict). Answers "why is nothing being captured?" in one call.
*
* LOCAL_ONLY: covered by the "/api/tools/agent-bridge/" prefix in routeGuard.ts.
*/
import net from "node:net";
import path from "node:path";
import fs from "node:fs";
import { sanitizeErrorMessage } from "@omniroute/open-sse/utils/error";
import { createErrorResponse } from "@/lib/api/errorResponse";
import { getMitmStatus } from "@/mitm/manager";
import { checkCertInstalled } from "@/mitm/cert/install";
import { resolveMitmDataDir } from "@/mitm/dataDir";
import { summarizeDiagnostics } from "@/mitm/inspector/diagnostics";

/** Best-effort TCP reachability probe; resolves false on error/timeout. */
function probeTcp(port: number, host = "127.0.0.1", timeoutMs = 1500): Promise<boolean> {
return new Promise((resolve) => {
const socket = net.connect({ port, host });
const done = (ok: boolean) => {
try {
socket.destroy();
} catch {
// ignore
}
resolve(ok);
};
socket.setTimeout(timeoutMs, () => done(false));
socket.once("connect", () => done(true));
socket.once("error", () => done(false));
});
}

export async function GET(): Promise<Response> {
try {
const status = await getMitmStatus();
const certPath = path.join(resolveMitmDataDir(), "mitm", "server.crt");
const certExists = fs.existsSync(certPath);
const certTrusted = certExists ? await checkCertInstalled(certPath) : false;
const port =
Number(process.env.MITM_LOCAL_PORT) > 0 ? Number(process.env.MITM_LOCAL_PORT) : 443;
Comment on lines +46 to +47

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The current port parsing logic does not validate that the port is a valid integer within the allowed TCP port range (1-65535). If process.env.MITM_LOCAL_PORT is set to an out-of-range number (e.g., 70000) or a float, net.connect in probeTcp will throw a synchronous RangeError, causing the entire diagnostic endpoint to fail with a 500 error instead of returning a proper diagnostic report.

We should parse and validate the port to ensure it is a valid integer between 1 and 65535, defaulting to 443 otherwise.

Suggested change
const port =
Number(process.env.MITM_LOCAL_PORT) > 0 ? Number(process.env.MITM_LOCAL_PORT) : 443;
const envPort = Number(process.env.MITM_LOCAL_PORT);
const port = Number.isInteger(envPort) && envPort > 0 && envPort <= 65535 ? envPort : 443;

const serverReachable = status.running ? await probeTcp(port) : false;

const report = summarizeDiagnostics({
serverRunning: status.running,
serverReachable,
certExists,
certTrusted,
dnsConfigured: status.dnsConfigured,
});

return Response.json({ ...report, port });
} catch (err) {
const msg = sanitizeErrorMessage(err instanceof Error ? err.message : String(err));
return createErrorResponse({ status: 500, message: msg });
}
}
67 changes: 67 additions & 0 deletions src/mitm/inspector/diagnostics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/**
* Capture-pipeline self-test (Gap 12).
*
* MITM/AgentBridge setups fail silently in several independent ways — the cert
* is not trusted, the hosts are not spoofed, the server is down or unreachable
* on its port — and the user gets nothing actionable, just an empty capture
* list. `summarizeDiagnostics()` is the pure core: given each check's boolean
* result it produces a single `healthy` verdict plus a per-failure hint telling
* the user exactly what to fix. The route layer runs the effectful checks
* (getMitmStatus, checkCertInstalled, a TCP probe, checkDNSEntry) and feeds the
* booleans in here.
*/

export interface DiagnosticInput {
serverRunning: boolean;
serverReachable: boolean;
certExists: boolean;
certTrusted: boolean;
dnsConfigured: boolean;
}

export interface DiagnosticCheck {
name: string;
ok: boolean;
/** Actionable remediation when `ok` is false; null when the check passes. */
hint: string | null;
}

export interface DiagnosticReport {
healthy: boolean;
checks: DiagnosticCheck[];
}

function check(name: string, ok: boolean, failHint: string): DiagnosticCheck {
return { name, ok, hint: ok ? null : failHint };
}

export function summarizeDiagnostics(input: DiagnosticInput): DiagnosticReport {
const checks: DiagnosticCheck[] = [
check(
"server-running",
input.serverRunning,
"The MITM server is not running. Start it from the AgentBridge tab."
),
check(
"server-reachable",
input.serverReachable,
"The MITM server is not accepting connections on its port. Check that the port is free and that you have privileges to bind it."
),
check(
"cert-exists",
input.certExists,
"No MITM certificate has been generated yet. Generate one from the AgentBridge tab."
),
check(
"cert-trusted",
input.certTrusted,
"The MITM root CA is not trusted by the OS store, so TLS interception will fail. Trust the certificate from the AgentBridge tab."
),
check(
"dns-configured",
input.dnsConfigured,
"Target hostnames are not spoofed in /etc/hosts, so traffic never reaches the proxy. Enable DNS for the agent(s) you want to capture."
),
];
return { healthy: checks.every((c) => c.ok), checks };
}
64 changes: 64 additions & 0 deletions tests/unit/mitm-diagnostics.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/**
* Gap 12: capture-pipeline self-test. MITM setups fail silently in many ways
* (cert not trusted, DNS not spoofed, server down/unreachable) and the user
* gets no actionable signal. summarizeDiagnostics() is the pure core: given the
* boolean results of each check, it produces an actionable report with a single
* `healthy` verdict and a per-failure hint.
*/
import test from "node:test";
import assert from "node:assert/strict";
import { summarizeDiagnostics } from "../../src/mitm/inspector/diagnostics.ts";

test("all checks green → healthy, no hints", () => {
const report = summarizeDiagnostics({
serverRunning: true,
serverReachable: true,
certExists: true,
certTrusted: true,
dnsConfigured: true,
});
assert.equal(report.healthy, true);
assert.equal(report.checks.length, 5);
assert.ok(report.checks.every((c) => c.ok && c.hint === null));
});

test("cert not trusted → unhealthy with an actionable hint on that check", () => {
const report = summarizeDiagnostics({
serverRunning: true,
serverReachable: true,
certExists: true,
certTrusted: false,
dnsConfigured: true,
});
assert.equal(report.healthy, false);
const certCheck = report.checks.find((c) => c.name === "cert-trusted");
assert.ok(certCheck, "must include a cert-trusted check");
assert.equal(certCheck!.ok, false);
assert.ok(certCheck!.hint && certCheck!.hint.length > 0, "must give an actionable hint");
});

test("server down → unhealthy and the server-running check carries the hint", () => {
const report = summarizeDiagnostics({
serverRunning: false,
serverReachable: false,
certExists: true,
certTrusted: true,
dnsConfigured: true,
});
assert.equal(report.healthy, false);
const runCheck = report.checks.find((c) => c.name === "server-running");
assert.equal(runCheck?.ok, false);
assert.ok(runCheck?.hint);
});

test("every failing check has a non-null hint; every passing check has null", () => {
const report = summarizeDiagnostics({
serverRunning: false,
serverReachable: false,
certExists: false,
certTrusted: false,
dnsConfigured: false,
});
assert.equal(report.healthy, false);
assert.ok(report.checks.every((c) => !c.ok && typeof c.hint === "string" && c.hint.length > 0));
});
Loading