* test(web): audit branch-coverage outliers, raise per-file gate to 70 (#1271) The web per-file coverage gate had drifted red: the recently-landed EMA auth feature (core/auth/ema/*) and ClientSettings components shipped undertested, and the prior 50% branch floor let business-logic branches go untested. CI does not run the coverage gate, so this accumulated. Add tests to bring every failing file above the gate and push branch coverage well past 70 across the board, then raise the per-file branches threshold 50 -> 70 in clients/web/vite.config.ts. - EMA core (emaFlow, resourceContext, jwt, wire): 50-88% -> 86-100% branch - EMA OIDC/transport (idpOidc, tokenEndpoint, transportProvider): -> 97-100% - oauthManager / discovery: 73-83% -> 88-92% - ClientSettingsModal/Form, ConnectionInfoContent: 0-88% -> 96-100% - useClientSettingsDraft / useEmaIdpLoginState hooks: 20% -> 100% - TaskStatusBadge / SortableServerCard outliers: 50% -> 100% Coverable branches reached by mocking useComputedColorScheme (dark theme), dnd-kit useSortable (isDragging), and fetch/OIDC paths. Remaining sub-100 branches are genuinely-unreachable defensive guards or happy-dom-inherent (portal / useMediaQuery / typeof window) and documented in test comments. No source files changed. Global web branch coverage 88.73% -> 90.63%. AGENTS.md updated; cli/tui/launcher stay at 50 (out of scope). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * test: raise per-file coverage gate to 90/90/90/90 across all clients Follows the #1271 web branch-coverage audit (50 -> 70) by raising the whole per-file gate to >=90 on all four dimensions — lines, statements, functions, branches — for web, cli, tui, and launcher (core/ is measured under the web suite). A codebase-wide audit added real tests for every outlier and brought global coverage up across the board. Config: all four vitest/vite coverage configs set to 90/90/90/90. Two pure-type modules (core/mcp/import/types.ts, clients/web/server/ types.ts) added to the web coverage exclude list, matching the existing type-only exclusions. Tests: ~50 test files extended/created across core (auth, ema, mcp, remote, state, storage, react), web components/screens/server, and the cli/tui clients. Highlights: full EMA OAuth flow + transport coverage, inspectorClient/remote server backfill, every Mantine control's handler branches, and the cli unsupported-method / argv-fallback paths. Genuinely-unreachable branches are annotated at the source with justified `/* v8 ignore -- <reason> */` comments rather than lowering the gate: happy-dom-inherent paths (Mantine portal, useMediaQuery, typeof window SSR guards), React StrictMode effect replay, and provably-dead defensive guards (?? fallbacks the types make impossible, Select.onChange values outside the allowed list). No runtime logic changed; the only structural edits are two behavior-preserving refactors (ResourceTemplatePanel hoists the field value to a local so the ignore applies in JSX; ToolsScreen swaps a ternary for an if) and prettier line-wrapping. Also fixed a flaky real-timer debounce assertion in PromptArgumentsForm (asserted an exact sibling-typing interleaving that raced the 300ms debounce; now asserts the load-bearing fact — a non-empty fire-time sibling capture). AGENTS.md updated to describe the uniform 90 gate and the v8-ignore policy. All four client coverage gates, root validate, storybook (370), and smoke pass. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * test(web): make connect-crash SSE reader stop on the terminal event `readSseEvents` looped until the server closed the stream (`done`). The server closes the events stream immediately after writing the terminal `transport_error`, but under the heavy parallel scheduler pressure of a full `coverage` run (v8 instrumentation across all workers) that close can lag far enough behind the event to trip the 30s test timeout — a hang, not a wrong result. This made the test intermittently fail under `npm run coverage` (it passed in isolation and under CI's lighter `test:integration`). Stop reading as soon as the terminal `transport_error` event arrives (cancelling the reader) instead of waiting only for `done`. That event is always the last one the session queue emits, so nothing is lost, and the test no longer depends on stream-close timing. The `done` break is kept for any stream that closes first. Verified green across two consecutive full `npm run test:coverage` runs (3094 tests) where it previously hung, plus isolation (~0.5s). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
223 lines
6.3 KiB
TypeScript
223 lines
6.3 KiB
TypeScript
import { createServer, type Server } from "node:http";
|
|
import { parseOAuthCallbackParams } from "../utils.js";
|
|
import { generateOAuthErrorDescription } from "../utils.js";
|
|
|
|
const DEFAULT_HOSTNAME = "127.0.0.1";
|
|
const DEFAULT_CALLBACK_PATH = "/oauth/callback";
|
|
|
|
const SUCCESS_HTML = `<!DOCTYPE html>
|
|
<html>
|
|
<head><meta charset="utf-8"><title>OAuth complete</title></head>
|
|
<body><p>OAuth complete. You can close this window.</p></body>
|
|
</html>`;
|
|
|
|
function errorHtml(message: string): string {
|
|
return `<!DOCTYPE html>
|
|
<html>
|
|
<head><meta charset="utf-8"><title>OAuth error</title></head>
|
|
<body><p>OAuth failed: ${escapeHtml(message)}</p></body>
|
|
</html>`;
|
|
}
|
|
|
|
function escapeHtml(s: string): string {
|
|
return s
|
|
.replace(/&/g, "&")
|
|
.replace(/</g, "<")
|
|
.replace(/>/g, ">")
|
|
.replace(/"/g, """);
|
|
}
|
|
|
|
export type OAuthCallbackHandler = (params: {
|
|
code: string;
|
|
state?: string;
|
|
}) => Promise<void>;
|
|
|
|
export type OAuthErrorHandler = (params: {
|
|
error: string;
|
|
error_description?: string | null;
|
|
}) => void;
|
|
|
|
export interface OAuthCallbackServerStartOptions {
|
|
port?: number;
|
|
hostname?: string;
|
|
path?: string;
|
|
onCallback?: OAuthCallbackHandler;
|
|
onError?: OAuthErrorHandler;
|
|
}
|
|
|
|
export interface OAuthCallbackServerStartResult {
|
|
port: number;
|
|
redirectUrl: string;
|
|
}
|
|
|
|
/**
|
|
* Minimal HTTP server that receives OAuth 2.1 redirects at GET /oauth/callback.
|
|
* Used by TUI/CLI to complete the authorization code flow (both quick and guided).
|
|
* Caller provides onCallback/onError; typically onCallback calls
|
|
* InspectorClient.completeOAuthFlow(code) then stops the server.
|
|
*/
|
|
export class OAuthCallbackServer {
|
|
private server: Server | null = null;
|
|
private port: number = 0;
|
|
private callbackPath: string = DEFAULT_CALLBACK_PATH;
|
|
private handled = false;
|
|
private onCallback?: OAuthCallbackHandler;
|
|
private onError?: OAuthErrorHandler;
|
|
|
|
/**
|
|
* Start the server. Listens on the given port (default 0 = random).
|
|
* Returns port and redirectUrl for use as oauth.redirectUrl.
|
|
*/
|
|
async start(
|
|
options: OAuthCallbackServerStartOptions = {},
|
|
): Promise<OAuthCallbackServerStartResult> {
|
|
const {
|
|
port = 0,
|
|
hostname = DEFAULT_HOSTNAME,
|
|
path = DEFAULT_CALLBACK_PATH,
|
|
onCallback,
|
|
onError,
|
|
} = options;
|
|
if (!path.startsWith("/")) {
|
|
return Promise.reject(
|
|
new Error("Callback path must start with '/' (absolute path)"),
|
|
);
|
|
}
|
|
this.onCallback = onCallback;
|
|
this.onError = onError;
|
|
this.handled = false;
|
|
this.callbackPath = path;
|
|
|
|
return new Promise((resolve, reject) => {
|
|
this.server = createServer((req, res) => this.handleRequest(req, res));
|
|
this.server.on("error", reject);
|
|
this.server.listen(port, hostname, () => {
|
|
const a = this.server!.address();
|
|
/* v8 ignore next 4 -- defensive: a TCP server that has fired its
|
|
`listen` callback always reports an AddressInfo object (never null
|
|
and never a string, which only happens for a pipe/unix socket),
|
|
so this guard is unreachable from a successful `listen(port, host)`. */
|
|
if (!a || typeof a === "string") {
|
|
reject(new Error("Failed to get server address"));
|
|
return;
|
|
}
|
|
this.port = a.port;
|
|
resolve({
|
|
port: this.port,
|
|
redirectUrl: buildRedirectUrl(hostname, this.port, path),
|
|
});
|
|
});
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Stop the server. Idempotent.
|
|
*/
|
|
async stop(): Promise<void> {
|
|
if (!this.server) return;
|
|
await new Promise<void>((resolve) => {
|
|
this.server!.close(() => resolve());
|
|
});
|
|
this.server = null;
|
|
}
|
|
|
|
private handleRequest(
|
|
req: import("node:http").IncomingMessage,
|
|
res: import("node:http").ServerResponse<
|
|
import("node:http").IncomingMessage
|
|
>,
|
|
): void {
|
|
const needJson = req.headers["accept"]?.includes("application/json");
|
|
|
|
const send = (
|
|
status: number,
|
|
body: string,
|
|
contentType = "text/html; charset=utf-8",
|
|
) => {
|
|
res.writeHead(status, { "Content-Type": contentType });
|
|
res.end(body);
|
|
};
|
|
|
|
if (req.method !== "GET") {
|
|
send(405, needJson ? '{"error":"Method Not Allowed"}' : SUCCESS_HTML);
|
|
return;
|
|
}
|
|
|
|
let pathname: string;
|
|
let search: string;
|
|
let state: string | undefined;
|
|
try {
|
|
const u = new URL(
|
|
/* v8 ignore next -- defensive: Node always populates req.url for an
|
|
HTTP request, so the `?? ""` fallback is never taken. */
|
|
req.url ?? "",
|
|
"http://placeholder",
|
|
);
|
|
pathname = u.pathname;
|
|
search = u.search;
|
|
state = u.searchParams.get("state") ?? undefined;
|
|
} catch {
|
|
send(400, needJson ? '{"error":"Bad Request"}' : SUCCESS_HTML);
|
|
return;
|
|
}
|
|
|
|
if (pathname !== this.callbackPath) {
|
|
send(404, needJson ? '{"error":"Not Found"}' : SUCCESS_HTML);
|
|
return;
|
|
}
|
|
|
|
if (this.handled) {
|
|
send(
|
|
409,
|
|
needJson ? '{"error":"Callback already handled"}' : SUCCESS_HTML,
|
|
);
|
|
return;
|
|
}
|
|
|
|
const params = parseOAuthCallbackParams(search);
|
|
|
|
if (params.successful) {
|
|
this.handled = true;
|
|
const cb = this.onCallback;
|
|
if (cb) {
|
|
cb({ code: params.code, state })
|
|
.then(() => {
|
|
send(200, SUCCESS_HTML);
|
|
void this.stop();
|
|
})
|
|
.catch((err) => {
|
|
const msg = err instanceof Error ? err.message : String(err);
|
|
this.onError?.({ error: "callback_error", error_description: msg });
|
|
send(500, errorHtml(msg));
|
|
void this.stop();
|
|
});
|
|
} else {
|
|
send(200, SUCCESS_HTML);
|
|
void this.stop();
|
|
}
|
|
return;
|
|
}
|
|
|
|
this.handled = true;
|
|
const msg = generateOAuthErrorDescription(params);
|
|
this.onError?.({
|
|
error: params.error,
|
|
error_description: params.error_description ?? undefined,
|
|
});
|
|
send(400, errorHtml(msg));
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Create an OAuth callback server instance.
|
|
* Use start() then stop() when the OAuth flow is done.
|
|
*/
|
|
export function createOAuthCallbackServer(): OAuthCallbackServer {
|
|
return new OAuthCallbackServer();
|
|
}
|
|
|
|
function buildRedirectUrl(host: string, port: number, path: string): string {
|
|
const needsBrackets = host.includes(":") && !host.startsWith("[");
|
|
const formattedHost = needsBrackets ? `[${host}]` : host;
|
|
return `http://${formattedHost}:${port}${path}`;
|
|
}
|