Skip to content

armgit / rea

Public Imported from GitHub
0

Reverse engineer anything with agents, from app behavior down to native binaries.

feat(protocol): add custom TCP/UDP/IPC/XPC and auth-flow capture

morluto6fa6f9b6d959
diff --git a/src/domain/customProtocolCapture.ts b/src/domain/customProtocolCapture.ts
new file mode 100644
index 000000000..84ccfa62b
--- /dev/null
+++ b/src/domain/customProtocolCapture.ts
@@ -0,0 +1,173 @@
+import { z } from "zod";
+
+import { jsonValueSchema } from "./jsonValue.js";
+
+/** Supported transport types for custom protocol capture. */
+export const transportTypeSchema = z.enum([
+ "tcp",
+ "udp",
+ "ipc",
+ "unix-socket",
+ "named-pipe",
+ "xpc",
+]);
+export type TransportType = z.infer<typeof transportTypeSchema>;
+
+/** Direction of a protocol frame. */
+export const frameDirectionSchema = z.enum(["sent", "received", "intercepted"]);
+export type FrameDirection = z.infer<typeof frameDirectionSchema>;
+
+/** A captured protocol frame. */
+export const protocolFrameSchema = z.strictObject({
+ /** Monotonic sequence number. */
+ sequence: z.number().int().nonnegative(),
+ /** Timestamp in milliseconds. */
+ at_ms: z.number().int().nonnegative(),
+ /** Transport type. */
+ transport: transportTypeSchema,
+ /** Direction of the frame. */
+ direction: frameDirectionSchema,
+ /** Source process identity. */
+ source_pid: z.number().int().nullable(),
+ /** Destination process identity. */
+ dest_pid: z.number().int().nullable(),
+ /** Endpoint address (IP:port, socket path, pipe name). */
+ source_endpoint: z.string().nullable(),
+ /** Destination endpoint. */
+ dest_endpoint: z.string().nullable(),
+ /** Raw frame data as base64. */
+ raw_data: z.string().nullable(),
+ /** Decoded/parsed frame content if known. */
+ decoded_content: jsonValueSchema.nullable(),
+ /** Frame size in bytes. */
+ size: z.number().int().nonnegative(),
+ /** Whether the frame was truncated. */
+ truncated: z.boolean().default(false),
+});
+export type ProtocolFrame = z.infer<typeof protocolFrameSchema>;
+
+/** Authentication flow stage. */
+export const authStageSchema = z.enum([
+ "init",
+ "challenge",
+ "response",
+ "token_exchange",
+ "renewal",
+ "revocation",
+ "failure",
+ "success",
+]);
+export type AuthStage = z.infer<typeof authStageSchema>;
+
+/** Token lifecycle event. */
+export const tokenLifecycleEventSchema = z.enum([
+ "issued",
+ "refreshed",
+ "expired",
+ "revoked",
+ "renewed",
+]);
+export type TokenLifecycleEvent = z.infer<typeof tokenLifecycleEventSchema>;
+
+/** A captured authentication flow event. */
+export const authFlowEventSchema = z.strictObject({
+ /** Monotonic sequence number. */
+ sequence: z.number().int().nonnegative(),
+ /** Timestamp in milliseconds. */
+ at_ms: z.number().int().nonnegative(),
+ /** Authentication stage. */
+ stage: authStageSchema,
+ /** Protocol used. */
+ protocol: z.string().min(1),
+ /** Token type if applicable. */
+ token_type: z.string().nullable(),
+ /** Token lifecycle event. */
+ token_lifecycle: tokenLifecycleEventSchema.nullable(),
+ /** Correlation ID linking challenge-response pairs. */
+ correlation_id: z.string().nullable(),
+ /** Whether credentials were detected and redacted. */
+ credentials_redacted: z.boolean().default(false),
+ /** Whether the authentication succeeded. */
+ succeeded: z.boolean().default(false),
+ /** Error message if authentication failed. */
+ error: z.string().nullable(),
+});
+export type AuthFlowEvent = z.infer<typeof authFlowEventSchema>;
+
+/** A captured protocol session. */
+export const customProtocolCaptureSchema = z.strictObject({
+ /** Transport type for this session. */
+ transport: transportTypeSchema,
+ /** Captured frames in order. */
+ frames: z.array(protocolFrameSchema).min(0).max(100_000),
+ /** Authentication flow events. */
+ auth_events: z.array(authFlowEventSchema).default([]),
+ /** Whether any frame was truncated. */
+ has_truncated: z.boolean().default(false),
+ /** Whether credentials were detected. */
+ credentials_detected: z.boolean().default(false),
+});
+export type CustomProtocolCapture = z.infer<typeof customProtocolCaptureSchema>;
+
+/** Correlate a frame with process identity. */
+export function correlateProcessIdentity(
+ frame: ProtocolFrame,
+ pid: number,
+): boolean {
+ return frame.source_pid === pid || frame.dest_pid === pid;
+}
+
+/** Check if a frame contains credential-like content. */
+export function looksLikeCredentialFrame(frame: ProtocolFrame): boolean {
+ const patterns = [
+ "password",
+ "token",
+ "secret",
+ "api_key",
+ "apikey",
+ "authorization",
+ "credential",
+ ];
+ const content = JSON.stringify(frame.decoded_content ?? "").toLowerCase();
+ return patterns.some((p) => content.includes(p));
+}
+
+/** Filter frames by transport type. */
+export function framesByTransport(
+ frames: readonly ProtocolFrame[],
+ transport: TransportType,
+): ProtocolFrame[] {
+ return frames.filter((f) => f.transport === transport);
+}
+
+/** Get all authentication flow events for a specific protocol. */
+export function authEventsByProtocol(
+ events: readonly AuthFlowEvent[],
+ protocol: string,
+): AuthFlowEvent[] {
+ return events.filter((e) => e.protocol === protocol);
+}
+
+/** Get successful authentication events. */
+export function successfulAuthEvents(
+ events: readonly AuthFlowEvent[],
+): AuthFlowEvent[] {
+ return events.filter((e) => e.succeeded);
+}
+
+/** Get failed authentication events. */
+export function failedAuthEvents(
+ events: readonly AuthFlowEvent[],
+): AuthFlowEvent[] {
+ return events.filter((e) => !e.succeeded);
+}
+
+/** Compute the duration of an authentication flow in milliseconds. */
+export function authFlowDuration(
+ events: readonly AuthFlowEvent[],
+): number | null {
+ if (events.length === 0) return null;
+ const first = events[0]!;
+ const last = events[events.length - 1]!;
+ return last.at_ms - first.at_ms;
+}
diff --git a/tests/customProtocolCapture.test.ts b/tests/customProtocolCapture.test.ts
new file mode 100644
index 000000000..ad82b35a7
--- /dev/null
+++ b/tests/customProtocolCapture.test.ts
@@ -0,0 +1,157 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ authEventsByProtocol,
+ authFlowDuration,
+ customProtocolCaptureSchema,
+ correlateProcessIdentity,
+ failedAuthEvents,
+ framesByTransport,
+ looksLikeCredentialFrame,
+ successfulAuthEvents,
+ type AuthFlowEvent,
+ type FrameDirection,
+ type AuthStage,
+ type TokenLifecycleEvent,
+ type CustomProtocolCapture,
+ type ProtocolFrame,
+} from "../src/domain/customProtocolCapture.js";
+
+const sampleFrames: ProtocolFrame[] = [
+ {
+ sequence: 0,
+ at_ms: 100,
+ transport: "tcp",
+ direction: "sent",
+ source_pid: 100,
+ dest_pid: 200,
+ source_endpoint: "127.0.0.1:8080",
+ dest_endpoint: "127.0.0.1:9090",
+ raw_data: "hello",
+ decoded_content: "hello",
+ size: 5,
+ truncated: false,
+ },
+ {
+ sequence: 1,
+ at_ms: 200,
+ transport: "udp",
+ direction: "received",
+ source_pid: 200,
+ dest_pid: 100,
+ source_endpoint: "127.0.0.1:9090",
+ dest_endpoint: "127.0.0.1:8080",
+ raw_data: "world",
+ decoded_content: "world",
+ size: 5,
+ truncated: false,
+ },
+];
+
+const sampleAuthEvents: AuthFlowEvent[] = [
+ {
+ sequence: 0,
+ at_ms: 100,
+ stage: "init",
+ protocol: "OAuth2",
+ token_type: "Bearer",
+ token_lifecycle: "issued",
+ correlation_id: "abc-123",
+ credentials_redacted: true,
+ succeeded: false,
+ error: null,
+ },
+ {
+ sequence: 1,
+ at_ms: 500,
+ stage: "success",
+ protocol: "OAuth2",
+ token_type: "Bearer",
+ token_lifecycle: "issued",
+ correlation_id: "abc-123",
+ credentials_redacted: true,
+ succeeded: true,
+ error: null,
+ },
+];
+
+describe("custom protocol capture", () => {
+ it("validates a well-formed capture", () => {
+ const capture = {
+ transport: "tcp" as const,
+ frames: sampleFrames,
+ auth_events: sampleAuthEvents,
+ has_truncated: false,
+ credentials_detected: false,
+ };
+ const result = customProtocolCaptureSchema.safeParse(capture);
+ expect(result.success).toBe(true);
+ });
+
+ it("correlates process identity", () => {
+ expect(correlateProcessIdentity(sampleFrames[0]!, 100)).toBe(true);
+ expect(correlateProcessIdentity(sampleFrames[0]!, 200)).toBe(true);
+ expect(correlateProcessIdentity(sampleFrames[0]!, 999)).toBe(false);
+ });
+
+ it("filters frames by transport", () => {
+ const tcpFrames = framesByTransport(sampleFrames, "tcp");
+ expect(tcpFrames).toHaveLength(1);
+ const udpFrames = framesByTransport(sampleFrames, "udp");
+ expect(udpFrames).toHaveLength(1);
+ });
+
+ it("detects credential-like frames", () => {
+ const credFrame: ProtocolFrame = {
+ ...sampleFrames[0]!,
+ decoded_content: { password: "secret" },
+ };
+ expect(looksLikeCredentialFrame(credFrame)).toBe(true);
+ expect(looksLikeCredentialFrame(sampleFrames[0]!)).toBe(false);
+ });
+
+ it("filters auth events by protocol", () => {
+ const oauthEvents = authEventsByProtocol(sampleAuthEvents, "OAuth2");
+ expect(oauthEvents).toHaveLength(2);
+ const otherEvents = authEventsByProtocol(sampleAuthEvents, "SAML");
+ expect(otherEvents).toHaveLength(0);
+ });
+
+ it("gets successful auth events", () => {
+ const success = successfulAuthEvents(sampleAuthEvents);
+ expect(success).toHaveLength(1);
+ expect(success[0]!.succeeded).toBe(true);
+ });
+
+ it("gets failed auth events", () => {
+ const failed = failedAuthEvents(sampleAuthEvents);
+ expect(failed).toHaveLength(1);
+ expect(failed[0]!.succeeded).toBe(false);
+ });
+
+ it("computes auth flow duration", () => {
+ const duration = authFlowDuration(sampleAuthEvents);
+ expect(duration).toBe(400);
+ });
+
+ it("returns null for empty auth events", () => {
+ expect(authFlowDuration([])).toBeNull();
+ });
+
+ it("uses all exported types", () => {
+ const dir: FrameDirection = "sent";
+ expect(dir).toBe("sent");
+ const stage: AuthStage = "init";
+ expect(stage).toBe("init");
+ const event: TokenLifecycleEvent = "issued";
+ expect(event).toBe("issued");
+ const capture: CustomProtocolCapture = {
+ transport: "tcp",
+ frames: sampleFrames,
+ auth_events: sampleAuthEvents,
+ has_truncated: false,
+ credentials_detected: false,
+ };
+ expect(capture.transport).toBe("tcp");
+ });
+});