mirror of
https://github.com/mountain-loop/yaak.git
synced 2026-12-05 06:16:23 +01:00
Share Yaak's request and response panes (#815)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
4ad0533901
commit
08a98d5f82
85 files changed
+5567
-2872
No files matched your search
@@ -0,0 +1,222 @@
|
||||
import type { Flow } from "@yaakapp-internal/proxy-lib";
|
||||
import {
|
||||
BODY_TYPE_BINARY,
|
||||
BODY_TYPE_FORM_MULTIPART,
|
||||
BODY_TYPE_FORM_URLENCODED,
|
||||
BODY_TYPE_JSON,
|
||||
BODY_TYPE_OTHER,
|
||||
} from "@yaakapp-internal/ui/httpTypes";
|
||||
import { describe, expect, test } from "vite-plus/test";
|
||||
import {
|
||||
authFromHeaders,
|
||||
type FlowBodyData,
|
||||
flowBodyFromRpc,
|
||||
flowRequestToView,
|
||||
flowResponseToView,
|
||||
queryToPairs,
|
||||
utcTimestamp,
|
||||
} from "./flowViews";
|
||||
|
||||
const flow: Flow = {
|
||||
id: "fl_1",
|
||||
createdAt: "2026-11-04T22:10:00Z",
|
||||
updatedAt: "2026-11-04T22:10:01Z",
|
||||
startedAt: "2026-11-04T22:10:00Z",
|
||||
method: "POST",
|
||||
url: "https://api.example.com/v1/items?limit=1&q=a+b#top",
|
||||
clientHttpVersion: "HTTP/1.1",
|
||||
upstreamHttpVersion: "HTTP/2",
|
||||
remoteAddr: "1.2.3.4:443",
|
||||
status: 201,
|
||||
contentType: "application/json",
|
||||
requestHeaders: [
|
||||
{ name: "Content-Type", value: "application/json" },
|
||||
{ name: "Cookie", value: "a=1" },
|
||||
],
|
||||
responseHeaders: [
|
||||
{ name: "Content-Type", value: "application/json" },
|
||||
{ name: "Set-Cookie", value: "b=2; Path=/" },
|
||||
],
|
||||
requestSize: 7,
|
||||
responseSize: 12,
|
||||
requestTruncated: false,
|
||||
responseTruncated: false,
|
||||
elapsedHeadersMs: 40,
|
||||
elapsedMs: 55,
|
||||
error: null,
|
||||
cancelled: false,
|
||||
savedRequestId: null,
|
||||
clientPid: null,
|
||||
clientName: null,
|
||||
clientBundleId: null,
|
||||
clientPath: null,
|
||||
};
|
||||
|
||||
function bytes(text: string): FlowBodyData {
|
||||
return { bytes: new TextEncoder().encode(text), truncated: false, storedSize: text.length };
|
||||
}
|
||||
|
||||
function withContentType(contentType: string): Flow {
|
||||
return { ...flow, requestHeaders: [{ name: "Content-Type", value: contentType }] };
|
||||
}
|
||||
|
||||
describe("flowRequestToView", () => {
|
||||
test("maps the request line, headers and query", () => {
|
||||
const view = flowRequestToView(flow, bytes('{"a":1}'));
|
||||
expect(view.method).toBe("POST");
|
||||
expect(view.url).toBe(flow.url);
|
||||
expect(view.headers.map((h) => h.name)).toEqual(["Content-Type", "Cookie"]);
|
||||
expect(view.urlParameters.map(({ name, value }) => ({ name, value }))).toEqual([
|
||||
{ name: "limit", value: "1" },
|
||||
{ name: "q", value: "a b" },
|
||||
]);
|
||||
expect(view.contentType).toBe("application/json");
|
||||
});
|
||||
|
||||
test("reads a JSON body as JSON, sent as written", () => {
|
||||
const view = flowRequestToView(flow, bytes('{"a":1}'));
|
||||
expect(view.bodyType).toBe(BODY_TYPE_JSON);
|
||||
expect(view.body).toEqual({ text: '{"a":1}', sendJsonComments: true });
|
||||
});
|
||||
|
||||
test("reads a url-encoded body as form fields", () => {
|
||||
const view = flowRequestToView(
|
||||
withContentType("application/x-www-form-urlencoded; charset=utf-8"),
|
||||
bytes("a=1&b=two+words&c=%26"),
|
||||
);
|
||||
expect(view.bodyType).toBe(BODY_TYPE_FORM_URLENCODED);
|
||||
expect(view.body.form?.map(({ name, value }) => [name, value])).toEqual([
|
||||
["a", "1"],
|
||||
["b", "two words"],
|
||||
["c", "&"],
|
||||
]);
|
||||
});
|
||||
|
||||
test("leaves multipart and binary bodies to the viewers", () => {
|
||||
expect(
|
||||
flowRequestToView(withContentType("multipart/form-data; boundary=x"), bytes("--x--"))
|
||||
.bodyType,
|
||||
).toBe(BODY_TYPE_FORM_MULTIPART);
|
||||
const binary: FlowBodyData = {
|
||||
bytes: new Uint8Array([0xff, 0xfe, 0x00]),
|
||||
truncated: false,
|
||||
storedSize: 3,
|
||||
};
|
||||
expect(flowRequestToView(withContentType("application/octet-stream"), binary).bodyType).toBe(
|
||||
BODY_TYPE_BINARY,
|
||||
);
|
||||
});
|
||||
|
||||
test("reads other text as text, and no body as none", () => {
|
||||
expect(flowRequestToView(withContentType("text/plain"), bytes("hi")).bodyType).toBe(
|
||||
BODY_TYPE_OTHER,
|
||||
);
|
||||
expect(flowRequestToView(flow, bytes("")).bodyType).toBeNull();
|
||||
expect(flowRequestToView(flow, null).bodyType).toBeNull();
|
||||
});
|
||||
|
||||
test("shows authentication from the Authorization header", () => {
|
||||
expect(authFromHeaders([{ name: "authorization", value: "Bearer abc" }])).toEqual({
|
||||
label: "Bearer",
|
||||
values: [{ name: "Authorization", value: "Bearer abc" }],
|
||||
});
|
||||
expect(authFromHeaders([{ name: "Authorization", value: "Custom x" }])?.label).toBe("Auth");
|
||||
expect(authFromHeaders([])).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("flowResponseToView", () => {
|
||||
test("maps status, timing, sizes and cookies", () => {
|
||||
const view = flowResponseToView(flow);
|
||||
expect(view).toMatchObject({
|
||||
id: "fl_1",
|
||||
ownerId: "fl_1",
|
||||
state: "closed",
|
||||
status: 201,
|
||||
statusReason: "Created",
|
||||
contentType: "application/json",
|
||||
contentLength: 12,
|
||||
requestContentLength: 7,
|
||||
startedAt: "2026-11-04T22:10:00Z",
|
||||
elapsedMs: 55,
|
||||
elapsedHeadersMs: 40,
|
||||
version: "HTTP/2",
|
||||
remoteAddr: "1.2.3.4:443",
|
||||
cookieHeaders: { sent: ["a=1"], received: ["b=2; Path=/"] },
|
||||
});
|
||||
});
|
||||
|
||||
test("shows a gzip response's decoded size, with its wire size as compressed", () => {
|
||||
const gzipped: Flow = {
|
||||
...flow,
|
||||
responseHeaders: [...flow.responseHeaders, { name: "Content-Encoding", value: "gzip" }],
|
||||
responseSize: 40,
|
||||
};
|
||||
const decoded: FlowBodyData = {
|
||||
bytes: new Uint8Array(120),
|
||||
truncated: false,
|
||||
storedSize: 40,
|
||||
};
|
||||
expect(flowResponseToView(gzipped, decoded)).toMatchObject({
|
||||
contentLength: 120,
|
||||
contentLengthCompressed: 40,
|
||||
});
|
||||
// Before the body loads, the wire size stands in, still marked compressed
|
||||
expect(flowResponseToView(gzipped)).toMatchObject({
|
||||
contentLength: 40,
|
||||
contentLengthCompressed: 40,
|
||||
});
|
||||
});
|
||||
|
||||
test("keeps the wire size for an unencoded body cut at the capture limit", () => {
|
||||
const cut: FlowBodyData = { bytes: new Uint8Array(5), truncated: true, storedSize: 5 };
|
||||
expect(flowResponseToView(flow, cut)).toMatchObject({
|
||||
contentLength: 12,
|
||||
contentLengthCompressed: null,
|
||||
});
|
||||
expect(flowResponseToView(flow, bytes("hello world!"))).toMatchObject({
|
||||
contentLength: 12,
|
||||
contentLengthCompressed: null,
|
||||
});
|
||||
});
|
||||
|
||||
test("reads the engine's zone-less timestamps as UTC", () => {
|
||||
expect(flowResponseToView({ ...flow, startedAt: "2026-11-04T22:10:00.123" })?.startedAt).toBe(
|
||||
"2026-11-04T22:10:00.123Z",
|
||||
);
|
||||
expect(utcTimestamp("2026-11-04T22:10:00+02:00")).toBe("2026-11-04T22:10:00+02:00");
|
||||
});
|
||||
|
||||
test("is still connected while the body streams", () => {
|
||||
expect(flowResponseToView({ ...flow, elapsedMs: null })?.state).toBe("connected");
|
||||
});
|
||||
|
||||
test("has no response while waiting on one", () => {
|
||||
expect(flowResponseToView({ ...flow, status: null, elapsedMs: null })).toBeNull();
|
||||
});
|
||||
|
||||
test("carries a failure as the response's error", () => {
|
||||
const view = flowResponseToView({ ...flow, status: null, elapsedMs: null, error: "refused" });
|
||||
expect(view).toMatchObject({ state: "closed", status: 0, error: "refused" });
|
||||
});
|
||||
|
||||
test("says when the client gave up before a response", () => {
|
||||
const view = flowResponseToView({ ...flow, status: null, elapsedMs: null, cancelled: true });
|
||||
expect(view?.error).toBe("Cancelled by the client");
|
||||
});
|
||||
});
|
||||
|
||||
describe("flowBodyFromRpc", () => {
|
||||
test("decodes the RPC's base64", () => {
|
||||
const body = flowBodyFromRpc({ data: btoa("hello"), truncated: true, storedSize: 5 });
|
||||
expect(new TextDecoder().decode(body.bytes)).toBe("hello");
|
||||
expect(body.truncated).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("queryToPairs", () => {
|
||||
test("ignores the fragment and keeps repeats", () => {
|
||||
expect(queryToPairs("https://x.test/?a=1&a=2#b=3").map((p) => p.value)).toEqual(["1", "2"]);
|
||||
expect(queryToPairs("https://x.test/")).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,235 @@
|
||||
import type { Flow, GetFlowBodyResponse, ProxyHeader } from "@yaakapp-internal/proxy-lib";
|
||||
import {
|
||||
BODY_TYPE_BINARY,
|
||||
BODY_TYPE_FORM_MULTIPART,
|
||||
BODY_TYPE_FORM_URLENCODED,
|
||||
BODY_TYPE_JSON,
|
||||
BODY_TYPE_OTHER,
|
||||
BODY_TYPE_XML,
|
||||
type HttpAuthView,
|
||||
type HttpBodyLoader,
|
||||
type HttpBodyResult,
|
||||
type HttpPairView,
|
||||
type HttpRequestBodyView,
|
||||
type HttpRequestView,
|
||||
type HttpResponseView,
|
||||
} from "@yaakapp-internal/ui/httpTypes";
|
||||
import { useEffect, useState } from "react";
|
||||
import { base64ToBytes, bytesToText, findHeader, mimeEssence } from "./body";
|
||||
import { statusReason } from "./statusReason";
|
||||
|
||||
/** A captured body as the engine's body RPC returns it, decoded */
|
||||
export interface FlowBodyData {
|
||||
bytes: Uint8Array<ArrayBuffer>;
|
||||
truncated: boolean;
|
||||
storedSize: number;
|
||||
}
|
||||
|
||||
export function flowBodyFromRpc(res: GetFlowBodyResponse): FlowBodyData {
|
||||
return { bytes: base64ToBytes(res.data), truncated: res.truncated, storedSize: res.storedSize };
|
||||
}
|
||||
|
||||
/** A captured request as the shared request pane shows it, read-only */
|
||||
export function flowRequestToView(flow: Flow, body: FlowBodyData | null): HttpRequestView {
|
||||
const contentType = findHeader(flow.requestHeaders, "content-type");
|
||||
const text = body == null ? null : bytesToText(body.bytes, body.truncated);
|
||||
const { bodyType, body: bodyView } = requestBodyView(contentType, body, text);
|
||||
|
||||
return {
|
||||
id: flow.id,
|
||||
method: flow.method,
|
||||
url: flow.url,
|
||||
headers: headersToPairs(flow.requestHeaders),
|
||||
urlParameters: queryToPairs(flow.url),
|
||||
bodyType,
|
||||
body: bodyView,
|
||||
contentType,
|
||||
auth: authFromHeaders(flow.requestHeaders),
|
||||
};
|
||||
}
|
||||
|
||||
/** The body type a captured body reads as, in the shape that body type's editor shows */
|
||||
function requestBodyView(
|
||||
contentType: string | null,
|
||||
body: FlowBodyData | null,
|
||||
text: string | null,
|
||||
): { bodyType: string | null; body: HttpRequestBodyView } {
|
||||
if (body == null || body.bytes.length === 0) return { bodyType: null, body: {} };
|
||||
|
||||
const mime = mimeEssence(contentType) ?? "";
|
||||
if (mime.startsWith("multipart/")) return { bodyType: BODY_TYPE_FORM_MULTIPART, body: {} };
|
||||
if (text == null) return { bodyType: BODY_TYPE_BINARY, body: {} };
|
||||
if (mime === BODY_TYPE_FORM_URLENCODED) {
|
||||
return { bodyType: BODY_TYPE_FORM_URLENCODED, body: { form: formToPairs(text) } };
|
||||
}
|
||||
if (mime === "application/json" || mime.endsWith("+json")) {
|
||||
// Captured as sent, so nothing was cleaned up before it went out
|
||||
return { bodyType: BODY_TYPE_JSON, body: { text, sendJsonComments: true } };
|
||||
}
|
||||
if (mime === "text/xml" || mime === "application/xml" || mime.endsWith("+xml")) {
|
||||
return { bodyType: BODY_TYPE_XML, body: { text } };
|
||||
}
|
||||
return { bodyType: BODY_TYPE_OTHER, body: { text } };
|
||||
}
|
||||
|
||||
/**
|
||||
* A captured response as the shared response pane shows it, or null when the request never
|
||||
* got one and didn't fail either (it's still waiting). `body` is the response body from the
|
||||
* engine, decoded; its size is the one the pane shows, and the wire size counts as compressed
|
||||
* when the response had a Content-Encoding. Until it loads, the wire size stands in.
|
||||
*/
|
||||
export function flowResponseToView(
|
||||
flow: Flow,
|
||||
body: FlowBodyData | null = null,
|
||||
): HttpResponseView | null {
|
||||
const ended = flow.elapsedMs != null || flow.error != null || flow.cancelled;
|
||||
if (flow.status == null && !ended) return null;
|
||||
|
||||
const encoding = findHeader(flow.responseHeaders, "content-encoding")?.trim().toLowerCase();
|
||||
const encoded = encoding != null && encoding !== "" && encoding !== "identity";
|
||||
|
||||
return {
|
||||
id: flow.id,
|
||||
ownerId: flow.id,
|
||||
state: ended ? "closed" : "connected",
|
||||
status: flow.status ?? 0,
|
||||
statusReason: flow.status == null ? null : statusReason(flow.status),
|
||||
url: flow.url,
|
||||
headers: headersToPairs(flow.responseHeaders),
|
||||
requestHeaders: headersToPairs(flow.requestHeaders),
|
||||
contentType: findHeader(flow.responseHeaders, "content-type"),
|
||||
// A body cut at the capture limit is short; unencoded, the wire size is the exact one
|
||||
contentLength:
|
||||
body == null || (body.truncated && !encoded) ? flow.responseSize : body.bytes.length,
|
||||
contentLengthCompressed: encoded ? flow.responseSize : null,
|
||||
requestContentLength: flow.requestSize,
|
||||
startedAt: utcTimestamp(flow.startedAt),
|
||||
elapsedMs: flow.elapsedMs ?? 0,
|
||||
elapsedHeadersMs: flow.elapsedHeadersMs ?? 0,
|
||||
elapsedDnsMs: 0,
|
||||
error: flow.error ?? (flow.cancelled && flow.status == null ? "Cancelled by the client" : null),
|
||||
remoteAddr: flow.remoteAddr,
|
||||
version: flow.upstreamHttpVersion ?? flow.clientHttpVersion,
|
||||
cookieHeaders: {
|
||||
sent: headerValues(flow.requestHeaders, "cookie"),
|
||||
received: headerValues(flow.responseHeaders, "set-cookie"),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a captured body the ways the shared viewers ask for it. `useBody` is the hook that
|
||||
* loads it, the engine's body RPC in the app or a fixture in tests.
|
||||
*/
|
||||
export function flowBodyLoader({
|
||||
useBody,
|
||||
contentType,
|
||||
filterText,
|
||||
}: {
|
||||
useBody: () => HttpBodyResult<FlowBodyData | null>;
|
||||
contentType: string | null;
|
||||
filterText?: (expression: string) => Promise<string | null>;
|
||||
}): HttpBodyLoader {
|
||||
return {
|
||||
useText: () => {
|
||||
const body = useBody();
|
||||
return { ...body, data: mapData(body, (b) => bytesToText(b.bytes, b.truncated)) };
|
||||
},
|
||||
useBytes: () => {
|
||||
const body = useBody();
|
||||
return { ...body, data: mapData(body, (b) => b.bytes) };
|
||||
},
|
||||
useUrl: (enabled: boolean) => {
|
||||
const body = useBody();
|
||||
const bytes = enabled ? (body.data?.bytes ?? null) : null;
|
||||
const url = useObjectUrl(bytes, contentType);
|
||||
// The URL follows the bytes by a render
|
||||
const waiting = bytes != null && bytes.length > 0 && url == null;
|
||||
return { ...body, isLoading: !enabled || body.isLoading || waiting, data: url };
|
||||
},
|
||||
filterText,
|
||||
};
|
||||
}
|
||||
|
||||
function mapData<T>(
|
||||
body: HttpBodyResult<FlowBodyData | null>,
|
||||
fn: (b: FlowBodyData) => T,
|
||||
): T | null | undefined {
|
||||
if (body.data === undefined) return undefined;
|
||||
if (body.data == null || body.data.bytes.length === 0) return null;
|
||||
return fn(body.data);
|
||||
}
|
||||
|
||||
/** A URL for bytes held in memory, revoked when they change */
|
||||
function useObjectUrl(bytes: Uint8Array<ArrayBuffer> | null, contentType: string | null) {
|
||||
const [url, setUrl] = useState<string | null>(null);
|
||||
// Made and revoked by the same effect, so a remount can't revoke a URL still in use
|
||||
useEffect(() => {
|
||||
if (bytes == null || bytes.length === 0) {
|
||||
setUrl(null);
|
||||
return;
|
||||
}
|
||||
const next = URL.createObjectURL(new Blob([bytes], { type: mimeEssence(contentType) ?? "" }));
|
||||
setUrl(next);
|
||||
return () => URL.revokeObjectURL(next);
|
||||
}, [bytes, contentType]);
|
||||
return url;
|
||||
}
|
||||
|
||||
/** The engine stores UTC without a zone; JavaScript would read that as local time */
|
||||
export function utcTimestamp(timestamp: string): string {
|
||||
return /(Z|[+-]\d\d:?\d\d)$/i.test(timestamp) ? timestamp : `${timestamp}Z`;
|
||||
}
|
||||
|
||||
function headersToPairs(headers: ProxyHeader[]): HttpPairView[] {
|
||||
return headers.map((h, i) => ({ id: `${i}`, name: h.name, value: h.value, enabled: true }));
|
||||
}
|
||||
|
||||
function headerValues(headers: ProxyHeader[], name: string): string[] {
|
||||
return headers.filter((h) => h.name.toLowerCase() === name).map((h) => h.value);
|
||||
}
|
||||
|
||||
/** A URL's query string as parameters, in order, repeats kept */
|
||||
export function queryToPairs(url: string): HttpPairView[] {
|
||||
const query = url.split("#")[0]?.split("?").slice(1).join("?") ?? "";
|
||||
return formToPairs(query);
|
||||
}
|
||||
|
||||
/** `a=1&b=2` as pairs, decoded the way a form or query string is */
|
||||
export function formToPairs(text: string): HttpPairView[] {
|
||||
if (text === "") return [];
|
||||
return text.split("&").map((part, i) => {
|
||||
const [name = "", ...rest] = part.split("=");
|
||||
return {
|
||||
id: `${i}`,
|
||||
name: decodeFormPart(name),
|
||||
value: decodeFormPart(rest.join("=")),
|
||||
enabled: true,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function decodeFormPart(s: string): string {
|
||||
try {
|
||||
return decodeURIComponent(s.replaceAll("+", " "));
|
||||
} catch {
|
||||
return s;
|
||||
}
|
||||
}
|
||||
|
||||
/** What the request authenticated with, named by its scheme, for display */
|
||||
export function authFromHeaders(headers: ProxyHeader[]): HttpAuthView | null {
|
||||
const value = findHeader(headers, "authorization");
|
||||
if (value == null) return null;
|
||||
const scheme = value.split(" ")[0]?.toLowerCase() ?? "";
|
||||
return { label: AUTH_SCHEMES[scheme] ?? "Auth", values: [{ name: "Authorization", value }] };
|
||||
}
|
||||
|
||||
const AUTH_SCHEMES: Record<string, string> = {
|
||||
basic: "Basic",
|
||||
bearer: "Bearer",
|
||||
digest: "Digest",
|
||||
ntlm: "NTLM",
|
||||
negotiate: "Negotiate",
|
||||
"aws4-hmac-sha256": "AWS",
|
||||
};
|
||||
Reference in new issue
Block a user