marasi

package module
v0.0.0-...-87dd84e Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 28, 2026 License: MIT Imports: 66 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Marasi

Go reference

Marasi

Marasi is an application security testing proxy for HTTP/1.1, HTTP/2, WebSockets, and streamed traffic (gRPC, gRPC-Web, Connect, SSE, and NDJSON). You drive it through the marasi CLI, store traffic and assessment work in SQLite .marasi projects, and extend it with Lua. It also works as a Go library.

marasi.app

Features

  • HTTP/1.1 and HTTP/2 proxy: Full request/response capture, metadata, notes, highlights, sitemap, and AIP-160 search (traffic, notes).
  • WebSockets and streaming: Inspect, inject into, and close WebSockets (websocket), and read, inject into, or cancel streamed pairs over gRPC, gRPC-Web, Connect, SSE, and NDJSON (stream), with schema-less protobuf text decoding.
  • Checkpoint: Hold, edit, forward, or drop in-flight HTTP requests, responses, WebSocket messages, stream messages, and trailers (checkpoint).
  • Launchpad: Group captured pairs and launch edited raw HTTP/1.1, HTTP/2, or streamed requests (launchpad).
  • Armory: Wordlist-driven request templates with payload positions (armory, wordlist).
  • Lua extensions: Scriptable hooks for requests, responses, WebSockets, and stream messages (extension). New projects include compass (scope), checkpoint (interception rules), and workshop (Lua scratchpad).
  • Routing and Chrome: Scope checks (scope), host:port overrides (waypoint), HTTP/HTTPS/SOCKS5 upstream proxies (upstream), and managed Chrome profiles with optional CDP (chrome).
  • Assessment and reporting: Test cases, CVSS 3.1 findings, file artifacts, and template-based reports (test-case, finding, artifact, report).
  • SQLite projects: Self-contained .marasi files holding traffic and assessment data.

Install

Download a release binary or archive from GitHub Releases (Linux amd64, macOS arm64, Windows amd64), or build from source with Go 1.26+:

make install   # installs to ~/.local/bin/marasi (override with PREFIX=...)

Use make build to compile dist/marasi without installing, or go build -o marasi ./cmd/marasi. Builds do not require CGO.

Release and nightly builds update in place through a running service instance:

marasi update
marasi update install
marasi service restart

Switch between release and nightly with marasi update channel.

Quick start

Start a service instance, export its CA certificate, and proxy a request:

# Start an instance with a project and proxy listener
marasi service start --project-name assessment --address 127.0.0.1 --port 8080

# Export the CA certificate and send a request through the proxy
marasi certificate get > marasi-ca.pem
curl --proxy http://127.0.0.1:8080 --cacert marasi-ca.pem https://example.com

# List, search, and inspect captured traffic
marasi traffic list
marasi traffic list -q 'host = "example.com" AND status_code = 200'
marasi traffic get <pair-id>

# Stop the instance when done
marasi service stop

Run marasi --help or marasi <command> --help for all commands and flags. Pass --json to any command for JSON output.

To let a coding agent use Marasi, export the skill file matching your installed CLI:

marasi skill > ~/.agents/skills/marasi/SKILL.md

Service instances and remote control

marasi service start launches a background service instance that owns one open .marasi project. Use --instance NAME to run multiple instances against different projects, marasi project open to switch projects without restarting the proxy listener, and marasi listener stop to pause capture while keeping the instance available for inspection.

Locally, the CLI talks to an instance over a Unix-domain socket. To control an instance over the network or connect a GUI from another machine, expose the control listener with --control-address HOST:PORT (or marasi service control start), set a control password via MARASI_PASSWORD, and point the CLI at it with --remote http://HOST:PORT. Run marasi service control pair to print a QR code for pairing another device.

Use marasi events to watch live activity from an instance (pass --last-event-id to replay recent events after a disconnect). Any client routed through the proxy can also open http://marasi/cert to download the CA certificate in DER format, or http://marasi/view/<pair-id> for a browser view of a stored response at its original URL without contacting the origin.

Configuration

Global flags
Flag Environment variable Purpose
--instance NAME MARASI_INSTANCE Service instance name (default default)
--config-dir PATH MARASI_CONFIG_DIR Config directory
--remote URL MARASI_REMOTE Control listener URL of a remote instance
--password PASS MARASI_PASSWORD Control password for --remote or service start
--json - Print JSON output (NDJSON for streaming commands)
Config directory

By default, Marasi stores configuration and projects in:

Platform Default location
macOS ~/Library/Application Support/Marasi
Linux $XDG_CONFIG_HOME/Marasi (or ~/.config/Marasi)
Windows %AppData%\Marasi

Inside the config directory:

  • projects/<name>.marasi: named SQLite project files.
  • marasi_config.yaml: machine configuration (update settings, upstream proxies, Chrome paths and profiles, message/body size limits).
  • marasi_cert.pem and marasi_key.pem: shared CA certificate and private key.
  • wordlists/ and templates/: Armory wordlists and report templates.
  • instances/: per-instance control sockets (<name>.sock) and process logs (<name>.log).

Go library

Configure a proxy in Go with marasi.New and its option functions. Shared data types live in domain, and service provides the HTTP control API server and client.

go get github.com/tfkr-ae/marasi

See the Go package reference and cmd/marasi/service.go for a full setup example.

Development

Requires Go 1.26+.

Command Purpose
make build Build dist/marasi for this machine (no CGO)
make install Build and install marasi to ~/.local/bin (PREFIX overrides ~/.local)
make all Cross-compile all targets in Makefile
make check Run gofmt, go vet, staticcheck, and go test -short ./...
make test Run the full Go test suite (go test ./...)

Make sets GOWORK=off automatically; if a parent go.work excludes this checkout, pass GOWORK=off for direct go commands.

Conformance harness

Marasi's proxy behavior is tested against eight Docker-based conformance suites covering HTTP/1.1, HTTP/2, gRPC, Connect, SSE/NDJSON streaming, and WebSockets (Autobahn).

Run the required suites with make conformance and the WebSocket suite with make autobahn. See docs/conformance.md for suite details, narrowing flags, baselines, and CI setup.

Documentation

Documentation

Overview

Package marasi provides an HTTP/HTTPS proxy server with extension support, request/response interception, and SQLite database storage. It is designed to be decoupled from GUI implementations and provides methods to load handlers for building security testing tools, traffic analysis, and HTTP manipulation applications.

The core functionality includes:

  • HTTP/HTTPS proxy server with TLS certificate management
  • Lua-based extension system for request/response processing
  • Request/response interception and modification
  • SQLite database storage for traffic analysis
  • Scope-based filtering system
  • Chrome browser integration for testing
  • Launchpad system for organizing test requests

Index

Constants

View Source
const DefaultBodyThreshold = 64 << 20

DefaultBodyThreshold is the body threshold when body_threshold is unset: 64 MiB, the WebSocket message limit.

View Source
const DefaultUpstreamProxyTimeout = 30 * time.Second

DefaultUpstreamProxyTimeout bounds reaching an upstream proxy and opening a tunnel through it, so a proxy that hangs fails the request.

View Source
const UpstreamProxySelectionKey = "upstream_proxy.active"

UpstreamProxySelectionKey is the client setting under domain.ReservedClient that holds a project's upstream proxy selection as a JSON string. A missing key means none.

Variables

View Source
var (
	// ErrCheckpointNotFound is returned when a Checkpoint item is missing or already resolved.
	ErrCheckpointNotFound = errors.New("checkpoint item not found")
	// ErrCheckpointExists is returned when a Checkpoint id is already pending.
	ErrCheckpointExists = errors.New("checkpoint item already pending")
	// ErrInterceptResponseNotAllowed is returned when intercept_response is set on a non-request item.
	ErrInterceptResponseNotAllowed = errors.New("intercept_response is only valid for request items")
)
View Source
var (
	// ErrMetadata is returned when metadata is invalid or missing
	ErrMetadataNotFound = errors.New("invalid or missing metadata")

	// ErrExtensionNotFound is returned when extension is invalid or missing
	ErrExtensionNotFound = errors.New("invalid or missing extension")

	// ErrRequestIDNotFound is returned when requestID is not found
	ErrRequestIDNotFound = errors.New("invalid or missing requestID")

	// ErrRebuildRequest is returned when the request is malformed and cannot be rebuilt
	ErrRebuildRequest = errors.New("cannot rebuild request")

	// ErrRebuildResponse is returned when the response is malformed and cannot be rebuilt
	ErrRebuildResponse = errors.New("cannot rebuild response")

	// ErrRequestHandlerUndefined is no longer returned: a proxy with no request handler still captures.
	ErrRequestHandlerUndefined = errors.New("no request handler defined")

	// ErrResponseHandlerUndefined is no longer returned: a proxy with no response handler still captures.
	ErrResponseHandlerUndefined = errors.New("no response handler defined")

	// ErrProxyRequest is returned when ProxyRequest cannot be created
	ErrProxyRequest = errors.New("failed to create proxyrequest")

	// ErrProxyResponse is returned when ErrProxyResponse cannot be created
	ErrProxyResponse = errors.New("failed to create proxyresponse")

	// ErrReadBody is returned when there is an error with reading the response body
	ErrReadBody = errors.New("failed to read the body")

	// ErrWebSocketUpstreamUnavailable is returned when an upgrade response does not expose a bidirectional upstream stream.
	ErrWebSocketUpstreamUnavailable = errors.New("websocket upstream stream unavailable")
)
View Source
var (
	// ErrConfigDirNotSet is returned when the configuration directory is not set.
	ErrConfigDirNotSet = errors.New("config dir not set")
	// ErrScopeNotFound is returned when the scope is not found in the proxy.
	ErrScopeNotFound = errors.New("scope field is not found")
	// ErrClientNotFound is returned when the HTTP client is not found in the proxy.
	ErrClientNotFound = errors.New("http client field not found")
	// ErrExtensionRepoNotFound is returned when the extension repository is not found.
	ErrExtensionRepoNotFound = errors.New("extension repo not found")
	// ErrLaunchpadRepoNotFound is returned when the launchpad repository is not found.
	ErrLaunchpadRepoNotFound = errors.New("launchpad repo not found")
	// ErrWaypointRepoNotFound is returned when the waypoint repository is not found.
	ErrWaypointRepoNotFound = errors.New("waypoint repo not found")
	// ErrReportingRepoNotFound is returned when the reporting repository is not found.
	ErrReportingRepoNotFound = errors.New("reporting repo not found")
	// ErrArmoryRepoNotFound is returned when the Armory repository is not found.
	ErrArmoryRepoNotFound = errors.New("armory repo not found")
	// ErrConfigRepoNotFound is returned when the config repository is not found.
	ErrConfigRepoNotFound = errors.New("config repo not found")
	// ErrStatsRepoNotFound is returned when the stats repository is not found.
	ErrStatsRepoNotFound = errors.New("stats repo not found")
	// ErrArmoryNotFound is returned when the Armory service is not found.
	ErrArmoryNotFound = errors.New("armory service not found")
	// ErrWordlistManagerNotSet is returned when the wordlist manager is not set.
	ErrWordlistManagerNotSet = errors.New("wordlist manager not set")
	// ErrWebSocketConnectionNotFound is returned when a live WebSocket cannot be located.
	ErrWebSocketConnectionNotFound = errors.New("websocket connection not found or closed")
	// ErrWebSocketRepositoryNotSet is returned when WebSocket persistence is unavailable.
	ErrWebSocketRepositoryNotSet = errors.New("websocket repository not set")
	// ErrWebSocketDirection is returned when an inject direction is not client or server.
	ErrWebSocketDirection = errors.New("websocket direction must be client or server")
)
View Source
var (
	// ErrStreamedPairNotFound is returned for a pair that is not a
	// streamed pair being carried.
	ErrStreamedPairNotFound = errors.New("streamed pair not found or ended")
	// ErrStreamDirection is returned for a direction that is not request
	// or response.
	ErrStreamDirection = errors.New("stream direction must be request or response")
	// ErrStreamDirectionNotStreamed is returned for an injection into a
	// direction of the pair that is not carried as stream messages, or
	// not yet.
	ErrStreamDirectionNotStreamed = errors.New("the direction is not carried as stream messages")
	// ErrStreamDirectionEnded is returned for an injection into a
	// direction that ended.
	ErrStreamDirectionEnded = errors.New("the direction ended")
)
View Source
var (
	// ErrStreamedRequestOpen means the pair's request direction is still being
	// carried, so its body is not yet whole.
	ErrStreamedRequestOpen = errors.New("the streamed pair's request direction is still open")
	// ErrStreamedResponseOpen means the pair's SSE response direction is still
	// live or has not finished persisting its response capture.
	ErrStreamedResponseOpen = errors.New("the streamed pair's SSE response direction is still open")
	// ErrResponseNotSSE means the pair has no stored SSE response.
	ErrResponseNotSSE = errors.New("the pair has no SSE response")
)
View Source
var (
	// ErrInvalidUpstreamProxy reports an upstream proxy name, URL or CA that
	// cannot be used. Its messages never contain the URL, which can hold
	// credentials.
	ErrInvalidUpstreamProxy = errors.New("invalid upstream proxy")
	// ErrUpstreamProxyExists reports an add of a name already in the list.
	ErrUpstreamProxyExists = errors.New("upstream proxy already exists")
	// ErrUpstreamProxyNotFound reports a name missing from the list.
	ErrUpstreamProxyNotFound = errors.New("upstream proxy not found")
)
View Source
var ErrDecodedContentTooLarge = errors.New("decoded content is larger than the body threshold")

ErrDecodedContentTooLarge means a coded body decodes to more than the body threshold. Such a body is left coded, as one that does not decode is, so a small compressed body cannot expand into gigabytes of memory.

View Source
var ErrInvalidUpstreamProxyTarget = errors.New("invalid check target")

ErrInvalidUpstreamProxyTarget reports a check target that is not an http or https URL with a host.

View Source
var ErrStreamLengthDeclared = errors.New("the direction's head declares a length")

ErrStreamLengthDeclared is returned for a Checkpoint edit or drop of a stream message whose direction's head declared a length that the change would alter. The message stays held.

View Source
var ErrStreamReadOnly = errors.New("the stream message cannot be edited")

ErrStreamReadOnly is returned for a Checkpoint edit of a stream message compressed with an encoding Marasi does not decode. The message stays held.

View Source
var ErrStreamText = errors.New("the text form cannot be encoded")

ErrStreamText is returned for a Checkpoint edit or an injection given in a text form that cannot be encoded: one that does not parse, which also wraps protoscope.ErrSyntax and names its line and column, one for a message with no text form, or one given with a payload as well.

View Source
var ErrTrailerEdit = errors.New("the trailer block does not parse")

ErrTrailerEdit is returned for a Checkpoint edit of a trailer item with a line that is not a field. The trailers stay held.

Functions

func CheckpointItemFromWebSocket

func CheckpointItemFromWebSocket(message domain.WebSocketMessage) domain.CheckpointItem

CheckpointItemFromWebSocket returns the Checkpoint item for a held WebSocket message.

func CheckpointRequestModifier

func CheckpointRequestModifier(proxy *Proxy, pair *Pair) error

CheckpointRequestModifier holds requests when the global HTTP Checkpoint flag is set or interceptRequest returns true. A nil notify still holds until forward, drop, or drop-all. Forward rebuilds from optional raw. Drop does not rebuild. A Lua error in interceptRequest does not skip the global flag.

func CheckpointResponseModifier

func CheckpointResponseModifier(proxy *Proxy, pair *Pair) error

CheckpointResponseModifier holds responses when the global HTTP Checkpoint flag is set, interceptResponse returns true, or the matching request was forwarded with intercept-response. A nil notify still holds until forward, drop, or drop-all. A Lua error in interceptResponse does not skip either flag.

func CompassRequestModifier

func CompassRequestModifier(proxy *Proxy, pair *Pair) error

CompassRequestModifier will run the `processRequest` function in the compass extension to determine if the request is in scope. After `processRequest`, it will check if the request is passed through (nil), stopped (Stop), or dropped (Drop). If the compass extension is not found the modifier will return `ErrExtensionNotFound` as "compass" is considered a core extension. Compass's skip decision does not apply to a launch (see compassSkips).

func CompassResponseModifier

func CompassResponseModifier(proxy *Proxy, pair *Pair) error

CompassResponseModifier will run the `processResponse` function in the compass extension to determine if the response is in scope. After `processResponse`, it will check if the response is passed through (nil), stopped (Stop), or dropped (Drop). If the compass extension is not found the modifier will return `ErrExtensionNotFound` as "compass" is considered a core extension. Compass's skip decision does not apply to a launch (see compassSkips).

func CompressedResponseModifier

func CompressedResponseModifier(proxy *Proxy, pair *Pair) error

CompressedResponseModifier decodes a response whose content codings are all ones Marasi undoes (gzip, x-gzip, deflate, br and zstd, in any case, one or several, on one field line or several), so the rest of the chain, Checkpoint and storage see the body decoded with Content-Encoding removed and Content-Length set to the decoded length (when the response is not chunked). A response with any other coding is left as received. The pair's metadata records the codings in decoded_content_encoding, lower case and in the order they were applied ("gzip" or "gzip, br"), and the length of the encoded body in wire_content_length.

The client still receives the origin's encoded bytes unless the chain changed the decoded body (docs/adr/2026-11-17-compressed-responses-are-transparent-on-the-wire-and-decoded-in-storage.md). A body that does not decode is not something that broke: it is left as received, so the client and storage get the origin's coded bytes, and metadata.content_decoding_error holds why it did not decode. A body that decodes to more than the body threshold is left coded the same way, and named in a proxy log.

func ExtensionsRequestModifier

func ExtensionsRequestModifier(proxy *Proxy, pair *Pair) error

ExtensionsRequestModifier will run the `processRequest` function (if it is defined) for all the loaded extensions (except compass and checkpoint). Initially the modifier will check if the request originated from an extension by reading the "x-extension-id" header. That extension is recorded on the pair, so that its hooks run on neither half of its own pair. After processRequest, it will check if the request is passed through (nil), stopped (Stop), or dropped (Drop).

func ExtensionsResponseModifier

func ExtensionsResponseModifier(proxy *Proxy, pair *Pair) error

ExtensionsResponseModifier will run the `processResponse` function (if it is defined) for all the loaded extensions (except compass and checkpoint). The modifier will check if the extension ID in request context matches the current extension and skip execution if it does. After `processResponse`, it will check if the request is passed through (nil), stopped (Stop), or dropped (Drop).

func LoadUpstreamProxySelection

func LoadUpstreamProxySelection(repository domain.ConfigRepository) (string, error)

LoadUpstreamProxySelection reads a project's selection, "" for none. A stored value that is not a JSON string is returned as it is, with an error wrapping ErrInvalidUpstreamProxy.

func MarasiPagesModifier

func MarasiPagesModifier(proxy *Proxy, pair *Pair) error

MarasiPagesModifier answers requests for Marasi's own pages and requests that use a pending browser view through Respond. It runs first in the request pipeline, and a response from Respond skips the response chain, so neither is ever captured, held by Checkpoint, or seen by an extension (docs/adr/2026-10-20-a-browser-view-serves-the-stored-response-once-at-its-original-url.md).

func NewProxyRequest

func NewProxyRequest(pair *Pair) (*domain.ProxyRequest, error)

NewProxyRequest creates a new domain.ProxyRequest from the request of pair, with the pair's UUID, metadata and request time, and dumps the raw request.

func NewProxyResponse

func NewProxyResponse(pair *Pair) (*domain.ProxyResponse, error)

NewProxyResponse creates a new domain.ProxyResponse from the pair's response. It takes the ID, response time, metadata and route from the pair and dumps the raw response.

func OverrideWaypointsModifier

func OverrideWaypointsModifier(proxy *Proxy, pair *Pair) error

OverrideWaypointsModifier checks if a Waypoint (host override) is defined for this host:port. If a waypoint exists it will write the "original_host" and "override_host" to the pair's metadata and rewrite the URL host to the destination, which the transport then dials as is. If the pair has no metadata the modifier will return `ErrMetadataNotFound` TODO should allow TLS -> Non TLS override

func ParseUpstreamProxyCA

func ParseUpstreamProxyCA(data string) ([]*x509.Certificate, error)

ParseUpstreamProxyCA parses a PEM bundle that must hold at least one certificate and returns them.

func PreventLoopModifier

func PreventLoopModifier(proxy *Proxy, pair *Pair) error

PreventLoopModifier answers a request made to marasi's active listener address and port with a 502 proxy error response, so it never loops back through the proxy. It normalises localhost and 127.0.0.1 when it checks the host and port. Like a refused request, the pair is set up, stored whatever the scope and its cause logged (docs/adr/2026-11-17-go-modifier-errors-fail-closed-and-proxy-error-responses-never-go-upstream.md).

func ResponseFilterModifier

func ResponseFilterModifier(proxy *Proxy, pair *Pair) error

ResponseFilterModifier will perform an initial filtering round on responses. It skips responses where the skip flag was set. It records when the response was read on the pair. A CONNECT never reaches the chain (see admitTunnel), and neither does a response to a request a request modifier answered or dropped (see WithBasePipeline).

func SetupRequestModifier

func SetupRequestModifier(proxy *Proxy, pair *Pair) error

SetupRequestModifier sets up the pair: its UUID, request time, metadata and route record. It also captures internal Launchpad and Armory correlation IDs. A claimed launch's id becomes the pair's UUID, and a second claim of the same launch is dropped.

func StoreUpstreamProxySelection

func StoreUpstreamProxySelection(repository domain.ConfigRepository, name string) error

StoreUpstreamProxySelection writes a project's selection, deleting it for none ("").

func UpstreamProxyIndex

func UpstreamProxyIndex(entries []UpstreamProxyConfig, name string) int

UpstreamProxyIndex returns the index of the entry called name in entries, or -1 when there is none.

func ValidateUpstreamProxyName

func ValidateUpstreamProxyName(name string) error

ValidateUpstreamProxyName checks name against the client-name pattern.

func WebSocketNegotiationModifier

func WebSocketNegotiationModifier(proxy *Proxy, pair *Pair) error

WebSocketNegotiationModifier sets the client's extension response to exactly what the upstream accepted, undoing any edit made after the upstream answered. It runs after Extensions and Checkpoint and before WriteResponseModifier, so the stored response is the one the client gets.

func WebSocketOffersModifier

func WebSocketOffersModifier(proxy *Proxy, pair *Pair) error

WebSocketOffersModifier removes every WebSocket extension offer except permessage-deflate from an upgrade request and records the removed names. It runs after Extensions and Checkpoint so their edits are filtered too.

func WebSocketPrepareModifier

func WebSocketPrepareModifier(proxy *Proxy, pair *Pair) error

WebSocketPrepareModifier detaches the upstream stream from a successful upgrade response and marks the request metadata state as open.

func WebSocketUpgradeHandler

func WebSocketUpgradeHandler(proxy *Proxy, pair *Pair, client, upstream io.ReadWriteCloser) error

WebSocketUpgradeHandler is the upgrade handler for WebSocket: it relays the session between the client and the origin and records it. The proxy has already written the 101 to the client.

func WithArmory

func WithArmory(service ArmoryService) func(*Proxy) error

WithArmory sets the Armory service exposed by the proxy.

func WithArmoryRepository

func WithArmoryRepository(repo domain.ArmoryRepository) func(*Proxy) error

WithArmoryRepository injects the Armory repository implementation.

func WithBasePipeline

func WithBasePipeline() func(*Proxy) error

WithBasePipeline will setup the base modifier pipeline for marasi It will define the main Request & Response steps that will execute the attached modifiers and carry out the control a modifier set on the pair. Work is admitted for the request modifiers and again, once the response body has been read, for the response modifiers, never for the wait on the origin. If a response is dropped the client connection is taken over and closed. A 101 that the response chain passes is handed to the upgrade handler.

func WithBrowserViewExpiry

func WithBrowserViewExpiry(expiry time.Duration) func(*Proxy) error

WithBrowserViewExpiry sets how long a pending browser view waits for its redirect to be followed. The default is 10 seconds (docs/adr/2026-10-20-a-browser-view-serves-the-stored-response-once-at-its-original-url.md).

func WithCheckpointAbandonedHandler

func WithCheckpointAbandonedHandler(handler func(item domain.CheckpointItem) error) func(*Proxy) error

WithCheckpointAbandonedHandler sets OnCheckpointAbandoned for Checkpoint items dropped because their client left or their WebSocket connection closed. Its return error is ignored.

func WithConfigDir

func WithConfigDir(appConfigDir string) func(*Proxy) error

WithConfigDir configures the proxy to use the specified configuration directory. It creates the directory if it doesn't exist and initializes the configuration file using Viper.

Parameters:

  • appConfigDir: Path to the configuration directory

Returns:

  • func(*Proxy) error: Configuration function that sets up the config directory

func WithConfigRepository

func WithConfigRepository(repo domain.ConfigRepository) func(*Proxy) error

WithConfigRepository injects the config repository implementation.

func WithDBCloser

func WithDBCloser(closer io.Closer) func(*Proxy) error

WithDBCloser injects the database closer.

func WithDefaultModifierPipeline

func WithDefaultModifierPipeline() func(*Proxy) error

WithDefaultModifierPipeline adds the default request and response modifiers. They run in the order they are added below. The base pipeline has already buffered the response body.

func WithDefaultRepositories

func WithDefaultRepositories(repo RepositoryProvider) func(*Proxy) error

WithDefaultRepositories is a convenience option to apply all repository implementations from a single provider.

func WithExtension

func WithExtension(extension *domain.Extension, options ...func(*extensions.Runtime) error) func(*Proxy) error

TODO: Need to fix this, currently if the extension exists it does not overrite it, this breaks opening new projects WithExtension loads a single extension into the proxy. It prepares the extension's Lua state and adds it to the proxy's extension list.

func WithExtensionRepository

func WithExtensionRepository(repo domain.ExtensionRepository) func(*Proxy) error

WithExtensionRepository injects the extension repository implementation.

func WithExtensions

func WithExtensions(exts []*domain.Extension, options ...func(*extensions.Runtime) error) func(*Proxy) error

WithExtensions loads multiple extensions into the proxy. It iterates through the provided extensions and prepares each one.

func WithInterceptHandler

func WithInterceptHandler(handler func(item domain.CheckpointItem) error) func(*Proxy) error

WithInterceptHandler sets OnIntercept for pending HTTP Checkpoint items. The handler runs synchronously, and its return error is ignored. A blocking handler blocks the intercepted execution.

func WithLaunchFinishedHandler

func WithLaunchFinishedHandler(handler func(domain.Launch)) func(*Proxy) error

WithLaunchFinishedHandler sets OnLaunchFinished, called once per launch on its terminal state.

func WithLaunchStartedHandler

func WithLaunchStartedHandler(handler func(domain.Launch)) func(*Proxy) error

WithLaunchStartedHandler sets OnLaunchStarted, called once a launch is accepted.

func WithLaunchpadRepository

func WithLaunchpadRepository(repo domain.LaunchpadRepository) func(*Proxy) error

WithLaunchpadRepository injects the launchpad repository implementation.

func WithLogHandler

func WithLogHandler(handler func(log domain.Log) error) func(*Proxy) error

WithLogHandler takes a handler function that will be executed on each Log

func WithLogRepository

func WithLogRepository(repo domain.LogRepository) func(*Proxy) error

WithLogRepository injects the log repository implementation.

func WithLogger

func WithLogger(logger *slog.Logger) func(*Proxy) error

WithLogger sets the structured logger for the proxy. It performs a nil check to ensure the proxy always has a valid logger.

func WithReportGenerator

func WithReportGenerator(generator domain.ReportGenerator) func(*Proxy) error

WithReportGenerator injects the report generator implementation.

func WithReportingRepository

func WithReportingRepository(repo domain.ReportingRepository) func(*Proxy) error

WithReportingRepository injects the reporting repository implementation.

func WithRequestHandler

func WithRequestHandler(handler func(req domain.ProxyRequest) error) func(*Proxy) error

WithRequestHandler takes a handler function that will be executed on each Request

func WithResponseHandler

func WithResponseHandler(handler func(res domain.ProxyResponse) error) func(*Proxy) error

WithResponseHandler takes a handler function that will be executed on each response

func WithStatsRepository

func WithStatsRepository(repo domain.StatsRepository) func(*Proxy) error

WithStatsRepository injects the stats repository implementation.

func WithStreamMessageHandler

func WithStreamMessageHandler(handler func(domain.StreamMessage)) func(*Proxy) error

WithStreamMessageHandler sets OnStreamMessage.

func WithStreamMessageProgressHandler

func WithStreamMessageProgressHandler(handler func(domain.StreamMessageProgress)) func(*Proxy) error

WithStreamMessageProgressHandler sets OnStreamMessageProgress.

func WithStreamRepository

func WithStreamRepository(repo domain.StreamRepository) func(*Proxy) error

WithStreamRepository injects the stream message repository implementation.

func WithStreamedPairEndedHandler

func WithStreamedPairEndedHandler(handler func(domain.StreamedPairEnded)) func(*Proxy) error

WithStreamedPairEndedHandler sets OnStreamedPairEnded.

func WithStreamedPairStartedHandler

func WithStreamedPairStartedHandler(handler func(domain.StreamedPairStarted)) func(*Proxy) error

WithStreamedPairStartedHandler sets OnStreamedPairStarted.

func WithStreamedPairUpdatedHandler

func WithStreamedPairUpdatedHandler(handler func(domain.StreamedPairUpdated)) func(*Proxy) error

WithStreamedPairUpdatedHandler sets OnStreamedPairUpdated.

func WithTLS

func WithTLS() func(*Proxy) error

WithTLS will configure the proxy CA based on the proxy.ConfigDir It will also configure the http.Client that is used for the launchpad requests TODO - Check if the certificate expired

func WithTLSContext

func WithTLSContext(ctx context.Context) func(*Proxy) error

WithTLSContext configures TLS like WithTLS and allows cancellation while waiting for another process to finish initializing the shared CA.

func WithTrafficRepository

func WithTrafficRepository(repo domain.TrafficRepository) func(*Proxy) error

WithTrafficRepository injects the traffic repository implementation.

func WithUpstreamProxyTimeout

func WithUpstreamProxyTimeout(timeout time.Duration) func(*Proxy) error

WithUpstreamProxyTimeout bounds how long reaching an upstream proxy and opening a tunnel through it may take before the request fails. The default is DefaultUpstreamProxyTimeout.

func WithWaypointRepository

func WithWaypointRepository(repo domain.WaypointRepository) func(*Proxy) error

WithWaypointRepository injects the waypoint repository implementation.

func WithWebSocketCloseHandler

func WithWebSocketCloseHandler(handler func(domain.WebSocketConnection) error) func(*Proxy) error

WithWebSocketCloseHandler takes a handler function that will be executed when a WebSocket connection closes.

func WithWebSocketHandshakeEndedHandler

func WithWebSocketHandshakeEndedHandler(handler func(requestID uuid.UUID, state string)) func(*Proxy) error

WithWebSocketHandshakeEndedHandler sets OnWebSocketHandshakeEnded, called once an upgrade that failed or was dropped has its websocket.state stored.

func WithWebSocketInterceptHandler

func WithWebSocketInterceptHandler(handler func(domain.WebSocketMessage) error) func(*Proxy) error

WithWebSocketInterceptHandler takes a handler function that will be executed when a WebSocket message is intercepted.

func WithWebSocketMessageHandler

func WithWebSocketMessageHandler(handler func(domain.WebSocketMessage) error) func(*Proxy) error

WithWebSocketMessageHandler takes a handler function that will be executed for each WebSocket message.

func WithWebSocketOpenHandler

func WithWebSocketOpenHandler(handler func(domain.WebSocketConnection) error) func(*Proxy) error

WithWebSocketOpenHandler takes a handler function that will be executed when a WebSocket connection opens.

func WithWebSocketProgressHandler

func WithWebSocketProgressHandler(handler func(domain.WebSocketMessageProgress) error) func(*Proxy) error

WithWebSocketProgressHandler takes a handler function that will be executed while a WebSocket message's frames are still arriving. It must not block.

func WithWebSocketRepository

func WithWebSocketRepository(repo domain.WebSocketRepository) func(*Proxy) error

WithWebSocketRepository injects the WebSocket repository implementation.

func WithWordlistManager

func WithWordlistManager(manager wordlist.Provider) func(*Proxy) error

WithWordlistManager injects the wordlist provider implementation.

func WithWorkAdmission

func WithWorkAdmission(admit func(context.Context, bool) (func(), uint64, error)) func(*Proxy) error

WithWorkAdmission coordinates proxy traffic with service lifecycle changes. The boolean identifies requests made by the proxy's own client, including CONNECT. admit returns the work's release and the generation of the open project it runs in. A request is admitted for its request-side work and again for its response-side work, and a response admitted in another generation than its request skips every project-bound step (docs/adr/2026-10-17-project-switch-never-waits-on-the-network.md).

func WriteRequestModifier

func WriteRequestModifier(proxy *Proxy, pair *Pair) error

WriteRequestModifier is the final modifier in the default request pipeline. It will create a `ProxyRequest` struct and queue it for database insertion. If the request came from launchpad, it will create a `LaunchpadRequest` struct and queue it for database insertion as well. If the `proxy.OnRequest` handler is defined, it is called with the `ProxyRequest`. A proxy with no handler still captures the request.

func WriteResponseModifier

func WriteResponseModifier(proxy *Proxy, pair *Pair) error

WriteResponseModifier is the final modifier in the default response pipeline. It will create a `ProxyResponse` struct and queue it for database insertion. If the `proxy.OnResponse` handler is defined, it is called with the `ProxyResponse`. A proxy with no handler still captures the response.

Types

type ArmoryService

type ArmoryService interface {
	Repo() domain.ArmoryRepository
	ValidateRun(*domain.ArmoryRun) error
	ValidateTemplate(*domain.ArmoryTemplate) error
	StartRun(uuid.UUID) error
	CancelRun(uuid.UUID) error
	ActiveRunIDs() []uuid.UUID
	Shutdown()
}

ArmoryService defines the Armory operations exposed by the proxy.

type BodyEnding

type BodyEnding int

BodyEnding is how the proxy's read of a body ended. The proxy reads each body whole before the chains run, so a modifier always sees what arrived.

const (
	// BodyUnread means the proxy did not read the body: there is no
	// response yet, it is the proxy's own answer, or it is an upgrade's
	// connection.
	BodyUnread BodyEnding = iota
	// BodyComplete means the body arrived whole, or there was none.
	BodyComplete
	// BodyCutShort means the peer stopped sending, or the read failed,
	// before the body was whole.
	BodyCutShort
	// BodyTooLarge means the body passed the body threshold, so it was
	// forwarded as it arrived and only what came before is kept
	// (body_threshold.go).
	BodyTooLarge
)

func (BodyEnding) String

func (ending BodyEnding) String() string

String returns the ending in words.

type CheckpointForward

type CheckpointForward struct {
	// Raw replaces the dumped HTTP request or response when non-nil.
	Raw *[]byte
	// InterceptResponse holds the matching response after a request forward.
	InterceptResponse bool
	// Payload replaces the WebSocket frame payload, or the stream message
	// payload, when non-nil.
	Payload *[]byte
	// Text replaces the stream message payload with what its text form
	// encodes to when non-nil (stream.FromText). It is refused with
	// ErrStreamText alongside Payload.
	Text *string
	// Opcode replaces the WebSocket frame opcode when non-nil.
	Opcode *int
}

CheckpointForward is the optional edit applied when forwarding a pending Checkpoint item.

type Config

type Config struct {
	ConfigDir      string              `mapstructure:"config_dir"` // Current config dir
	DesktopOS      string              `mapstructure:"desktop_os"` // Operating system identifier
	ChromeDirs     []chrome.PathConfig `mapstructure:"chrome_dirs"`
	ChromeProfiles []string            `mapstructure:"chrome_profiles"`
	// WebSocketMaxMessageSize is the per-message WebSocket size limit in
	// bytes, set by websocket_max_message_size in marasi_config.yaml. Zero or
	// unset means websocket.DefaultMaxMessageSize (64 MiB). A negative value
	// is rejected when the config loads.
	WebSocketMaxMessageSize int64 `mapstructure:"websocket_max_message_size"`
	// StreamMaxMessageSize is the per-message limit of a streamed pair's
	// stream messages in bytes, set by stream_max_message_size in
	// marasi_config.yaml. Zero or unset means stream.DefaultMaxMessageSize
	// (64 MiB). A negative value is rejected when the config loads.
	StreamMaxMessageSize int64 `mapstructure:"stream_max_message_size"`
	// BodyThreshold is the size in bytes past which an ordinary pair's body
	// is forwarded as it arrives instead of read whole, set by
	// body_threshold in marasi_config.yaml. Zero or unset means
	// DefaultBodyThreshold (64 MiB). A negative value is rejected when the
	// config loads.
	BodyThreshold int64 `mapstructure:"body_threshold"`
	// Updates is the updates section of marasi_config.yaml.
	Updates UpdatesConfig `mapstructure:"updates"`
	// UpstreamProxies is the machine's upstream proxy list, the
	// upstream_proxies section of marasi_config.yaml. Entries are checked
	// when they are added or updated, not when the file loads, so a bad hand
	// edit fails only the route that uses it.
	UpstreamProxies []UpstreamProxyConfig `mapstructure:"upstream_proxies"`
	// contains filtered or unexported fields
}

func ReadConfig

func ReadConfig(configDir string) (*Config, error)

ReadConfig reads marasi_config.yaml in configDir into a new Config without touching any loaded one. Callers that share the file with other instances hold the config lock while they read and write (docs/adr/2026-10-06-chrome-config-lock-reread.md).

func (*Config) AddChromePath

func (cfg *Config) AddChromePath(path, os string) error

func (*Config) AddChromeProfile

func (cfg *Config) AddChromeProfile(name string) error

AddChromeProfile adds a chrome profile to the configuration.

func (*Config) AddUpstreamProxy

func (cfg *Config) AddUpstreamProxy(entry UpstreamProxyConfig) error

AddUpstreamProxy appends entry to the upstream proxy list and saves the configuration. Callers hold the config lock and reread first (docs/adr/2026-10-06-chrome-config-lock-reread.md).

func (*Config) DeleteChromePath

func (cfg *Config) DeleteChromePath(path, os string) error

func (*Config) DeleteChromeProfile

func (cfg *Config) DeleteChromeProfile(name string) error

DeleteChromeProfile deletes a chrome profile from the configuration and removes its profile directory from disk.

func (*Config) ReloadChrome

func (cfg *Config) ReloadChrome() error

ReloadChrome rereads machine Chrome configuration into cfg.

func (*Config) RemoveUpstreamProxy

func (cfg *Config) RemoveUpstreamProxy(name string) error

RemoveUpstreamProxy removes the named entry and saves the configuration. Callers hold the config lock and reread first.

func (*Config) SetUpdateChannel

func (cfg *Config) SetUpdateChannel(channel update.Channel) error

SetUpdateChannel saves channel as updates.channel. Callers hold the config lock and reread first (docs/adr/2026-10-06-chrome-config-lock-reread.md).

func (*Config) UpdateUpstreamProxy

func (cfg *Config) UpdateUpstreamProxy(name string, update UpstreamProxyUpdate) error

UpdateUpstreamProxy changes the named entry and saves the configuration. Callers hold the config lock and reread first.

type JoinedRequest

type JoinedRequest struct {
	ID uuid.UUID
	// Raw is the stored request head followed by the body. For a pair
	// that is not a streamed pair, or whose request direction is not
	// streamed, it is the stored raw request unchanged.
	Raw []byte
	// Streamed reports that the body was joined from the request's stream
	// messages.
	Streamed bool
	// Messages is how many request messages the body joins, and Omitted
	// how many stored request messages it leaves out because they never
	// reached the origin whole: dropped, too large, cut short or not
	// decoded.
	Messages int
	Omitted  int
	// contains filtered or unexported fields
}

JoinedRequest is a pair's raw request with its body as it went to the origin.

type JoinedSSEResponse

type JoinedSSEResponse struct {
	ID uuid.UUID
	// contains filtered or unexported fields
}

JoinedSSEResponse streams a pair's stored SSE response head followed by its forwarded decoded SSE event payloads in stream order, reading stream messages one page at a time.

func (*JoinedSSEResponse) WriteTo

func (r *JoinedSSEResponse) WriteTo(w io.Writer) (int64, error)

WriteTo writes the stored SSE response head, blank line, and each forwarded SSE event payload to w incrementally, one database page at a time.

func (*JoinedSSEResponse) WriteToContext

func (r *JoinedSSEResponse) WriteToContext(ctx context.Context, w io.Writer) (int64, error)

WriteToContext writes the stored SSE response head, blank line, and each forwarded SSE event payload to w incrementally, stopping if ctx ends.

type ModifierGroup

type ModifierGroup struct {
	// contains filtered or unexported fields
}

ModifierGroup runs pair modifiers in the order they were added.

func NewModifierGroup

func NewModifierGroup() *ModifierGroup

NewModifierGroup returns an empty modifier group.

func (*ModifierGroup) Add

func (group *ModifierGroup) Add(modifier PairModifier)

Add appends modifier to the end of the group.

func (*ModifierGroup) Modify

func (group *ModifierGroup) Modify(proxy *Proxy, pair *Pair) error

Modify runs every modifier in the order added. It stops at the first error, which it returns, or at the first control a modifier sets on the pair.

type Pair

type Pair struct {
	// Request is the request as it will go upstream.
	Request *http.Request
	// Response is the response, nil on the request chain.
	Response *http.Response
	// ID is the pair UUID. It is uuid.Nil until the pair is set up.
	ID uuid.UUID
	// Metadata is the document stored with the pair.
	Metadata map[string]any
	// Timing records when the request and the response were read.
	Timing PairTiming
	// Route collects the route the request went out on.
	Route *core.RouteRecord
	// LaunchpadID is the launchpad a launch came from, or uuid.Nil.
	LaunchpadID uuid.UUID
	// ExtensionID is the extension that sent the request, or uuid.Nil. That
	// extension's hooks do not run on its own pair.
	ExtensionID uuid.UUID
	// Skipped is set when an extension skipped the pair: it goes on with no
	// further extension or Checkpoint and is not stored.
	Skipped bool
	// InterceptResponse is set when Checkpoint was asked, while holding the
	// request, to hold the response too.
	InterceptResponse bool
	// ArmoryRunID is the Armory run that made the request, or uuid.Nil.
	ArmoryRunID uuid.UUID
	// RequestBodyEnding is how the proxy's read of the request body ended.
	RequestBodyEnding BodyEnding
	// ResponseBodyEnding is how the proxy's read of the response body
	// ended, BodyUnread on the request chain.
	ResponseBodyEnding BodyEnding
	// contains filtered or unexported fields
}

Pair is a request/response pair in flight: one request and its matching response, identified by one UUID from the moment the proxy reads the request. Modifiers read and edit its typed fields instead of values in a context.

func NewTestPair

func NewTestPair(req *http.Request) *Pair

NewTestPair builds a pair around req for modifier unit tests, as the proxy would set it up: a new pair UUID, empty metadata, the request time and an empty route record. Tests set any other field directly.

func (*Pair) Context

func (pair *Pair) Context() context.Context

Context returns the pair's context. It is done when the client leaves or the proxy stops, and carries no pair values.

func (*Pair) Drop

func (pair *Pair) Drop()

Drop ends the chain and the pair: a request does not go upstream, and a response does not reach the client, whose connection is closed.

func (*Pair) Dropped

func (pair *Pair) Dropped() bool

Dropped reports whether a modifier dropped the pair.

func (*Pair) FromMarasi

func (pair *Pair) FromMarasi() bool

FromMarasi reports whether the pair's response is one Marasi made through Respond, rather than one the origin sent.

func (*Pair) Respond

func (pair *Pair) Respond(res *http.Response)

Respond ends the chain and answers the pair with res, which Marasi made. On the request chain the request never goes upstream and no response modifier runs; on the response chain res replaces the origin's response. A res without a request is given the pair's.

func (*Pair) Stop

func (pair *Pair) Stop()

Stop ends the chain. The pair goes on, with no further modifier in this chain.

type PairModifier

type PairModifier func(proxy *Proxy, pair *Pair) error

PairModifier edits a pair on the request chain or the response chain. It ends the chain with a control on the pair (Respond, Drop or Stop). A returned error means only that something broke, and also stops the chain.

type PairTiming

type PairTiming struct {
	Requested time.Time
	Responded time.Time
}

PairTiming records when each half of a pair was read.

type ProjectResources

type ProjectResources struct {
	Repository      RepositoryProvider
	Extensions      []*extensions.Runtime
	Scope           *compass.Scope
	Waypoints       map[string]string
	Armory          ArmoryService
	ReportGenerator domain.ReportGenerator
	// UpstreamProxy is the project's upstream proxy selection, or "" for a
	// direct connection.
	UpstreamProxy string
}

ProjectResources is the complete set of dependencies owned by one open project.

type Proxy

type Proxy struct {
	ConfigDir      string                               // The configuration directory (defaults to the marasi folder under the user configuration directory)
	Config         *Config                              // The marasi proxy configuration (separate from the GUI config)
	DBWriteChannel chan any                             // DB Write Channel
	OnRequest      func(req domain.ProxyRequest) error  // Function to be ran on each request - used by the GUI application to handle the new requests
	OnResponse     func(res domain.ProxyResponse) error // Function to be ran on each response - used by the GUI application to handle the new responses
	// OnIntercept runs synchronously after an HTTP Checkpoint item becomes pending.
	// Its return error is ignored. A blocking callback blocks the intercepted execution.
	OnIntercept func(item domain.CheckpointItem) error
	// OnCheckpointAbandoned runs after a Checkpoint item is dropped because its
	// client left or its WebSocket connection closed (docs/adr/2026-10-13-checkpoint-hold-ends-when-its-client-leaves.md). It is not called for a
	// forward or drop that resolved the item first.
	// Its return error is ignored.
	OnCheckpointAbandoned func(item domain.CheckpointItem) error
	OnLog                 func(log domain.Log) error // Function to be ran on each log event - used by the GUI application to handle new log entries
	// OnWebSocketOpen is called when a WebSocket connection opens.
	OnWebSocketOpen func(domain.WebSocketConnection) error
	// OnWebSocketMessage is called for each processed WebSocket message.
	OnWebSocketMessage func(domain.WebSocketMessage) error
	// OnWebSocketProgress is called while a WebSocket message's frames are
	// still arriving. It runs on the relay and must not block.
	OnWebSocketProgress func(domain.WebSocketMessageProgress) error
	// OnWebSocketClose is called when a WebSocket connection closes.
	OnWebSocketClose func(domain.WebSocketConnection) error
	// OnWebSocketIntercept is called when a WebSocket message is paused for inspection.
	OnWebSocketIntercept func(domain.WebSocketMessage) error
	// OnWebSocketHandshakeEnded is called with websocket.state failed or
	// dropped for an upgrade that will not open, once that state is stored.
	OnWebSocketHandshakeEnded func(requestID uuid.UUID, state string)
	// Streamed pairs (GLOSSARY) are announced for pairs that are stored,
	// from the goroutines that carry them; the handlers must not block.
	// OnStreamedPairStarted is called once the first head naming a
	// message framing is read.
	OnStreamedPairStarted func(domain.StreamedPairStarted)
	// OnStreamedPairUpdated is called when a direction of a started
	// streamed pair becomes known after it started, such as a gRPC call's
	// response once its head is admitted.
	OnStreamedPairUpdated func(domain.StreamedPairUpdated)
	// OnStreamMessage is called for each stream message once it is whole,
	// cut short or too large, in the order of each direction.
	OnStreamMessage func(domain.StreamMessage)
	// OnStreamMessageProgress is called while a stream message is still
	// arriving, at most once per streamProgressInterval per direction.
	OnStreamMessageProgress func(domain.StreamMessageProgress)
	// OnStreamedPairEnded is called once every streamed direction of a
	// pair ended, after its response is stored.
	OnStreamedPairEnded func(domain.StreamedPairEnded)
	// OnLaunchStarted is called once a launch is accepted, before it is sent.
	OnLaunchStarted func(domain.Launch)
	// OnLaunchFinished is called once per launch when it reaches a terminal state.
	OnLaunchFinished      func(domain.Launch)
	Addr                  string                // IP Address of the proxy
	Port                  string                // Port of the proxy
	Client                *http.Client          // Sends through Marasi's own listener, so launches, Armory and extensions run the full pipeline and are captured
	Extensions            []*extensions.Runtime // Slice of loaded extensions
	WordlistManager       wordlist.Provider     // Provider for available wordlists.
	SPKIHash              string                // SPKI Hash of the current certificate
	Cert                  *x509.Certificate     // The proxy's TLS certificate.
	MarasiClientTLSConfig *tls.Config           // TLSConfig for the proxy.Client
	Scope                 *compass.Scope        // Proxy scope configuration through Compass
	Waypoints             map[string]string     // Published host:port overrides. Replaced, never mutated.

	// WebSocketRegistry tracks live WebSocket connections.
	WebSocketRegistry *marasiws.Registry
	// WebSocketInterceptor pauses WebSocket messages for manual inspection.
	WebSocketInterceptor *marasiws.Interceptor

	TrafficRepo   domain.TrafficRepository   // Repository for traffic data.
	LaunchpadRepo domain.LaunchpadRepository // Repository for launchpad data.
	ArmoryRepo    domain.ArmoryRepository    // Repository for Armory data.
	WaypointRepo  domain.WaypointRepository  // Repository for waypoint data.
	StatsRepo     domain.StatsRepository     // Repository for statistics data.
	ConfigRepo    domain.ConfigRepository    // Repository for configuration data.
	LogRepo       domain.LogRepository       // Repository for log data.
	ExtensionRepo domain.ExtensionRepository // Repository for extension data.
	ReportingRepo domain.ReportingRepository // Repository for reporting data.
	WebSocketRepo domain.WebSocketRepository // Repository for websocket data
	StreamRepo    domain.StreamRepository    // Repository for stream messages

	Armory          ArmoryService          // Provides persistence and execution operations for request fuzzing.
	ReportGenerator domain.ReportGenerator // Generator for report templates and exports.
	DBCloser        io.Closer              // Closer for the database connection.
	Logger          *slog.Logger           // Logger for Marasi
	// contains filtered or unexported fields
}

Proxy is the main struct that orchestrates all proxy functionality including request/response processing, extension management, database operations, and TLS handling. It serves as the central coordinator for the Marasi proxy server.

func New

func New(options ...func(*Proxy) error) (*Proxy, error)

New creates a new Proxy instance with default configuration and applies any provided options. It initializes the proxy engine, database write channel, extensions map, HTTP client, scope, waypoints, and sets up default log modifiers.

Parameters:

  • options: Variadic list of option functions to configure the proxy

Returns:

  • *Proxy: Configured proxy instance
  • error: Configuration error if any option fails

func (*Proxy) ActiveListenerAddress

func (proxy *Proxy) ActiveListenerAddress() (string, bool)

ActiveListenerAddress returns the bound address of the listener currently served by the proxy.

func (*Proxy) AddRequestPairModifier

func (proxy *Proxy) AddRequestPairModifier(modifier PairModifier)

AddRequestPairModifier adds modifier to the end of the request chain.

func (*Proxy) AddResponsePairModifier

func (proxy *Proxy) AddResponsePairModifier(modifier PairModifier)

AddResponsePairModifier adds modifier to the end of the response chain.

func (*Proxy) ApplyWaypointChange

func (proxy *Proxy) ApplyWaypointChange(change func(domain.WaypointRepository) (publish bool, err error)) (bool, error)

ApplyWaypointChange persists a waypoint change and publishes the resulting routes as one snapshot. change reports whether that snapshot should replace the live routes. change must not call back into the proxy.

func (*Proxy) CancelLaunch

func (proxy *Proxy) CancelLaunch(id uuid.UUID) (domain.Launch, error)

CancelLaunch cancels a pending launch by cancelling the proxy client's request context, and returns the launch as it will end: cancelled.

A launch that has already reached a terminal state is returned with its final state and domain.ErrLaunchFinished. An id that names no launch returns domain.ErrLaunchNotFound.

func (*Proxy) CancelStreamedPair

func (proxy *Proxy) CancelStreamedPair(pairID uuid.UUID) error

CancelStreamedPair cancels the streamed pair pairID on both legs: RST_STREAM CANCEL toward the client and toward the origin on HTTP/2, and both connections closed on HTTP/1.1. Each direction still going is recorded cancelled, and the pair's held stream messages are abandoned.

func (*Proxy) CheckUpstreamProxy

func (proxy *Proxy) CheckUpstreamProxy(ctx context.Context, name, target string) (UpstreamProxyCheck, error)

CheckUpstreamProxy makes one test connection to target through the named entry of this machine's list, selected or not, and reports how it went. It dials exactly as traffic does: the same route dial and, for an https target, the same TLS handshake with the origin. It sends no request, so it stores no pair or proxy log, publishes nothing and leaves the selection alone. A name missing from the list is ErrUpstreamProxyNotFound and a bad target is ErrInvalidUpstreamProxyTarget.

func (*Proxy) CheckpointHoldStarted

func (proxy *Proxy) CheckpointHoldStarted() <-chan struct{}

CheckpointHoldStarted returns a channel closed when the next Checkpoint item becomes pending. A hold replaces the channel, so callers must re-check HasPendingCheckpoint after receiving.

func (*Proxy) CheckpointItems

func (proxy *Proxy) CheckpointItems() []domain.CheckpointItem

CheckpointItems returns pending HTTP, WebSocket and stream items in hold order, oldest first.

func (*Proxy) Close

func (proxy *Proxy) Close() error

Close shuts down the proxy and closes the database connection.

func (*Proxy) CloseLiveTrafficAndFlush

func (proxy *Proxy) CloseLiveTrafficAndFlush() error

CloseLiveTrafficAndFlush cancels the streamed pairs being carried and closes live WebSockets, waits until they ended, and flushes what they queued for storage, so none of it reaches the project opened next.

func (*Proxy) CloseTransport

func (proxy *Proxy) CloseTransport() error

CloseTransport stops listeners and live connections without closing the open project's database. The service project lifecycle closes that resource.

func (*Proxy) CloseTransportContext

func (proxy *Proxy) CloseTransportContext(ctx context.Context) error

CloseTransportContext allows traffic to finish until ctx expires, then interrupts network work and joins its handlers before flushing persistence.

func (*Proxy) CloseWebSocket

func (proxy *Proxy) CloseWebSocket(requestID uuid.UUID, code int, reason string) error

CloseWebSocket closes a live connection identified by its upgrade request ID. A code of 0 is treated as normal closure 1000.

func (*Proxy) CloseWebSockets

func (proxy *Proxy) CloseWebSockets(code int, reason string) error

CloseWebSockets closes every live WebSocket connection.

func (*Proxy) CloseWebSocketsAndFlush

func (proxy *Proxy) CloseWebSocketsAndFlush() error

CloseWebSocketsAndFlush normally closes live WebSockets and flushes their persistence updates.

func (*Proxy) CreateArmoryTemplateFromPair

func (proxy *Proxy) CreateArmoryTemplateFromPair(id uuid.UUID) (*domain.ArmoryTemplate, error)

CreateArmoryTemplateFromPair builds an Armory template from pair id's request and stores it. The template is named "METHOD host path" and holds the joined request, escaped so it renders back to the captured text (docs/adr/2026-11-23-armory-templates-name-their-framing-and-hold-messages-as-text-forms.md). A streamed request direction is built as a message-form body: each joined request message in its text form under a separator, with the framing the messages were sent in. One whose messages have no text form is built from the joined request as raw text, with no framing. A Connect unary request is built as a message-form body of its one message, with the framing connect (armory.ConnectUnaryTemplate). It has no payload positions until the tester adds them. A pair that is not stored returns an error wrapping domain.ErrPairNotFound.

func (*Proxy) CurrentRoute

func (proxy *Proxy) CurrentRoute() *Route

CurrentRoute returns the route new connections to the origin use.

func (*Proxy) DeleteLaunchpad

func (proxy *Proxy) DeleteLaunchpad(launchpadID uuid.UUID) error

DeleteLaunchpad deletes a launchpad, as domain.LaunchpadRepository's DeleteLaunchpad does, unless a launch from it is pending, whether or not its pair is written yet. Then it returns a *domain.LaunchPendingError naming those launches.

func (*Proxy) DeleteTraffic

func (proxy *Proxy) DeleteTraffic(sel domain.Selection) (int, error)

DeleteTraffic deletes every pair in sel, as domain.TrafficRepository's DeleteTraffic does, unless sel holds a pending launch's pair. Then it deletes nothing and returns a *domain.LaunchPendingError naming those pairs. A pair in flight that is not a launch can still be deleted.

func (*Proxy) DropAllCheckpoint

func (proxy *Proxy) DropAllCheckpoint() []domain.CheckpointItem

DropAllCheckpoint unblocks every pending HTTP, WebSocket and stream item as drop. It returns the items it actually removed.

func (*Proxy) DropCheckpoint

func (proxy *Proxy) DropCheckpoint(id uuid.UUID) error

DropCheckpoint dequeues a pending item without sending it.

func (*Proxy) ForceCloseTransport

func (proxy *Proxy) ForceCloseTransport()

ForceCloseTransport interrupts network work without releasing handler ownership. Full shutdown still joins those handlers before closing persistence.

func (*Proxy) ForwardCheckpoint

func (proxy *Proxy) ForwardCheckpoint(id uuid.UUID, fwd CheckpointForward) error

ForwardCheckpoint dequeues a pending item and forwards it with optional edits.

func (*Proxy) GetArmory

func (proxy *Proxy) GetArmory() (ArmoryService, error)

GetArmory returns the Armory service. It returns an error if the service is not set.

func (*Proxy) GetArmoryRepo

func (proxy *Proxy) GetArmoryRepo() (domain.ArmoryRepository, error)

GetArmoryRepo returns the Armory repository. It returns an error if the repository is not set.

func (*Proxy) GetCheckpoint

func (proxy *Proxy) GetCheckpoint(id uuid.UUID) (domain.CheckpointItem, bool)

GetCheckpoint returns one pending Checkpoint item.

func (*Proxy) GetClient

func (proxy *Proxy) GetClient() (*http.Client, error)

GetClient returns the proxy's HTTP client. It returns an error if the client is not set.

func (*Proxy) GetConfigDir

func (proxy *Proxy) GetConfigDir() (string, error)

GetConfigDir returns the configuration directory path. It returns an error if the configuration directory is not set.

func (*Proxy) GetConfigRepo

func (proxy *Proxy) GetConfigRepo() (domain.ConfigRepository, error)

GetConfigRepo returns the config repository, which holds client settings. It returns an error if the repository is not set.

func (*Proxy) GetExtension

func (proxy *Proxy) GetExtension(name string) (*extensions.Runtime, bool)

GetExtension retrieves a loaded extension by its name. It returns the extension and true if found, otherwise nil and false.

func (*Proxy) GetExtensionRepo

func (proxy *Proxy) GetExtensionRepo() (domain.ExtensionRepository, error)

GetExtensionRepo returns the extension repository. It returns an error if the repository is not set.

func (*Proxy) GetIntercept

func (proxy *Proxy) GetIntercept() bool

GetIntercept reports whether global HTTP Checkpoint is enabled.

func (*Proxy) GetLaunch

func (proxy *Proxy) GetLaunch(id uuid.UUID) (domain.Launch, error)

GetLaunch returns a launch by id. A launch is read from the registry until its final state is stored, then from the finished launches kept in memory (see maxFinishedLaunches), whichever project is open, and after that from its stored pair's metadata in the open project, so a launch id stays valid for good. It returns domain.ErrLaunchNotFound when the id is none of these.

func (*Proxy) GetLaunchpadRepo

func (proxy *Proxy) GetLaunchpadRepo() (domain.LaunchpadRepository, error)

GetLaunchpadRepo returns the launchpad repository.

func (*Proxy) GetListener

func (proxy *Proxy) GetListener(address string, port string) (net.Listener, error)

GetListener binds address:port and wraps the socket with WrapListener.

func (*Proxy) GetPendingWebSocketInterceptions

func (proxy *Proxy) GetPendingWebSocketInterceptions() []domain.WebSocketMessage

GetPendingWebSocketInterceptions returns snapshots of paused WebSocket messages.

func (*Proxy) GetReportingRepo

func (proxy *Proxy) GetReportingRepo() (domain.ReportingRepository, error)

GetReportingRepo returns the reporting repository. It returns an error if the repository is not set.

func (*Proxy) GetScope

func (proxy *Proxy) GetScope() (*compass.Scope, error)

GetScope returns the current scope configuration. It returns an error if the scope is not set.

func (*Proxy) GetStatsRepo

func (proxy *Proxy) GetStatsRepo() (domain.StatsRepository, error)

GetStatsRepo returns the stats repository, which holds the dashboard counts. It returns an error if the repository is not set.

func (*Proxy) GetStreamIntercept

func (proxy *Proxy) GetStreamIntercept() bool

GetStreamIntercept reports whether every stream message is held.

func (*Proxy) GetTrafficRepo

func (proxy *Proxy) GetTrafficRepo() (domain.TrafficRepository, error)

GetTrafficRepo returns the traffic repository. It returns an error if the repository is not set.

func (*Proxy) GetWaypointRepo

func (proxy *Proxy) GetWaypointRepo() (domain.WaypointRepository, error)

GetWaypointRepo returns the waypoint repository.

func (*Proxy) GetWebSocketConnection

func (proxy *Proxy) GetWebSocketConnection(requestID uuid.UUID) (domain.WebSocketConnection, bool)

GetWebSocketConnection returns live connection state for an upgrade request ID.

func (*Proxy) GetWebSocketIntercept

func (proxy *Proxy) GetWebSocketIntercept() bool

GetWebSocketIntercept reports whether global WebSocket interception is enabled.

func (*Proxy) GetWebSocketMessages

func (proxy *Proxy) GetWebSocketMessages(requestID uuid.UUID) ([]*domain.WebSocketMessage, error)

GetWebSocketMessages returns persisted messages for an upgrade request ID.

func (*Proxy) GetWordlistManager

func (proxy *Proxy) GetWordlistManager() (wordlist.Provider, error)

GetWordlistManager returns the proxy's wordlist provider. It returns an error if the provider is not set.

func (*Proxy) HasPendingCheckpoint

func (proxy *Proxy) HasPendingCheckpoint() bool

HasPendingCheckpoint reports whether any HTTP, WebSocket or stream Checkpoint item is pending.

func (*Proxy) InjectStreamMessage

func (proxy *Proxy) InjectStreamMessage(ctx context.Context, pairID uuid.UUID, direction string, payload []byte, options StreamInjectOptions) (domain.StreamMessage, error)

InjectStreamMessage puts a new stream message with payload into direction (request or response) of the streamed pair pairID, and returns it as it was stored. payload is the message without its envelope; for server-sent events and NDJSON it goes out as given, so it should end as their messages do. A hook or Checkpoint may drop it: it is returned with dropped metadata and not sent. Waiting for the direction's turn ends with ctx.

func (*Proxy) InjectStreamText

func (proxy *Proxy) InjectStreamText(ctx context.Context, pairID uuid.UUID, direction, text string, options StreamInjectOptions) (domain.StreamMessage, error)

InjectStreamText is InjectStreamMessage with the payload given in its text form, encoded with the codec the direction's head names (stream.FromText). Text that cannot be encoded is refused with ErrStreamText, naming the line and column of a syntax error, and nothing is sent.

func (*Proxy) InjectWebSocketMessage

func (proxy *Proxy) InjectWebSocketMessage(
	requestID uuid.UUID,
	direction string,
	opcode int,
	payload []byte,
	options marasiws.InjectOptions,
) (domain.WebSocketMessage, error)

InjectWebSocketMessage injects a message into a live connection. direction must be client or server. With permessage-deflate the message is compressed by the leg's compressor unless options.NeverCompress is set.

func (*Proxy) InterruptLaunches

func (proxy *Proxy) InterruptLaunches()

InterruptLaunches ends every pending launch as failed with reason interrupted, because the open project is being switched or the service is stopping. It cancels each launch and returns once all of them have ended, so their outcomes are written to the project they were launched in, and once any Checkpoint hold of theirs has ended, so a held launch does not leave the project busy.

A launch already cancelled stays cancelled, and one that already reached a terminal state keeps it. Both are still waited for.

func (*Proxy) JoinedRequest

func (proxy *Proxy) JoinedRequest(id uuid.UUID) (JoinedRequest, error)

JoinedRequest returns pair id's request with a streamed request direction's messages joined into its body, each in its envelope, as a client sends them:

  • A message is joined as it was forwarded, after hooks and Checkpoint: an edited message as edited, an injected one included. A dropped, too large or cut short message, or one that could not be decoded, never reached the origin whole and is left out.
  • A message the proxy stored decompressed is compressed again with its recorded encoding (gzip or deflate), its compressed flag kept; one stored as the compressed bytes, an encoding Marasi does not decode, is joined as stored. The compressed bytes can differ from the original's; the decoded payload is the same.
  • An HTTP/1.1 head loses Transfer-Encoding and gets a Content-Length of the joined body; an HTTP/2 head keeps its fields, and a content-length it has is set to the joined body's length.

A pair whose request direction is still being carried is refused with ErrStreamedRequestOpen; once the request direction ended, the pair joins even while its response is live. A pair that is not stored returns an error wrapping domain.ErrPairNotFound.

func (*Proxy) Launch

func (proxy *Proxy) Launch(raw string, launchpadID string, useHttps bool) (uuid.UUID, error)

Launch sends a raw HTTP request from a launchpad through the proxy's own listener, as bytes on a new connection, so its header case, order and whitespace reach the origin as typed. Only the Content-Length value is recalculated. It returns the launch id once the launch is accepted. The launch id is the UUID of the request/response pair the launch creates.

Malformed raw requests and a missing Host fail at once and create no launch. A normal HTTP launch completes once its response is drained. A WebSocket launch completes at the handshake, and the client body stays open until the peer closes, CloseWebSocket is used, or the proxy shuts down.

func (*Proxy) LaunchSync

func (proxy *Proxy) LaunchSync(ctx context.Context, raw string, launchpadID string, useHttps bool) (domain.Launch, error)

LaunchSync starts a launch like Launch and waits for it to reach a terminal state, then returns the final launch. When ctx is cancelled first, it cancels the launch and returns it once it has ended.

Errors from starting the launch are returned at once, as from Launch.

func (*Proxy) Launches

func (proxy *Proxy) Launches() []domain.Launch

Launches returns the pending launches, oldest first.

func (*Proxy) Listen

func (proxy *Proxy) Listen(address string, port string) (net.Listener, error)

Listen binds the TCP socket a proxy listener serves from.

func (*Proxy) MoveLaunchpadEntries

func (proxy *Proxy) MoveLaunchpadEntries(move domain.LaunchpadMove) ([]uuid.UUID, error)

MoveLaunchpadEntries moves entries to a new place, as domain.LaunchpadRepository's MoveLaunchpadEntries does, and returns the moved pair ids in their new entry order. Clients call this method rather than the repository method. A pending launch's pair can be reordered within its launchpad, but not moved to another one (docs/adr/2026-10-18-a-pending-launchs-pair-stays-in-its-launchpad.md): then it moves nothing and returns a *domain.LaunchPendingError naming the pending launches' pairs. It holds launchMu across the check and the move, as the guards in launchpad_pending.go do.

func (*Proxy) OpenJoinedSSEResponse

func (proxy *Proxy) OpenJoinedSSEResponse(id uuid.UUID) (*JoinedSSEResponse, error)

OpenJoinedSSEResponse validates that pair id has an ended SSE response in the open project and returns a JoinedSSEResponse that streams the stored status line, headers, blank line, and forwarded decoded SSE events in order.

While the SSE response direction is live (or before its deferred response capture is queued), OpenJoinedSSEResponse returns ErrStreamedResponseOpen. A pair without a stored SSE response returns ErrResponseNotSSE. A missing pair wraps domain.ErrPairNotFound, and an unavailable project returns ErrExtensionRepoNotFound.

func (*Proxy) ResolveWebSocketInterception

func (proxy *Proxy) ResolveWebSocketInterception(
	messageID uuid.UUID,
	decision marasiws.InterceptionDecision,
) error

ResolveWebSocketInterception applies a decision to a paused WebSocket message.

func (*Proxy) SelectUpstreamProxy

func (proxy *Proxy) SelectUpstreamProxy(name string)

SelectUpstreamProxy makes name the upstream proxy new connections to the origin go through, or a direct connection when name is "". It dials nothing. A name missing from this machine's list fails every request closed until it is added or the selection changes.

func (*Proxy) SendArmoryRequest

func (proxy *Proxy) SendArmoryRequest(ctx context.Context, raw string, runID uuid.UUID, useHTTPS bool) error

SendArmoryRequest sends a rendered Armory request raw through the proxy's own listener, on a connection of its own, as a launch is sent. It returns once the response has been read. Cancelling ctx abandons the request.

func (*Proxy) Serve

func (proxy *Proxy) Serve(activeListener net.Listener) error

Serve starts the proxy and begins accepting connections on the provided listener. It also starts the database writer goroutine.

func (*Proxy) SetIntercept

func (proxy *Proxy) SetIntercept(enabled bool)

SetIntercept enables or disables global HTTP Checkpoint.

func (*Proxy) SetProjectResources

func (proxy *Proxy) SetProjectResources(resources ProjectResources)

SetProjectResources replaces every project-owned dependency. Callers must block project work before calling it. Pending launches are interrupted first, so their outcomes are written to the project they were launched in.

func (*Proxy) SetStreamIntercept

func (proxy *Proxy) SetStreamIntercept(enabled bool)

SetStreamIntercept enables or disables holding every stream message.

func (*Proxy) SetUpgradeHandler

func (proxy *Proxy) SetUpgradeHandler(handler UpgradeHandler)

SetUpgradeHandler registers the handler that every switched pair is handed to.

func (*Proxy) SetWebSocketIntercept

func (proxy *Proxy) SetWebSocketIntercept(enabled bool)

SetWebSocketIntercept enables or disables global WebSocket message interception.

func (*Proxy) SyncWaypoints

func (proxy *Proxy) SyncWaypoints() error

SyncWaypoints reloads waypoints and publishes them as the live routing snapshot.

func (*Proxy) UnlinkRequestFromLaunchpad

func (proxy *Proxy) UnlinkRequestFromLaunchpad(requestID, launchpadID uuid.UUID) error

UnlinkRequestFromLaunchpad removes a pair from a launchpad, as domain.LaunchpadRepository's UnlinkRequestFromLaunchpad does, unless the pair is a launch pending from that launchpad. Then it returns a *domain.LaunchPendingError naming the pair.

func (*Proxy) UnlinkTraffic

func (proxy *Proxy) UnlinkTraffic(sel domain.Selection, target domain.LinkTarget) (int, error)

UnlinkTraffic removes the links between every pair in sel and target, as domain.TrafficRepository's UnlinkTraffic does. When target is a launchpad and sel holds the pair of a launch pending from that launchpad, it changes nothing and returns a *domain.LaunchPendingError naming those pairs.

func (*Proxy) UpstreamProxyStatus

func (proxy *Proxy) UpstreamProxyStatus() UpstreamProxyStatus

UpstreamProxyStatus returns the selection and whether it is configured.

func (*Proxy) WithOptions

func (proxy *Proxy) WithOptions(options ...func(*Proxy) error) error

WithOptions applies a series of configuration functions to the proxy instance. Each option function can modify the proxy configuration and return an error if it fails.

Parameters:

  • options: Variadic list of configuration functions

Returns:

  • error: First error encountered from any option function

func (*Proxy) WrapListener

func (proxy *Proxy) WrapListener(rawListener net.Listener) net.Listener

WrapListener makes rawListener, a bound TCP socket, the proxy listener: it stacks the listener wrappers and points proxy.Client at its address. The socket may come from Listen or from another process.

func (*Proxy) WriteLog

func (proxy *Proxy) WriteLog(level string, message string, options ...func(log *domain.Log) error) error

WriteLog creates a new log entry and sends it to the DBWriteChannel. It accepts a level, a message, and optional functions to modify the log entry.

func (*Proxy) WriteToDB

func (proxy *Proxy) WriteToDB()

WriteToDB reads from the DBWriteChannel and writes items to their respective repositories. It handles proxy traffic, websocket traffic, and log items. Once the channel has been empty for dbWriterIdleDelay, it refreshes the traffic repository's planner statistics.

type RepositoryProvider

type RepositoryProvider interface {
	domain.TrafficRepository
	domain.ExtensionRepository
	domain.LaunchpadRepository
	domain.ArmoryRepository
	domain.WaypointRepository
	domain.StatsRepository
	domain.ConfigRepository
	domain.LogRepository
	domain.ReportingRepository
	domain.WebSocketRepository
	domain.StreamRepository
	io.Closer
	// RefreshStatisticsIfDue refreshes the planner statistics when captures
	// have marked them due (docs/adr/2026-10-14-traffic-lists-sort-by-any-ledger-column.md). The database writer calls it when idle.
	RefreshStatisticsIfDue()
}

RepositoryProvider defines the interface for a provider of all data repositories used by the proxy. This allows for easy injection of a database implementation. In the service, the proxy holds it wrapped in a log-publishing repository, so a type assertion to *db.Repository or to a wider interface fails silently there, even though it passes in tests that use a bare *db.Repository. Add the method here instead.

type Route

type Route struct {
	// Name is the upstream proxy's name. It is empty for a direct route.
	Name string
	// Scheme is the upstream proxy's scheme. It is empty for a direct route
	// and for one that fails closed before reaching any upstream proxy.
	Scheme UpstreamProxyScheme
	// Host and Port are the upstream proxy's address.
	Host string
	Port int
	// contains filtered or unexported fields
}

Route says how the transport reaches the origin for a new connection. The proxy holds the current route behind an atomic pointer, and every connection the transport opens carries the route that opened it. A swap installs a new *Route, so a connection belongs to the current route only when it carries that same pointer. The route resolver (route_resolver.go) builds routes, and Route.dial (route_dial.go) applies them.

func DirectRoute

func DirectRoute() *Route

DirectRoute returns a route that connects to the origin directly.

func (*Route) Address

func (route *Route) Address() string

Address returns scheme://host:port of the upstream proxy without credentials, or "" when the route reaches no upstream proxy.

func (*Route) Direct

func (route *Route) Direct() bool

Direct reports whether the route connects to the origin directly.

func (*Route) Snapshot

func (route *Route) Snapshot() domain.RouteSnapshot

Snapshot returns the route as a pair records it: the name and the address without credentials, both empty for a direct route.

type StreamInjectOptions

type StreamInjectOptions struct {
	// NeverCompress sends the message uncompressed even when the direction
	// compresses its messages. Otherwise a message of a framing with
	// per-message compression is compressed with the direction's encoding
	// when the proxy encodes it (gzip, deflate).
	NeverCompress bool
}

StreamInjectOptions controls how an injected stream message goes out.

type UpdatesConfig

type UpdatesConfig struct {
	// Channel is update.Release or update.Nightly. Empty means the channel
	// of the installed build.
	Channel update.Channel `mapstructure:"channel"`
	// AutoCheck turns automatic update checks on or off. Unset means on.
	AutoCheck *bool `mapstructure:"auto_check"`
}

UpdatesConfig is how the installed build looks for updates.

func (UpdatesConfig) AutoCheckEnabled

func (u UpdatesConfig) AutoCheckEnabled() bool

AutoCheckEnabled reports whether automatic update checks are on.

type UpgradeHandler

type UpgradeHandler func(proxy *Proxy, pair *Pair, client, upstream io.ReadWriteCloser) error

UpgradeHandler takes over a pair whose origin switched protocols. The proxy calls it after the response chain has run and captured the pair, once it has written the 101 to the client. The handler owns both connections and closes them before it returns.

type UpstreamProxyAddress

type UpstreamProxyAddress struct {
	Scheme         UpstreamProxyScheme
	Host           string
	Port           int
	HasCredentials bool
}

UpstreamProxyAddress is an entry's URL without its credentials.

func ParseUpstreamProxyURL

func ParseUpstreamProxyURL(raw string) (*url.URL, UpstreamProxyAddress, error)

ParseUpstreamProxyURL parses an upstream proxy URL: scheme http, https or socks5, optional user:pass@, a host and a port, and nothing else. The returned URL keeps the credentials.

type UpstreamProxyCheck

type UpstreamProxyCheck struct {
	// Name is the upstream proxy checked.
	Name string
	// Address is its scheme://host:port, or "" when the entry has none.
	Address string
	// Target is the host:port the check connected to.
	Target string
	// Outcome is how the check went.
	Outcome UpstreamProxyCheckOutcome
	// Message says what happened in words.
	Message string
}

UpstreamProxyCheck is the result of one test connection through an upstream proxy. It never holds credentials.

type UpstreamProxyCheckOutcome

type UpstreamProxyCheckOutcome string

UpstreamProxyCheckOutcome is how a check went: UpstreamProxyCheckOK, or the UpstreamProxyFailure that stopped it (see checkOutcome).

const UpstreamProxyCheckOK UpstreamProxyCheckOutcome = "ok"

UpstreamProxyCheckOK is the outcome of a check that reached the target.

type UpstreamProxyConfig

type UpstreamProxyConfig struct {
	// Name matches the client-name pattern.
	Name string `mapstructure:"name" yaml:"name"`
	// URL is scheme://[user[:pass]@]host:port.
	URL string `mapstructure:"url" yaml:"url"`
	// CA is an extra trusted CA certificate as PEM, copied in when added.
	// Empty means none.
	CA string `mapstructure:"ca" yaml:"ca,omitempty"`
}

UpstreamProxyConfig is one entry of the upstream_proxies section of marasi_config.yaml (docs/adr/2026-10-23-upstream-proxies-are-listed-per-machine-and-selected-per-project.md).

type UpstreamProxyError

type UpstreamProxyError struct {
	// Name is the selected upstream proxy's name.
	Name string
	// Address is scheme://host:port, or "" when the entry has none.
	Address string
	// Failure classifies the cause.
	Failure UpstreamProxyFailure
	// Detail says what went wrong in words. It holds no credentials.
	Detail string
	// Err is the underlying error, if any. It is not part of Error's text.
	Err error
}

UpstreamProxyError is a route's failure to carry a connection. Its text names the upstream proxy by name and redacted address and never holds credentials, because it is the body of the proxy error response the client gets and is written to the proxy log.

func (*UpstreamProxyError) Error

func (e *UpstreamProxyError) Error() string

func (*UpstreamProxyError) Unwrap

func (e *UpstreamProxyError) Unwrap() error

type UpstreamProxyFailure

type UpstreamProxyFailure string

UpstreamProxyFailure classifies why a route could not carry a connection.

const (
	// UpstreamProxyNotConfigured: the selected name is not in this
	// machine's list.
	UpstreamProxyNotConfigured UpstreamProxyFailure = "not_configured"
	// UpstreamProxyInvalid: the entry, or marasi_config.yaml, cannot be used.
	UpstreamProxyInvalid UpstreamProxyFailure = "invalid"
	// UpstreamProxyRefused: the upstream proxy refused the connection.
	UpstreamProxyRefused UpstreamProxyFailure = "refused"
	// UpstreamProxyAuthRejected: the upstream proxy rejected the credentials,
	// or asked for some when none are set.
	UpstreamProxyAuthRejected UpstreamProxyFailure = "auth_rejected"
	// UpstreamProxyTLSVerification: a certificate did not verify.
	UpstreamProxyTLSVerification UpstreamProxyFailure = "tls_verification"
	// UpstreamProxyTimeout: the upstream proxy did not answer in time.
	UpstreamProxyTimeout UpstreamProxyFailure = "timeout"
	// UpstreamProxyRejected: the upstream proxy would not open the tunnel
	// for another reason, such as an unreachable target.
	UpstreamProxyRejected UpstreamProxyFailure = "rejected"
	// UpstreamProxyFailed: any other failure.
	UpstreamProxyFailed UpstreamProxyFailure = "failed"
)

type UpstreamProxyScheme

type UpstreamProxyScheme string

UpstreamProxyScheme is a scheme an upstream proxy URL can use.

const (
	UpstreamProxyHTTP   UpstreamProxyScheme = "http"
	UpstreamProxyHTTPS  UpstreamProxyScheme = "https"
	UpstreamProxySOCKS5 UpstreamProxyScheme = "socks5"
)

type UpstreamProxyStatus

type UpstreamProxyStatus struct {
	// Name is the selected upstream proxy, or "" for none.
	Name string
	// Configured reports whether Name is in this machine's list. It is true
	// when nothing is selected.
	Configured bool
}

UpstreamProxyStatus is the open project's upstream proxy selection.

type UpstreamProxyUpdate

type UpstreamProxyUpdate struct {
	URL *string
	CA  *string
}

UpstreamProxyUpdate changes an entry. A nil field is left as it is, and an empty CA removes the CA.

type Waypoint

type Waypoint struct {
	Hostname string // The hostname to match
	Override string // The destination to redirect to
}

Waypoint represents a hostname override mapping, allowing requests to specific hosts to be redirected to different destinations.

Directories

Path Synopsis
Package armory manages reusable request templates and their concurrent runs.
Package armory manages reusable request templates and their concurrent runs.
Package chrome handles launching Chrome to be used with the Marasi proxy
Package chrome handles launching Chrome to be used with the Marasi proxy
cmd
marasi command
Command marasi starts and stops named proxy instances and inspects captured HTTP traffic through a Unix-socket control API.
Command marasi starts and stops named proxy instances and inspects captured HTTP traffic through a Unix-socket control API.
Package core provides fundamental utilities for the Marasi proxy, including context management for passing data through the request/response lifecycle.
Package core provides fundamental utilities for the Marasi proxy, including context management for passing data through the request/response lifecycle.
Package cvss reads CVSS 3.1 base vectors and works out their base score, as the FIRST CVSS v3.1 specification defines it.
Package cvss reads CVSS 3.1 base vectors and works out their base score, as the FIRST CVSS v3.1 specification defines it.
db
Package db provides the database layer for the Marasi application.
Package db provides the database layer for the Marasi application.
Package domain defines the core business logic and data structures of the Marasi application.
Package domain defines the core business logic and data structures of the Marasi application.
Package extensions provides a sandboxed Lua scripting environment for extending the functionality of the proxy.
Package extensions provides a sandboxed Lua scripting environment for extending the functionality of the proxy.
internal
conformance
Package conformance scores how much Marasi changes the traffic between a client and an origin.
Package conformance scores how much Marasi changes the traffic between a client and an origin.
conformance/autobahn
Package autobahn is the conformance harness's WebSocket suite: the Autobahn testsuite in Docker, run against Autobahn's strict testee and the harness's lenient echo peer, in both fuzzing modes.
Package autobahn is the conformance harness's WebSocket suite: the Autobahn testsuite in Docker, run against Autobahn's strict testee and the harness's lenient echo peer, in both fuzzing modes.
conformance/cmd/conformance command
Command conformance runs the conformance suites through Marasi and scores each against its committed direct baseline and deviations file.
Command conformance runs the conformance suites through Marasi and scores each against its committed direct baseline and deviations file.
conformance/connectclient
Package connectclient is the conformance harness's connect-client suite.
Package connectclient is the conformance harness's connect-client suite.
conformance/connectclient/cmd/connectclient-wrapper command
Command connectclient-wrapper is the client under test the connect-client suite gives the connectrpc/conformance runner.
Command connectclient-wrapper is the client under test the connect-client suite gives the connectrpc/conformance runner.
conformance/grpcclient
Package grpcclient is the conformance harness's gRPC client-leg suite.
Package grpcclient is the conformance harness's gRPC client-leg suite.
conformance/h1
Package h1 is the conformance harness's HTTP/1.1 recording: each connection's messages as they were on the wire, parsed from the raw bytes in each direction, and the comparison of two recordings that leaves out hop-by-hop fields and framing.
Package h1 is the conformance harness's HTTP/1.1 recording: each connection's messages as they were on the wire, parsed from the raw bytes in each direction, and the comparison of two recordings that leaves out hop-by-hop fields and framing.
conformance/h1client
Package h1client is the conformance harness's HTTP/1.1 client-leg suite.
Package h1client is the conformance harness's HTTP/1.1 client-leg suite.
conformance/h1origin
Package h1origin is the conformance harness's HTTP/1.1 origin-leg suite.
Package h1origin is the conformance harness's HTTP/1.1 origin-leg suite.
conformance/h2
Package h2 is the conformance harness's HTTP/2 recording: what one side of each connection received, decoded to stream meaning, and the comparison of two recordings.
Package h2 is the conformance harness's HTTP/2 recording: what one side of each connection received, decoded to stream meaning, and the comparison of two recordings.
conformance/h2client
Package h2client is the conformance harness's HTTP/2 client-leg suite.
Package h2client is the conformance harness's HTTP/2 client-leg suite.
conformance/h2origin
Package h2origin is the conformance harness's HTTP/2 origin-leg suite.
Package h2origin is the conformance harness's HTTP/2 origin-leg suite.
conformance/nginx
Package nginx runs the reference target of the client-leg suites: nginx pinned by digest, in a container on the host's network, with fixed locations and, for TLS, a certificate from the harness CA.
Package nginx runs the reference target of the client-leg suites: nginx pinned by digest, in a container on the host's network, with fixed locations and, for TLS, a certificate from the harness CA.
conformance/shim
Package shim is the conformance shim: the harness component a third-party tester connects to when it has no proxy option.
Package shim is the conformance shim: the harness component a third-party tester connects to when it has no proxy option.
conformance/streamorigin
Package streamorigin is the conformance harness's stream origin-leg suite: our own origin fixtures for streamed pairs, scored against the direct baseline like h2-origin.
Package streamorigin is the conformance harness's stream origin-leg suite: our own origin fixtures for streamed pairs, scored against the direct baseline like h2-origin.
contentcoding
Package contentcoding reads a message's content codings and undoes them.
Package contentcoding reads a message's content codings and undoes them.
filelock
Package filelock provides nonblocking exclusive locks on open files.
Package filelock provides nonblocking exclusive locks on open files.
h1
Package h1 is Marasi's HTTP/1.1 codec.
Package h1 is Marasi's HTTP/1.1 codec.
ledgerbench
Package ledgerbench holds the harness for the ledger benchmarks: the measurement policy, the run environment record, and project cloning.
Package ledgerbench holds the harness for the ledger benchmarks: the measurement policy, the run environment record, and project cloning.
ledgerbench/cmd/ledgerfixture command
Command ledgerfixture builds the reference project for the ledger benchmarks.
Command ledgerfixture builds the reference project for the ledger benchmarks.
ledgerbench/fixture
Package fixture builds the reference project the ledger benchmarks run against: a .marasi project of request/response pairs whose shape follows a real engagement (see the ledger-redesign-support spec, ticket 01).
Package fixture builds the reference project the ledger benchmarks run against: a .marasi project of request/response pairs whose shape follows a real engagement (see the ledger-redesign-support spec, ticket 01).
repolint
Package repolint holds no code of its own.
Package repolint holds no code of its own.
stagedfile
Package stagedfile publishes a file from a stream so that readers of its directory never see it partly written and a racing writer never replaces it.
Package stagedfile publishes a file from a stream so that readers of its directory never see it partly written and a racing writer never replaces it.
update
Package update finds, verifies, and installs updates of the installed build (GLOSSARY "Updates").
Package update finds, verifies, and installs updates of the installed build (GLOSSARY "Updates").
upstreamtest
Package upstreamtest provides fake upstream proxies for tests.
Package upstreamtest provides fake upstream proxies for tests.
Package protoscope is Marasi's codec between protobuf's wire format and a text form compatible with Google's protoscope language, without a schema.
Package protoscope is Marasi's codec between protobuf's wire format and a text form compatible with Google's protoscope language, without a schema.
Package report provides template-based generation of assessment reports.
Package report provides template-based generation of assessment reports.
Package service is the HTTP control API for a running Marasi instance.
Package service is the HTTP control API for a running Marasi instance.
Package skills holds the agent skill files shipped with Marasi.
Package skills holds the agent skill files shipped with Marasi.
Package stream cuts a streamed pair's body into stream messages (GLOSSARY: Streamed pair, Stream message, Message framing).
Package stream cuts a streamed pair's body into stream messages (GLOSSARY: Streamed pair, Stream message, Message framing).
Package websocket implements WebSocket framing, connection relay, and interception helpers used by the Marasi proxy.
Package websocket implements WebSocket framing, connection relay, and interception helpers used by the Marasi proxy.
Package wordlist discovers and streams wordlist files stored in a managed directory.
Package wordlist discovers and streams wordlist files stored in a managed directory.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL