import { isError } from "es-toolkit"; import { isObject } from "es-toolkit/compat"; import type { CheckResult, RawTargetConfig } from "../../types"; import type { CheckerContext, CheckerDefinition, CheckerValidationInput, ResolveContext } from "../types"; import type { HttpExpectConfig, HttpTargetConfig, ResolvedHttpTarget } from "./types"; import { checkDuration } from "../../expect/duration"; import { errorFailure, mismatchFailure } from "../../expect/failure"; import { parseSize } from "../../utils"; import { checkBodyExpect } from "./body"; import { checkHeaders, checkStatus } from "./expect"; import { httpCheckerSchemas } from "./schema"; import { validateHttpConfig } from "./validate"; const CHARSET_RE = /charset="?([^";\s]+)"?/i; const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]); const SENSITIVE_HEADERS = new Set(["authorization", "cookie"]); export class HttpChecker implements CheckerDefinition { readonly configKey = "http"; readonly schemas = httpCheckerSchemas; readonly type = "http"; async execute(t: ResolvedHttpTarget, ctx: CheckerContext): Promise { const timestamp = new Date().toISOString(); const expect = t.expect; const start = performance.now(); try { const response = await fetchWithRedirects(t.http.url, t.http.maxRedirects, { body: t.http.method !== "GET" && t.http.method !== "HEAD" ? t.http.body : undefined, headers: t.http.headers, method: t.http.method, redirect: "manual", signal: ctx.signal, ...(t.http.ignoreSSL ? { tls: { rejectUnauthorized: false } } : {}), }); const statusCode = response.status; const responseHeaders = Object.fromEntries(response.headers); const statusResult = checkStatus(statusCode, expect?.status ?? [200]); if (!statusResult.matched) { return makeResult(t, timestamp, performance.now() - start, statusResult.failure, statusCode); } const headersResult = checkHeaders(responseHeaders, expect?.headers); if (!headersResult.matched) { return makeResult(t, timestamp, performance.now() - start, headersResult.failure, statusCode); } const hasBodyRules = !!(expect?.body && expect.body.length > 0); const earlyTimeout = hasBodyRules ? checkEarlyTimeout(start, expect?.maxDurationMs) : null; if (earlyTimeout) { return makeResult(t, timestamp, earlyTimeout.elapsed, earlyTimeout.failure, statusCode); } if (hasBodyRules) { const bodyReadResult = await readBodyStream(response, t.http.maxBodyBytes); if (!bodyReadResult.ok) { return makeResult(t, timestamp, performance.now() - start, bodyReadResult.failure, statusCode); } const decodeResult = decodeBody(bodyReadResult.data, response.headers); if (!decodeResult.ok) { return makeResult(t, timestamp, performance.now() - start, decodeResult.failure, statusCode); } const bodyResult = checkBodyExpect(decodeResult.text, expect.body); if (!bodyResult.matched) { return makeResult(t, timestamp, performance.now() - start, bodyResult.failure, statusCode); } } const durationMs = Math.round(performance.now() - start); const durationResult = checkDuration(durationMs, expect?.maxDurationMs); if (!durationResult.matched) { return makeResult(t, timestamp, durationMs, durationResult.failure, statusCode); } return makeResult(t, timestamp, durationMs, null, statusCode); } catch (error) { const durationMs = Math.round(performance.now() - start); const isTimeout = ctx.signal.aborted || (error instanceof DOMException && error.name === "AbortError"); return { durationMs, failure: errorFailure( "request", "request", isTimeout ? `请求超时 (${t.timeoutMs}ms)` : isError(error) ? error.message : String(error), ), matched: false, statusDetail: null, targetId: t.id, timestamp, }; } } resolve(target: RawTargetConfig, context: ResolveContext): ResolvedHttpTarget { const t = target as RawTargetConfig & { http: HttpTargetConfig; type: "http" }; const httpDefaults = context.defaults["http"] as | undefined | { headers?: Record; maxBodyBytes?: string }; const method = t.http.method ?? "GET"; const maxBodyBytes = parseSize(t.http.maxBodyBytes ?? httpDefaults?.maxBodyBytes ?? "100MB"); return { description: null, expect: target.expect as HttpExpectConfig | undefined, group: target.group ?? "default", http: { body: t.http.body, headers: { ...(httpDefaults?.headers ?? {}), ...(t.http.headers ?? {}) }, ignoreSSL: t.http.ignoreSSL ?? false, maxBodyBytes, maxRedirects: t.http.maxRedirects ?? 0, method, url: t.http.url, }, id: t.id, intervalMs: context.defaultIntervalMs, name: t.name ?? null, timeoutMs: context.defaultTimeoutMs, type: "http", } satisfies ResolvedHttpTarget; } serialize(t: ResolvedHttpTarget): { config: string; target: string } { return { config: JSON.stringify({ body: t.http.body, headers: t.http.headers, ignoreSSL: t.http.ignoreSSL, maxBodyBytes: t.http.maxBodyBytes, maxRedirects: t.http.maxRedirects, method: t.http.method, url: t.http.url, }), target: t.http.url, }; } validate(input: CheckerValidationInput) { return validateHttpConfig(input); } } function buildRedirectInit(init: RequestInit, statusCode: number, fromUrl: string, toUrl: string): RequestInit { let newInit = { ...init }; const method = init.method?.toUpperCase(); if (statusCode === 303 || ((statusCode === 301 || statusCode === 302) && method === "POST")) { const headers = isObject(init.headers) ? { ...(init.headers as Record) } : undefined; if (headers) { for (const key of Object.keys(headers)) { const lower = key.toLowerCase(); if (lower === "content-type" || lower === "content-length") { delete headers[key]; } } } newInit = { ...newInit, body: undefined, headers, method: "GET" }; } try { const fromOrigin = new URL(fromUrl).origin; const toOrigin = new URL(toUrl).origin; if (fromOrigin !== toOrigin && isObject(newInit.headers)) { const headers = { ...(newInit.headers as Record) }; for (const key of Object.keys(headers)) { if (SENSITIVE_HEADERS.has(key.toLowerCase())) { delete headers[key]; } } newInit.headers = headers; } } catch { /* URL parsing failed, keep headers */ } return newInit; } function checkEarlyTimeout( start: number, maxDurationMs: number | undefined, ): null | { elapsed: number; failure: CheckResult["failure"] } { if (maxDurationMs === undefined) return null; const elapsed = performance.now() - start; if (elapsed <= maxDurationMs) return null; const durationMs = Math.round(elapsed); return { elapsed, failure: mismatchFailure( "duration", "duration", `<=${maxDurationMs}ms`, durationMs, `duration ${durationMs}ms > ${maxDurationMs}ms`, ), }; } function decodeBody( data: Uint8Array, headers: Headers, ): { failure: CheckResult["failure"]; ok: false } | { ok: true; text: string } { const contentType = headers.get("content-type") ?? ""; const charsetMatch = CHARSET_RE.exec(contentType); const encoding = charsetMatch?.[1]?.toLowerCase() ?? "utf-8"; try { const text = new TextDecoder(encoding).decode(data); return { ok: true, text }; } catch { return { failure: errorFailure("body", "body", `不支持的字符编码: ${encoding}`), ok: false, }; } } async function fetchWithRedirects(url: string, maxRedirects: number, init: RequestInit): Promise { let currentUrl = url; let currentInit = init; for (let followed = 0; ; followed++) { const response = await fetch(currentUrl, currentInit); if (!REDIRECT_STATUSES.has(response.status)) return response; const location = response.headers.get("location"); if (!location || followed >= maxRedirects) return response; try { await response.arrayBuffer(); } catch { /* ignore body drain error */ } const nextUrl = new URL(location, currentUrl).toString(); currentInit = buildRedirectInit(currentInit, response.status, currentUrl, nextUrl); currentUrl = nextUrl; } } function makeResult( t: ResolvedHttpTarget, timestamp: string, elapsed: number, failure: CheckResult["failure"], statusCode: number, ): CheckResult { return { durationMs: Math.round(elapsed), failure, matched: failure === null, statusDetail: `HTTP ${statusCode}`, targetId: t.id, timestamp, }; } async function readBodyStream( response: Response, maxBodyBytes: number, ): Promise<{ data: Uint8Array; ok: true } | { failure: CheckResult["failure"]; ok: false }> { const reader = response.body?.getReader(); if (!reader) { return { data: new Uint8Array(0), ok: true }; } const chunks: Uint8Array[] = []; let totalBytes = 0; try { for (;;) { const { done, value } = await reader.read(); if (done) break; totalBytes += value.byteLength; if (totalBytes > maxBodyBytes) { try { await reader.cancel(); } catch { /* ignore cancel error */ } return { failure: errorFailure("body", "body", `响应体大小超过限制 ${maxBodyBytes}`), ok: false, }; } chunks.push(value); } } finally { reader.releaseLock(); } const result = new Uint8Array(totalBytes); let offset = 0; for (const chunk of chunks) { result.set(chunk, offset); offset += chunk.byteLength; } return { data: result, ok: true }; }