core

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Feb 17, 2026 License: GPL-3.0 Imports: 31 Imported by: 0

Documentation

Index

Constants

View Source
const (
	MaxBodyPrintSize = 1024 * 10 // Max size if truncation is enabled
	LogLevelDisabled = "disabled"
)

Constants

View Source
const (
	ColorReset   = "\033[0m"
	ColorRed     = "\033[31m"
	ColorGreen   = "\033[32m"
	ColorYellow  = "\033[33m"
	ColorBlue    = "\033[34m"
	ColorMagenta = "\033[35m"
	ColorCyan    = "\033[36m"
	ColorWhite   = "\033[37m"
	ColorGray    = "\033[90m"
	ColorBold    = "\033[1m"
)

ANSI Color Codes

View Source
const Version = "dev"

Variables

View Source
var GlobalVar = &GlobalVarStore{
	sysConfig:         nil,
	config_ids:        make([]string, 0),
	id_to_config:      make(map[string]*ProxyConfig),
	id_to_proxyserver: make(map[string]*http.Server),
}

GlobalVar is the shared instance of the configuration store.

View Source
var HeadersToOmit = map[string]struct{}{
	"x-forwarded-proto": {},
	"cf-ipcountry":      {},
	"cf-ray":            {},
	"x-real-ip":         {},
	"cf-visitor":        {},
	"cf-connecting-ip":  {},
	"cdn-loop":          {},
	"x-forwarded-for":   {},
}

Configuration for Header Omission during Logging

Functions

func CopyFile

func CopyFile(src, dst string) error

CopyFile copies a file from src to dst

func CountSessionsByMethod

func CountSessionsByMethod(db *gorm.DB) (map[string]int64, error)

func DefaultDbPath

func DefaultDbPath() string

func DeleteBookmark

func DeleteBookmark(db *gorm.DB, bookmarkID string) error

DeleteBookmark deletes a bookmark by ID

func DeleteOldSessions

func DeleteOldSessions(db *gorm.DB, olderThan time.Duration) (int64, error)

func ExportCurrentProxiesToConfig

func ExportCurrentProxiesToConfig() error

ExportCurrentProxiesToConfig surgically updates the current config file with active proxies

func FinishProxySession

func FinishProxySession(db *gorm.DB, session *ProxySessionRow, entry *LogEntry) error

FinishProxySession updates an existing proxy session with response data

func FormatSessionStub

func FormatSessionStub(session *ProxySessionRow) map[string]any

func GetAllSystemSettings

func GetAllSystemSettings(db *gorm.DB) (map[string]string, error)

GetAllSystemSettings retrieves all settings as a map

func GetAverageDurationByPath

func GetAverageDurationByPath(db *gorm.DB) (map[string]float64, error)

func GetCurrentDBSize

func GetCurrentDBSize(dbPath string) (int64, error)

func GetFileSize

func GetFileSize(path string) (int64, error)

GetFileSize returns the size of the file at the given path in bytes

func GetSystemSetting

func GetSystemSetting(db *gorm.DB, key string, defaultVal string) string

GetSystemSetting retrieves a setting from the database, or returns the default value if not found

func InitDatabase

func InitDatabase(dbPath string) (*gorm.DB, error)

initDatabase initializes the database with migrations

func IsDev

func IsDev() bool

func IsSessionBookmarked

func IsSessionBookmarked(db *gorm.DB, sessionID string) (bool, string, error)

IsSessionBookmarked checks if a session has been bookmarked

func NewProxyHandler

func NewProxyHandler(config *ProxyConfig) http.HandlerFunc

NewProxyHandler creates a new HTTP handler for proxying requests

func RegisterConfiguration

func RegisterConfiguration(db *gorm.DB, proxyEntry SysConfigProxyEntry) (string, error)

RegisterConfiguration handles the registration of current configuration with the database Returns the configuration ID that can be used to link proxy sessions

func SetSystemSetting

func SetSystemSetting(db *gorm.DB, key string, value string) error

SetSystemSetting persists a setting to the database

func StartProxyServer

func StartProxyServer(
	index int,
	proxyEntry SysConfigProxyEntry,
	db *gorm.DB,
	wsPublishFn func(topic string, v any),
)

StartProxyServer creates and starts a proxy server from a SysConfigProxyEntry

func StopProxyServer

func StopProxyServer(configID string) error

StopProxyServer stops a running proxy server by config ID

Types

type GlobalVarStore

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

GlobalVarStore manages the active configuration IDs in a thread-safe manner.

func (*GlobalVarStore) AddProxyConfig

func (g *GlobalVarStore) AddProxyConfig(id string, config *ProxyConfig)

AddProxyConfig adds or updates a ProxyConfig in the map.

func (*GlobalVarStore) AddProxyServer

func (g *GlobalVarStore) AddProxyServer(id string, server *http.Server)

AddProxyServer adds or updates an http.Server in the map.

func (*GlobalVarStore) ClearProxyConfigs

func (g *GlobalVarStore) ClearProxyConfigs()

ClearProxyConfigs removes all ProxyConfigs from the map.

func (*GlobalVarStore) ClearProxyServers

func (g *GlobalVarStore) ClearProxyServers()

ClearProxyServers removes all http.Servers from the map.

func (*GlobalVarStore) ConfigAdd

func (g *GlobalVarStore) ConfigAdd(id string)

ConfigAdd appends a new ID to the active list if it doesn't already exist (upsert behavior).

func (*GlobalVarStore) ConfigClear

func (g *GlobalVarStore) ConfigClear()

ConfigClear empties the configuration ID list.

func (*GlobalVarStore) ConfigGetAll

func (g *GlobalVarStore) ConfigGetAll() []string

ConfigGetAll returns a copy of all stored configuration IDs.

func (*GlobalVarStore) ConfigSet

func (g *GlobalVarStore) ConfigSet(id string)

ConfigSet replaces all existing IDs with a single new ID.

func (*GlobalVarStore) GetAPIAddr

func (g *GlobalVarStore) GetAPIAddr() string

GetAPIAddr returns the API address from system config.

func (*GlobalVarStore) GetAllProxyConfigs

func (g *GlobalVarStore) GetAllProxyConfigs() map[string]*ProxyConfig

GetAllProxyConfigs returns a copy of all ProxyConfigs as a map.

func (*GlobalVarStore) GetAllProxyServers

func (g *GlobalVarStore) GetAllProxyServers() map[string]*http.Server

GetAllProxyServers returns a copy of all http.Servers as a map.

func (*GlobalVarStore) GetDBPath

func (g *GlobalVarStore) GetDBPath() string

GetDBPath returns the database path from system config.

func (*GlobalVarStore) GetLogDest

func (g *GlobalVarStore) GetLogDest() string

GetLogDest returns the log destination from system config.

func (*GlobalVarStore) GetLogLevel

func (g *GlobalVarStore) GetLogLevel() string

GetLogLevel returns the log level from system config.

func (*GlobalVarStore) GetProxies

func (g *GlobalVarStore) GetProxies() []SysConfigProxyEntry

GetProxies returns a copy of all proxy entries from system config.

func (*GlobalVarStore) GetProxyConfig

func (g *GlobalVarStore) GetProxyConfig(id string) *ProxyConfig

GetProxyConfig retrieves a ProxyConfig by ID. Returns nil if not found.

func (*GlobalVarStore) GetProxyServer

func (g *GlobalVarStore) GetProxyServer(id string) *http.Server

GetProxyServer retrieves an http.Server by ID. Returns nil if not found.

func (*GlobalVarStore) GetSysConfig

func (g *GlobalVarStore) GetSysConfig() *SysConfig

GetSysConfig returns a pointer to the stored system configuration.

func (*GlobalVarStore) HasProxyConfig

func (g *GlobalVarStore) HasProxyConfig(id string) bool

HasProxyConfig checks if a ProxyConfig exists for the given ID.

func (*GlobalVarStore) HasProxyServer

func (g *GlobalVarStore) HasProxyServer(id string) bool

HasProxyServer checks if an http.Server exists for the given ID.

func (*GlobalVarStore) RemoveProxyConfig

func (g *GlobalVarStore) RemoveProxyConfig(id string) bool

RemoveProxyConfig deletes a ProxyConfig by ID. Returns true if found and deleted.

func (*GlobalVarStore) RemoveProxyServer

func (g *GlobalVarStore) RemoveProxyServer(id string) bool

RemoveProxyServer deletes an http.Server by ID. Returns true if found and deleted.

func (*GlobalVarStore) SetSysConfig

func (g *GlobalVarStore) SetSysConfig(cfg *SysConfig)

SetSysConfig stores the system configuration.

type LogEntry

type LogEntry struct {
	ConfigID        string
	Timestamp       time.Time
	ClientAddr      string
	RequestMethod   string
	RequestURL      *url.URL
	RequestProto    string
	RequestHost     string
	RequestHeaders  http.Header
	RequestBody     []byte
	StatusCode      int
	ResponseHeaders http.Header
	ResponseBody    []byte
	Duration        time.Duration
}

LogEntry represents a complete HTTP request/response cycle

type MaxSessionRowsReaper

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

MaxSessionRowsReaper manages the background deletion of old sessions

func NewMaxSessionRowsReaper

func NewMaxSessionRowsReaper(db *gorm.DB, publish func(topic string, v any)) *MaxSessionRowsReaper

NewMaxSessionRowsReaper creates a new MaxSessionRowsReaper instance

func (*MaxSessionRowsReaper) Start

func (r *MaxSessionRowsReaper) Start(interval time.Duration)

Start runs the reaper loop

type ProxyBookmark

type ProxyBookmark struct {
	ID        string    `gorm:"primaryKey;type:text"`
	SessionID string    `gorm:"index"`
	CreatedAt time.Time `gorm:"autoCreateTime"`

	Note string
	Tags string

	// Full copy of ProxySessionRow fields
	Timestamp               time.Time `gorm:"index"`
	DurationMs              int64
	ClientAddr              string
	ClientIP                string
	RequestMethod           string `gorm:"index"`
	RequestPath             string `gorm:"index"`
	RequestQuery            string
	RequestProto            string
	RequestHost             string
	RequestURLFull          string
	RequestHeaders          datatypes.JSON `gorm:"type:text"`
	QueryParameters         datatypes.JSON `gorm:"type:text"`
	RequestBody             []byte         `gorm:"type:blob"`
	RequestBodySize         int
	RequestContentType      string
	RequestContentEncoding  string
	ResponseStatusCode      int `gorm:"index"`
	ResponseStatusText      string
	ResponseHeaders         datatypes.JSON `gorm:"type:text"`
	ResponseBody            []byte         `gorm:"type:blob"`
	ResponseBodySize        int
	ResponseContentType     string
	ResponseContentEncoding string
	ConfigID                string `gorm:"index"`

	// Full copy of ProxyConfigRow fields (relevant ones)
	ConfigSourcePath string
	ConfigJSON       string
}

ProxyBookmark represents a saved session bookmark

func CreateBookmark

func CreateBookmark(db *gorm.DB, sessionID string) (*ProxyBookmark, error)

CreateBookmark creates a new bookmark from an existing session

func GetBookmark

func GetBookmark(db *gorm.DB, bookmarkID string) (*ProxyBookmark, error)

GetBookmark retrieves a single bookmark by ID

func GetBookmarks

func GetBookmarks(db *gorm.DB, configID string, query string, limit int, offset int) ([]ProxyBookmark, int64, error)

GetBookmarks retrieves bookmarks, optionally filtering by query (FTS)

func UpdateBookmarkMetadata

func UpdateBookmarkMetadata(db *gorm.DB, bookmarkID string, note string, tags string) (*ProxyBookmark, error)

UpdateBookmarkMetadata updates the note and tags for a bookmark

func (*ProxyBookmark) BeforeCreate

func (b *ProxyBookmark) BeforeCreate(tx *gorm.DB) (err error)

BeforeCreate is a GORM hook to generate bookmark ID

func (ProxyBookmark) TableName

func (ProxyBookmark) TableName() string

TableName overrides default table name

type ProxyConfig

type ProxyConfig struct {
	ConfigID        string
	ListenAddr      string
	TargetURL       *url.URL
	TruncateLogBody bool
	DB              *gorm.DB
	HeadersToOmit   map[string]struct{}
	WsPublishFn     func(topic string, v any)
}

ProxyConfig holds the configuration for the proxy handler

func SetupProxyConfig

func SetupProxyConfig(
	configID string,
	listenAddr string,
	targetURL *url.URL,
	db *gorm.DB,
	truncateLogBody bool,
	wsPublishFn func(topic string, v any),
) *ProxyConfig

SetupProxyConfig creates a ProxyConfig from viper settings

type ProxyConfigRow

type ProxyConfigRow struct {
	ID        string    `gorm:"primaryKey;type:text"`
	CreatedAt time.Time `gorm:"not null;default:CURRENT_TIMESTAMP"`

	// Where the config was loaded from (e.g., /path/to/file or "shell")
	SourcePath string `gorm:"not null"`

	// The directory where the proxy was executed
	Cwd string `gorm:"not null"`

	// The full configuration content in JSON format
	ConfigJSON string `gorm:"not null"`

	// A unique hash of (SourcePath + Cwd + ConfigJSON) for fast lookup
	Fingerprint string `gorm:"uniqueIndex;not null"`

	// Relationship: One config row can have many sessions
	Sessions []ProxySessionRow `gorm:"foreignKey:ConfigID"`
}

ProxyConfigRow represents the database record for a specific environment and settings.

func GetConfigRowByID

func GetConfigRowByID(db *gorm.DB, id string) (*ProxyConfigRow, error)

GetConfigRowByID retrieves a specific configuration row by its NanoID.

func GetOrCreateConfigRow

func GetOrCreateConfigRow(db *gorm.DB, sourcePath, cwd, configJSON string) (*ProxyConfigRow, error)

GetOrCreateConfigRow ensures the current environment is registered in the DB. It checks the fingerprint first; if missing, it creates a new row with a NanoID.

func (ProxyConfigRow) TableName

func (ProxyConfigRow) TableName() string

TableName overrides the default tablename to proxy_configs

type ProxySessionRow

type ProxySessionRow struct {
	ID        string    `gorm:"primaryKey;type:text"`
	ConfigID  string    `gorm:"index"` // References ProxyConfig.ID
	CreatedAt time.Time `gorm:"index:idx_sessions_created_at"`

	// Timing information
	Timestamp  time.Time `gorm:"not null;index:idx_sessions_timestamp"`
	DurationMs int64     `gorm:"not null;index:idx_sessions_duration"` // Duration in milliseconds

	// Client information
	ClientAddr string `gorm:"not null"`
	ClientIP   string `gorm:"index:idx_sessions_client_ip"` // Extracted IP without port

	// Request information
	RequestMethod  string `gorm:"not null;index:idx_sessions_method_path"`
	RequestPath    string `gorm:"not null;index:idx_sessions_method_path"`
	RequestQuery   string // Raw query string
	RequestProto   string `gorm:"not null"`
	RequestHost    string `gorm:"not null"`
	RequestURLFull string `gorm:"not null"` // Complete URL for reference

	// Request headers and query params as JSON
	RequestHeaders  datatypes.JSON `gorm:"type:text"` // Stored as JSON
	QueryParameters datatypes.JSON `gorm:"type:text"` // Stored as JSON

	// Request body
	RequestBody            []byte `gorm:"type:blob"`
	RequestBodySize        int    `gorm:"default:0"`
	RequestContentType     string
	RequestContentEncoding string

	// Response information
	ResponseStatusCode int `gorm:"not null;index:idx_sessions_status_code"` // response_status_code = 0 for pending responses
	ResponseStatusText string

	// Response headers as JSON
	ResponseHeaders datatypes.JSON `gorm:"type:text"` // Stored as JSON

	// Response body
	ResponseBody            []byte `gorm:"type:blob"`
	ResponseBodySize        int    `gorm:"default:0"`
	ResponseContentType     string
	ResponseContentEncoding string
}

ProxySessionRow represents a complete HTTP request/response cycle

func CreateProxySession

func CreateProxySession(db *gorm.DB, entry *LogEntry) (*ProxySessionRow, error)

CreateProxySession inserts a new proxy session with all data

func GetErrorSessions

func GetErrorSessions(db *gorm.DB, configID string, limit int, offset int) ([]ProxySessionRow, error)

GetErrorSessions retrieves sessions with error status codes for a specific config

func GetRecentSessions

func GetRecentSessions(db *gorm.DB, configID string, limit int, offset int, since time.Time) ([]ProxySessionRow, error)

GetRecentSessions retrieves the most recent sessions for a specific config

func GetSessionByID

func GetSessionByID(db *gorm.DB, sessionID string) (*ProxySessionRow, error)

GetSessionByID retrieves a single session by ID

func GetSessionsByHeaderValue

func GetSessionsByHeaderValue(db *gorm.DB, configID string, headerName, value string, limit int, offset int) ([]ProxySessionRow, error)

GetSessionsByHeaderValue retrieves sessions where a header contains specific value for a config

func GetSessionsByMethod

func GetSessionsByMethod(db *gorm.DB, configID string, method string, limit int, offset int) ([]ProxySessionRow, error)

GetSessionsByMethod retrieves sessions by HTTP method and config

func GetSessionsByPath

func GetSessionsByPath(db *gorm.DB, configID string, path string, limit int, offset int) ([]ProxySessionRow, error)

GetSessionsByPath retrieves sessions for a specific endpoint and config

func GetSessionsWithHeader

func GetSessionsWithHeader(db *gorm.DB, configID string, headerName string, limit int, offset int) ([]ProxySessionRow, error)

GetSessionsWithHeader retrieves sessions that have a specific request header for a config

func GetSessionsWithQueryParam

func GetSessionsWithQueryParam(db *gorm.DB, configID string, paramName string, limit int, offset int) ([]ProxySessionRow, error)

GetSessionsWithQueryParam retrieves sessions with a specific query parameter for a config

func GetSlowSessions

func GetSlowSessions(db *gorm.DB, configID string, minDurationMs int64, limit int, offset int) ([]ProxySessionRow, error)

GetSlowSessions retrieves sessions that exceeded duration for a specific config

func SearchSessions

func SearchSessions(db *gorm.DB, configID string, searchText string, limit int, offset int) ([]ProxySessionRow, error)

SearchSessions performs a full-text search using FTS5

func StartProxySession

func StartProxySession(db *gorm.DB, entry *LogEntry) (*ProxySessionRow, error)

StartProxySession inserts a new proxy session with initial request data

func (*ProxySessionRow) BeforeCreate

func (s *ProxySessionRow) BeforeCreate(tx *gorm.DB) (err error)

BeforeCreate is a GORM hook that runs before inserting into the DB

func (*ProxySessionRow) ParseQueryParameters

func (s *ProxySessionRow) ParseQueryParameters() (url.Values, error)

func (*ProxySessionRow) ParseRequestHeaders

func (s *ProxySessionRow) ParseRequestHeaders() (http.Header, error)

func (*ProxySessionRow) ParseResponseHeaders

func (s *ProxySessionRow) ParseResponseHeaders() (http.Header, error)

func (ProxySessionRow) TableName

func (ProxySessionRow) TableName() string

TableName overrides the default tablename

type ProxySessionStub

type ProxySessionStub struct {
	ID                 string
	ConfigID           string
	ResponseStatusCode int
	RequestMethod      string
	RequestPath        string
	Timestamp          time.Time
	DurationMs         int64
	Note               string
	Tags               string
}

type SysConfig

type SysConfig struct {
	LogLevel          string                `mapstructure:"log-level" json:"log_level" toml:"log-level"`
	LogDest           string                `mapstructure:"log-dest" json:"log_dest" toml:"log-dest"`
	DBPath            string                `mapstructure:"db-path" json:"db_path" toml:"db-path"`
	InMemory          bool                  `mapstructure:"in-memory" json:"in_memory" toml:"in-memory"`
	APIAddr           string                `mapstructure:"api-addr" json:"api_addr" toml:"api-addr"`
	MaxSessionsRetain int                   `mapstructure:"max-sessions-retain" json:"max_sessions_retain" toml:"max-sessions-retain"`
	Proxies           []SysConfigProxyEntry `mapstructure:"proxies" json:"proxies" toml:"proxies"`
}

Config represents the top-level configuration structure

type SysConfigProxyEntry

type SysConfigProxyEntry struct {
	Listen          string `mapstructure:"listen" json:"listen" toml:"listen"`
	Target          string `mapstructure:"target" json:"target" toml:"target"`
	TruncateLogBody bool   `mapstructure:"truncate-log-body" json:"truncate_log_body" toml:"truncate-log-body"`
}

ProxyEntry represents a single proxy configuration

type SystemSettingRow

type SystemSettingRow struct {
	Key       string    `gorm:"primaryKey"`
	Value     string    `gorm:"not null"`
	UpdatedAt time.Time `gorm:"autoUpdateTime"`
}

SystemSettingRow represents a persistent system configuration setting

func (SystemSettingRow) TableName

func (SystemSettingRow) TableName() string

TableName overrides the default tablename

Jump to

Keyboard shortcuts

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