Compare commits
5 Commits
2aee0765aa
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 8dfb14f1e7 | |||
| 9edea27148 | |||
| c9304ea1cf | |||
| 9efc2b0494 | |||
| 1a4bc76a2c |
10
AGENTS.md
10
AGENTS.md
@@ -11,7 +11,7 @@ Conduit is a self-hosted tunneling service (Go, single binary). A **server** (`c
|
|||||||
make build_local
|
make build_local
|
||||||
|
|
||||||
# Run tests
|
# Run tests
|
||||||
make tests # includes coverage
|
make tests # includes race detection + coverage
|
||||||
|
|
||||||
# Lint
|
# Lint
|
||||||
golangci-lint run
|
golangci-lint run
|
||||||
@@ -30,8 +30,8 @@ tunnel/tcp_forwarder.go — Direct net.Dial TCP forwarding
|
|||||||
tunnel/stream.go — Stream interface (io.ReadWriteCloser + Source/Target)
|
tunnel/stream.go — Stream interface (io.ReadWriteCloser + Source/Target)
|
||||||
server/reconstructed_conn.go — Replays re-serialized headers + buffered body + raw conn after hijack
|
server/reconstructed_conn.go — Replays re-serialized headers + buffered body + raw conn after hijack
|
||||||
store/store.go — In-memory request/response recorder with pub/sub (SSE)
|
store/store.go — In-memory request/response recorder with pub/sub (SSE)
|
||||||
web/web.go — Local tunnel monitor (port 8181), SSE endpoint
|
web/web.go — Local tunnel monitor (port 8181), embedded static UI assets, SSE endpoint
|
||||||
config/config.go — Reflection-based config from struct tags → flags + env vars
|
config/config.go — Reflection-based config from struct tags → flags + env vars + client config file
|
||||||
pkg/maps/map.go — Generic sync.RWMutex-guarded map
|
pkg/maps/map.go — Generic sync.RWMutex-guarded map
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -39,7 +39,7 @@ pkg/maps/map.go — Generic sync.RWMutex-guarded map
|
|||||||
|
|
||||||
- **Go style**: standard `gofmt`, golangci-lint with `.golangci.toml`
|
- **Go style**: standard `gofmt`, golangci-lint with `.golangci.toml`
|
||||||
- **Comment style**: Title Case heading above logical blocks (see root `AGENTS.md`)
|
- **Comment style**: Title Case heading above logical blocks (see root `AGENTS.md`)
|
||||||
- **Config**: add struct tags (`json`, `default`, `description`) to `ServerConfig` or `ClientConfig` — flags and env vars are auto-derived
|
- **Config**: add struct tags (`json`, `default`, `description`) to `ServerConfig` or `ClientConfig` — flags and env vars are auto-derived. Client config may also come from `./conduit.json` or `~/.config/conduit/config.json` for `server`, `api_key`, `log_level`, and `log_format` only.
|
||||||
- **Logging**: use `logrus` (`log` alias); structured fields preferred
|
- **Logging**: use `logrus` (`log` alias); structured fields preferred
|
||||||
- **Concurrency**: use `pkg/maps.Map` for shared maps; protect other shared state with `sync.Mutex`
|
- **Concurrency**: use `pkg/maps.Map` for shared maps; protect other shared state with `sync.Mutex`
|
||||||
- **Error handling**: return errors up; log at command/entry-point level. Use `fmt.Errorf` with `%w` for wrapping
|
- **Error handling**: return errors up; log at command/entry-point level. Use `fmt.Errorf` with `%w` for wrapping
|
||||||
@@ -59,7 +59,7 @@ pkg/maps/map.go — Generic sync.RWMutex-guarded map
|
|||||||
|
|
||||||
## Testing
|
## Testing
|
||||||
|
|
||||||
E2E tests live in `e2e_test.go` at the project root. They spin up real servers, tunnels, and targets on random ports.
|
E2E tests live in `e2e_test.go` at the project root. They spin up real servers, tunnels, and targets on random ports. `make tests` runs with `-race` and coverage enabled.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Run all tests
|
# Run all tests
|
||||||
|
|||||||
2
Makefile
2
Makefile
@@ -30,6 +30,6 @@ clean:
|
|||||||
rm -rf ./build
|
rm -rf ./build
|
||||||
|
|
||||||
tests:
|
tests:
|
||||||
SET_TEST=set_val go test -coverpkg=./... ./... -coverprofile=./cover.out
|
SET_TEST=set_val go test -race -coverpkg=./... ./... -coverprofile=./cover.out
|
||||||
go tool cover -html=./cover.out -o ./cover.html
|
go tool cover -html=./cover.out -o ./cover.html
|
||||||
rm ./cover.out
|
rm ./cover.out
|
||||||
|
|||||||
@@ -85,10 +85,10 @@ conduit tunnel \
|
|||||||
--server https://conduit.example.com \
|
--server https://conduit.example.com \
|
||||||
--api_key your-secret-key \
|
--api_key your-secret-key \
|
||||||
--name my-service \
|
--name my-service \
|
||||||
--target localhost:5432
|
--target tcp://localhost:5432
|
||||||
```
|
```
|
||||||
|
|
||||||
The local tunnel monitor is available at `http://localhost:8181` for HTTP tunnels.
|
Targets must include an explicit `tcp://`, `http://`, or `https://` scheme. The local tunnel monitor is available at `http://localhost:8181` for HTTP tunnels.
|
||||||
|
|
||||||
## Configuration
|
## Configuration
|
||||||
|
|
||||||
@@ -111,7 +111,7 @@ All options can be set via CLI flags or environment variables (`CONDUIT_` prefix
|
|||||||
| `--server` | `CONDUIT_SERVER` | `http://localhost:8080` | Conduit server address |
|
| `--server` | `CONDUIT_SERVER` | `http://localhost:8080` | Conduit server address |
|
||||||
| `--api_key` | `CONDUIT_API_KEY` | — | API key (required) |
|
| `--api_key` | `CONDUIT_API_KEY` | — | API key (required) |
|
||||||
| `--name` | `CONDUIT_NAME` | (auto-generated) | Tunnel subdomain name |
|
| `--name` | `CONDUIT_NAME` | (auto-generated) | Tunnel subdomain name |
|
||||||
| `--target` | `CONDUIT_TARGET` | — | Local target address (required) |
|
| `--target` | `CONDUIT_TARGET` | — | Local target address with `tcp://`, `http://`, or `https://` scheme (required) |
|
||||||
| `--log_level` | `CONDUIT_LOG_LEVEL` | `info` | Log level |
|
| `--log_level` | `CONDUIT_LOG_LEVEL` | `info` | Log level |
|
||||||
| `--log_format` | `CONDUIT_LOG_FORMAT` | `text` | Log format (`text` or `json`) |
|
| `--log_format` | `CONDUIT_LOG_FORMAT` | `text` | Log format (`text` or `json`) |
|
||||||
|
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
var tunnelCmd = &cobra.Command{
|
var tunnelCmd = &cobra.Command{
|
||||||
Use: "tunnel <name> <host:port>",
|
Use: "tunnel --target <scheme://host:port>",
|
||||||
Short: "Create a conduit tunnel",
|
Short: "Create a conduit tunnel",
|
||||||
Run: func(cmd *cobra.Command, args []string) {
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
// Get Client Config
|
// Get Client Config
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
package config
|
package config
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/url"
|
"net/url"
|
||||||
"os"
|
"os"
|
||||||
|
"path/filepath"
|
||||||
"reflect"
|
"reflect"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
@@ -51,7 +53,7 @@ type ServerConfig struct {
|
|||||||
type ClientConfig struct {
|
type ClientConfig struct {
|
||||||
BaseConfig
|
BaseConfig
|
||||||
TunnelName string `json:"name" description:"Tunnel name"`
|
TunnelName string `json:"name" description:"Tunnel name"`
|
||||||
TunnelTarget string `json:"target" description:"Tunnel target address"`
|
TunnelTarget string `json:"target" description:"Tunnel target address (tcp://, http://, or https://)"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *ClientConfig) Validate() error {
|
func (c *ClientConfig) Validate() error {
|
||||||
@@ -69,7 +71,7 @@ func GetServerConfig(cmdFlags *pflag.FlagSet) (*ServerConfig, error) {
|
|||||||
|
|
||||||
cfgValues := make(map[string]string)
|
cfgValues := make(map[string]string)
|
||||||
for _, def := range defs {
|
for _, def := range defs {
|
||||||
cfgValues[def.Key] = getConfigValue(cmdFlags, def)
|
cfgValues[def.Key] = getConfigValue(cmdFlags, nil, def)
|
||||||
}
|
}
|
||||||
|
|
||||||
cfg := &ServerConfig{
|
cfg := &ServerConfig{
|
||||||
@@ -86,9 +88,15 @@ func GetServerConfig(cmdFlags *pflag.FlagSet) (*ServerConfig, error) {
|
|||||||
func GetClientConfig(cmdFlags *pflag.FlagSet) (*ClientConfig, error) {
|
func GetClientConfig(cmdFlags *pflag.FlagSet) (*ClientConfig, error) {
|
||||||
defs := GetConfigDefs[ClientConfig]()
|
defs := GetConfigDefs[ClientConfig]()
|
||||||
|
|
||||||
|
// Load Client Config File
|
||||||
|
fileValues, err := getClientConfigFileValues()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
cfgValues := make(map[string]string)
|
cfgValues := make(map[string]string)
|
||||||
for _, def := range defs {
|
for _, def := range defs {
|
||||||
cfgValues[def.Key] = getConfigValue(cmdFlags, def)
|
cfgValues[def.Key] = getConfigValue(cmdFlags, fileValues, def)
|
||||||
}
|
}
|
||||||
|
|
||||||
cfg := &ClientConfig{
|
cfg := &ClientConfig{
|
||||||
@@ -122,7 +130,33 @@ func getBaseConfig(cfgValues map[string]string) BaseConfig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func getConfigValue(cmdFlags *pflag.FlagSet, def ConfigDef) string {
|
func getClientConfigFileValues() (map[string]string, error) {
|
||||||
|
path, err := findConfigFile()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if path == "" {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load Config File
|
||||||
|
values, err := loadConfigFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Keep Client File Settings Explicit - Tunnel name and target are intentionally
|
||||||
|
// not read from the config file because they should be provided per invocation.
|
||||||
|
clientValues := make(map[string]string)
|
||||||
|
for key, value := range values {
|
||||||
|
if isClientFileConfigKey(key) {
|
||||||
|
clientValues[key] = value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return clientValues, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func getConfigValue(cmdFlags *pflag.FlagSet, fileValues map[string]string, def ConfigDef) string {
|
||||||
// 1. Get Flags First
|
// 1. Get Flags First
|
||||||
if cmdFlags != nil {
|
if cmdFlags != nil {
|
||||||
if val, err := cmdFlags.GetString(def.Key); err == nil && val != "" && val != def.Default {
|
if val, err := cmdFlags.GetString(def.Key); err == nil && val != "" && val != def.Default {
|
||||||
@@ -135,10 +169,65 @@ func getConfigValue(cmdFlags *pflag.FlagSet, def ConfigDef) string {
|
|||||||
return envVal
|
return envVal
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. Defaults Last
|
// 3. Config File Next
|
||||||
|
if fileValues != nil {
|
||||||
|
if val := fileValues[def.Key]; val != "" {
|
||||||
|
return val
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Defaults Last
|
||||||
return def.Default
|
return def.Default
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func findConfigFile() (string, error) {
|
||||||
|
// Check Project Config
|
||||||
|
localPath := "conduit.json"
|
||||||
|
if _, err := os.Stat(localPath); err == nil {
|
||||||
|
return localPath, nil
|
||||||
|
} else if !errors.Is(err, os.ErrNotExist) {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check User Config
|
||||||
|
configDir, err := os.UserConfigDir()
|
||||||
|
if err != nil {
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
userPath := filepath.Join(configDir, "conduit", "config.json")
|
||||||
|
if _, err := os.Stat(userPath); err == nil {
|
||||||
|
return userPath, nil
|
||||||
|
} else if !errors.Is(err, os.ErrNotExist) {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func loadConfigFile(path string) (map[string]string, error) {
|
||||||
|
// Read Config File
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decode Config File
|
||||||
|
values := make(map[string]string)
|
||||||
|
if err := json.Unmarshal(data, &values); err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to parse config file %s: %w", path, err)
|
||||||
|
}
|
||||||
|
return values, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func isClientFileConfigKey(key string) bool {
|
||||||
|
switch key {
|
||||||
|
case "server", "api_key", "log_level", "log_format":
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func processFields(t reflect.Type, defs *[]ConfigDef) {
|
func processFields(t reflect.Type, defs *[]ConfigDef) {
|
||||||
for i := 0; i < t.NumField(); i++ {
|
for i := 0; i < t.NumField(); i++ {
|
||||||
field := t.Field(i)
|
field := t.Field(i)
|
||||||
|
|||||||
144
config/config_test.go
Normal file
144
config/config_test.go
Normal file
@@ -0,0 +1,144 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/spf13/pflag"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestLoadConfigFile(t *testing.T) {
|
||||||
|
path := filepath.Join(t.TempDir(), "config.json")
|
||||||
|
if err := os.WriteFile(path, []byte(`{"server":"https://example.com","api_key":"secret"}`), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load Config File
|
||||||
|
values, err := loadConfigFile(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify Values
|
||||||
|
if values["server"] != "https://example.com" {
|
||||||
|
t.Fatalf("expected server from config file, got %q", values["server"])
|
||||||
|
}
|
||||||
|
if values["api_key"] != "secret" {
|
||||||
|
t.Fatalf("expected api_key from config file, got %q", values["api_key"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFindConfigFile(t *testing.T) {
|
||||||
|
workDir := t.TempDir()
|
||||||
|
configDir := t.TempDir()
|
||||||
|
oldDir, err := os.Getwd()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer func() {
|
||||||
|
if err := os.Chdir(oldDir); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
if err := os.Chdir(workDir); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Setenv("XDG_CONFIG_HOME", configDir)
|
||||||
|
|
||||||
|
// Missing Config File
|
||||||
|
path, err := findConfigFile()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if path != "" {
|
||||||
|
t.Fatalf("expected no config file, got %q", path)
|
||||||
|
}
|
||||||
|
|
||||||
|
// User Config File
|
||||||
|
userPath := filepath.Join(configDir, "conduit", "config.json")
|
||||||
|
if err := os.MkdirAll(filepath.Dir(userPath), 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(userPath, []byte(`{}`), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
path, err = findConfigFile()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if path != userPath {
|
||||||
|
t.Fatalf("expected user config file %q, got %q", userPath, path)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Local Config File Precedence
|
||||||
|
localPath := "conduit.json"
|
||||||
|
if err := os.WriteFile(localPath, []byte(`{}`), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
path, err = findConfigFile()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if path != localPath {
|
||||||
|
t.Fatalf("expected local config file %q, got %q", localPath, path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetConfigValuePriority(t *testing.T) {
|
||||||
|
def := ConfigDef{Key: "server", Env: "CONDUIT_SERVER", Default: "default"}
|
||||||
|
fileValues := map[string]string{"server": "file"}
|
||||||
|
|
||||||
|
// Config File Beats Default
|
||||||
|
if value := getConfigValue(nil, fileValues, def); value != "file" {
|
||||||
|
t.Fatalf("expected file value, got %q", value)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Environment Beats Config File
|
||||||
|
t.Setenv("CONDUIT_SERVER", "env")
|
||||||
|
if value := getConfigValue(nil, fileValues, def); value != "env" {
|
||||||
|
t.Fatalf("expected env value, got %q", value)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Flags Beat Environment
|
||||||
|
flags := pflag.NewFlagSet("test", pflag.ContinueOnError)
|
||||||
|
flags.String("server", "default", "server")
|
||||||
|
if err := flags.Set("server", "flag"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if value := getConfigValue(flags, fileValues, def); value != "flag" {
|
||||||
|
t.Fatalf("expected flag value, got %q", value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetClientConfigFileValuesIgnoresTunnelSettings(t *testing.T) {
|
||||||
|
workDir := t.TempDir()
|
||||||
|
oldDir, err := os.Getwd()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer func() {
|
||||||
|
if err := os.Chdir(oldDir); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
if err := os.Chdir(workDir); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write Local Config File
|
||||||
|
if err := os.WriteFile("conduit.json", []byte(`{"server":"https://example.com","api_key":"secret","name":"saved","target":"localhost:3000"}`), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
values, err := getClientConfigFileValues()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if values["server"] != "https://example.com" {
|
||||||
|
t.Fatalf("expected server from config file, got %q", values["server"])
|
||||||
|
}
|
||||||
|
if values["name"] != "" || values["target"] != "" {
|
||||||
|
t.Fatalf("expected tunnel settings to be ignored, got name=%q target=%q", values["name"], values["target"])
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -666,8 +666,8 @@ func TestTCPTunnelEcho(t *testing.T) {
|
|||||||
serverAddr, stopServer := startConduitServer(t, apiKey)
|
serverAddr, stopServer := startConduitServer(t, apiKey)
|
||||||
defer stopServer()
|
defer stopServer()
|
||||||
|
|
||||||
// Connect TCP Tunnel (bare host:port — the realistic way users would specify it)
|
// Connect TCP Tunnel
|
||||||
stopTunnel := connectTunnel(t, serverAddr, tcpAddr, "tcp-test", apiKey)
|
stopTunnel := connectTunnel(t, serverAddr, fmt.Sprintf("tcp://%s", tcpAddr), "tcp-test", apiKey)
|
||||||
defer stopTunnel()
|
defer stopTunnel()
|
||||||
|
|
||||||
// Send Raw HTTP Request Through Tunnel to TCP Echo
|
// Send Raw HTTP Request Through Tunnel to TCP Echo
|
||||||
@@ -709,8 +709,8 @@ func TestTCPTunnelLargePayload(t *testing.T) {
|
|||||||
serverAddr, stopServer := startConduitServer(t, apiKey)
|
serverAddr, stopServer := startConduitServer(t, apiKey)
|
||||||
defer stopServer()
|
defer stopServer()
|
||||||
|
|
||||||
// Connect TCP Tunnel (bare host:port)
|
// Connect TCP Tunnel
|
||||||
stopTunnel := connectTunnel(t, serverAddr, tcpAddr, "tcp-large", apiKey)
|
stopTunnel := connectTunnel(t, serverAddr, fmt.Sprintf("tcp://%s", tcpAddr), "tcp-large", apiKey)
|
||||||
defer stopTunnel()
|
defer stopTunnel()
|
||||||
|
|
||||||
// Connect and Send Large Payload
|
// Connect and Send Large Payload
|
||||||
|
|||||||
18
go.mod
18
go.mod
@@ -3,12 +3,14 @@ module reichard.io/conduit
|
|||||||
go 1.25.1
|
go 1.25.1
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/google/uuid v1.6.0 // indirect
|
github.com/google/uuid v1.6.0
|
||||||
github.com/gorilla/websocket v1.5.3 // indirect
|
github.com/gorilla/websocket v1.5.3
|
||||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
github.com/sirupsen/logrus v1.9.3
|
||||||
github.com/sirupsen/logrus v1.9.3 // indirect
|
github.com/spf13/cobra v1.10.1
|
||||||
github.com/spf13/cobra v1.10.1 // indirect
|
github.com/spf13/pflag v1.0.9
|
||||||
github.com/spf13/pflag v1.0.9 // indirect
|
)
|
||||||
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 // indirect
|
|
||||||
maragu.dev/gomponents v1.2.0 // indirect
|
require (
|
||||||
|
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||||
|
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 // indirect
|
||||||
)
|
)
|
||||||
|
|||||||
6
go.sum
6
go.sum
@@ -1,5 +1,6 @@
|
|||||||
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
|
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
|
||||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
@@ -7,6 +8,7 @@ github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aN
|
|||||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||||
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||||
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||||
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
|
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
|
||||||
@@ -16,11 +18,11 @@ github.com/spf13/cobra v1.10.1/go.mod h1:7SmJGaTHFVBY0jW4NXGluQoLvhqFQM+6XSKD+P4
|
|||||||
github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY=
|
github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY=
|
||||||
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
|
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
|
||||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 h1:0A+M6Uqn+Eje4kHMK80dtF3JCXC4ykBgQG4Fe06QRhQ=
|
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 h1:0A+M6Uqn+Eje4kHMK80dtF3JCXC4ykBgQG4Fe06QRhQ=
|
||||||
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
maragu.dev/gomponents v1.2.0 h1:H7/N5htz1GCnhu0HB1GasluWeU2rJZOYztVEyN61iTc=
|
|
||||||
maragu.dev/gomponents v1.2.0/go.mod h1:oEDahza2gZoXDoDHhw8jBNgH+3UR5ni7Ur648HORydM=
|
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"sync/atomic"
|
||||||
|
|
||||||
"github.com/gorilla/websocket"
|
"github.com/gorilla/websocket"
|
||||||
log "github.com/sirupsen/logrus"
|
log "github.com/sirupsen/logrus"
|
||||||
@@ -35,6 +35,7 @@ type Server struct {
|
|||||||
|
|
||||||
upgrader websocket.Upgrader
|
upgrader websocket.Upgrader
|
||||||
tunnels *maps.Map[string, *tunnel.Tunnel]
|
tunnels *maps.Map[string, *tunnel.Tunnel]
|
||||||
|
streamID atomic.Uint64
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewServer(ctx context.Context, cfg *config.ServerConfig) (*Server, error) {
|
func NewServer(ctx context.Context, cfg *config.ServerConfig) (*Server, error) {
|
||||||
@@ -145,7 +146,7 @@ func (s *Server) handleTunnelRequest(w http.ResponseWriter, r *http.Request, tun
|
|||||||
reconstructedConn := newReconstructedConn(conn, &reqBuf, bufrw)
|
reconstructedConn := newReconstructedConn(conn, &reqBuf, bufrw)
|
||||||
|
|
||||||
// Create Stream
|
// Create Stream
|
||||||
streamID := fmt.Sprintf("stream_%d", time.Now().UnixNano())
|
streamID := fmt.Sprintf("stream_%d", s.streamID.Add(1))
|
||||||
tunnelStream := tunnel.NewStream(reconstructedConn, r.RemoteAddr, conduitTunnel.Source())
|
tunnelStream := tunnel.NewStream(reconstructedConn, r.RemoteAddr, conduitTunnel.Source())
|
||||||
|
|
||||||
// Add Stream
|
// Add Stream
|
||||||
@@ -156,7 +157,7 @@ func (s *Server) handleTunnelRequest(w http.ResponseWriter, r *http.Request, tun
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Start Stream
|
// Start Stream
|
||||||
conduitTunnel.StartStream(tunnelStream, streamID)
|
conduitTunnel.StartStream(s.ctx, tunnelStream, streamID)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) getInfo(w http.ResponseWriter, _ *http.Request) {
|
func (s *Server) getInfo(w http.ResponseWriter, _ *http.Request) {
|
||||||
|
|||||||
@@ -20,10 +20,18 @@ type TunnelRecord struct {
|
|||||||
RequestHeaders http.Header
|
RequestHeaders http.Header
|
||||||
RequestBodyType string
|
RequestBodyType string
|
||||||
RequestBody []byte
|
RequestBody []byte
|
||||||
|
RequestBodySize int64
|
||||||
|
RequestBodyCaptured bool
|
||||||
|
RequestBodyTruncated bool
|
||||||
|
RequestBodySkipped string
|
||||||
|
|
||||||
ResponseHeaders http.Header
|
ResponseHeaders http.Header
|
||||||
ResponseBodyType string
|
ResponseBodyType string
|
||||||
ResponseBody []byte
|
ResponseBody []byte
|
||||||
|
ResponseBodySize int64
|
||||||
|
ResponseBodyCaptured bool
|
||||||
|
ResponseBodyTruncated bool
|
||||||
|
ResponseBodySkipped string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (tr *TunnelRecord) MarshalJSON() ([]byte, error) {
|
func (tr *TunnelRecord) MarshalJSON() ([]byte, error) {
|
||||||
|
|||||||
118
store/store.go
118
store/store.go
@@ -16,6 +16,7 @@ import (
|
|||||||
const (
|
const (
|
||||||
defaultQueueSize = 100
|
defaultQueueSize = 100
|
||||||
maxQueueSize = 100
|
maxQueueSize = 100
|
||||||
|
maxBodyCapture = 1024 * 1024
|
||||||
)
|
)
|
||||||
|
|
||||||
var ErrRecordNotFound = errors.New("record not found")
|
var ErrRecordNotFound = errors.New("record not found")
|
||||||
@@ -98,11 +99,15 @@ func (s *tunnelStoreImpl) RecordRequest(req *http.Request, sourceAddress string)
|
|||||||
SourceAddr: sourceAddress,
|
SourceAddr: sourceAddress,
|
||||||
RequestHeaders: req.Header,
|
RequestHeaders: req.Header,
|
||||||
RequestBodyType: req.Header.Get("Content-Type"),
|
RequestBodyType: req.Header.Get("Content-Type"),
|
||||||
|
RequestBodySize: req.ContentLength,
|
||||||
}
|
}
|
||||||
|
|
||||||
if bodyData, err := getRequestBody(req); err == nil {
|
bodyData, meta := captureBody(&req.Body, req.Header.Get("Content-Type"), req.ContentLength, false)
|
||||||
rec.RequestBody = bodyData
|
rec.RequestBody = bodyData
|
||||||
}
|
rec.RequestBodySize = meta.size
|
||||||
|
rec.RequestBodyCaptured = meta.captured
|
||||||
|
rec.RequestBodyTruncated = meta.truncated
|
||||||
|
rec.RequestBodySkipped = meta.skipped
|
||||||
|
|
||||||
// Add Record & Truncate
|
// Add Record & Truncate
|
||||||
s.orderedRecords = append(s.orderedRecords, rec)
|
s.orderedRecords = append(s.orderedRecords, rec)
|
||||||
@@ -122,10 +127,14 @@ func (s *tunnelStoreImpl) RecordResponse(resp *http.Response) error {
|
|||||||
rec.Status = resp.StatusCode
|
rec.Status = resp.StatusCode
|
||||||
rec.ResponseHeaders = resp.Header
|
rec.ResponseHeaders = resp.Header
|
||||||
rec.ResponseBodyType = resp.Header.Get("Content-Type")
|
rec.ResponseBodyType = resp.Header.Get("Content-Type")
|
||||||
|
rec.ResponseBodySize = resp.ContentLength
|
||||||
|
|
||||||
if bodyData, err := getResponseBody(resp); err == nil {
|
bodyData, meta := captureBody(&resp.Body, resp.Header.Get("Content-Type"), resp.ContentLength, true)
|
||||||
rec.ResponseBody = bodyData
|
rec.ResponseBody = bodyData
|
||||||
}
|
rec.ResponseBodySize = meta.size
|
||||||
|
rec.ResponseBodyCaptured = meta.captured
|
||||||
|
rec.ResponseBodyTruncated = meta.truncated
|
||||||
|
rec.ResponseBodySkipped = meta.skipped
|
||||||
|
|
||||||
s.broadcast(rec)
|
s.broadcast(rec)
|
||||||
|
|
||||||
@@ -156,44 +165,71 @@ func (s *tunnelStoreImpl) broadcast(record *TunnelRecord) {
|
|||||||
s.subs = active
|
s.subs = active
|
||||||
}
|
}
|
||||||
|
|
||||||
func getRequestBody(req *http.Request) ([]byte, error) {
|
type bodyCaptureMeta struct {
|
||||||
if req.ContentLength == 0 || req.Body == nil || req.Body == http.NoBody {
|
size int64
|
||||||
return nil, nil
|
captured bool
|
||||||
|
truncated bool
|
||||||
|
skipped string
|
||||||
}
|
}
|
||||||
|
|
||||||
if !isTextContentType(req.Header.Get("Content-Type")) {
|
func captureBody(body *io.ReadCloser, contentType string, contentLength int64, allowImages bool) ([]byte, bodyCaptureMeta) {
|
||||||
return nil, nil
|
meta := bodyCaptureMeta{size: contentLength}
|
||||||
|
if contentLength == 0 || *body == nil || *body == http.NoBody {
|
||||||
|
return nil, meta
|
||||||
}
|
}
|
||||||
|
|
||||||
// Read Body
|
previewable := isTextContentType(contentType) || (allowImages && isImageContentType(contentType))
|
||||||
bodyBytes, err := io.ReadAll(req.Body)
|
if !previewable {
|
||||||
|
meta.skipped = "body content type is not previewable"
|
||||||
|
return nil, meta
|
||||||
|
}
|
||||||
|
|
||||||
|
if isImageContentType(contentType) && contentLength > maxBodyCapture {
|
||||||
|
meta.skipped = "image body is too large to preview"
|
||||||
|
return nil, meta
|
||||||
|
}
|
||||||
|
|
||||||
|
// Capture Bounded Prefix
|
||||||
|
originalBody := *body
|
||||||
|
limit := int64(maxBodyCapture + 1)
|
||||||
|
captured, err := io.ReadAll(io.LimitReader(originalBody, limit))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
meta.skipped = "failed to read body"
|
||||||
|
*body = originalBody
|
||||||
|
return nil, meta
|
||||||
|
}
|
||||||
|
|
||||||
|
if meta.size < 0 && len(captured) <= maxBodyCapture {
|
||||||
|
meta.size = int64(len(captured))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Restore Body
|
// Restore Body
|
||||||
req.Body = io.NopCloser(bytes.NewReader(bodyBytes))
|
*body = &replayReadCloser{
|
||||||
return bodyBytes, nil
|
Reader: io.MultiReader(bytes.NewReader(captured), originalBody),
|
||||||
|
closer: originalBody,
|
||||||
}
|
}
|
||||||
|
|
||||||
func getResponseBody(resp *http.Response) ([]byte, error) {
|
if len(captured) > maxBodyCapture {
|
||||||
if resp.ContentLength == 0 || resp.Body == nil || resp.Body == http.NoBody {
|
meta.truncated = true
|
||||||
return nil, nil
|
captured = captured[:maxBodyCapture]
|
||||||
}
|
}
|
||||||
|
|
||||||
if !isTextContentType(resp.Header.Get("Content-Type")) {
|
if isImageContentType(contentType) && meta.truncated {
|
||||||
return nil, nil
|
meta.skipped = "image body is too large to preview"
|
||||||
|
return nil, meta
|
||||||
}
|
}
|
||||||
|
|
||||||
// Read Body
|
meta.captured = len(captured) > 0
|
||||||
bodyBytes, err := io.ReadAll(resp.Body)
|
return captured, meta
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Restore Body
|
type replayReadCloser struct {
|
||||||
resp.Body = io.NopCloser(bytes.NewReader(bodyBytes))
|
io.Reader
|
||||||
return bodyBytes, nil
|
closer io.Closer
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *replayReadCloser) Close() error {
|
||||||
|
return r.closer.Close()
|
||||||
}
|
}
|
||||||
|
|
||||||
func isTextContentType(contentType string) bool {
|
func isTextContentType(contentType string) bool {
|
||||||
@@ -206,14 +242,44 @@ func isTextContentType(contentType string) bool {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if strings.HasSuffix(mediaType, "+json") || strings.HasSuffix(mediaType, "+xml") {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
switch mediaType {
|
switch mediaType {
|
||||||
case "application/json":
|
case "application/json":
|
||||||
return true
|
return true
|
||||||
case "application/xml":
|
case "application/xml":
|
||||||
return true
|
return true
|
||||||
|
case "application/javascript":
|
||||||
|
return true
|
||||||
|
case "application/x-javascript":
|
||||||
|
return true
|
||||||
case "application/x-www-form-urlencoded":
|
case "application/x-www-form-urlencoded":
|
||||||
return true
|
return true
|
||||||
default:
|
default:
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func isImageContentType(contentType string) bool {
|
||||||
|
mediaType, _, err := mime.ParseMediaType(contentType)
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
switch mediaType {
|
||||||
|
case "image/png":
|
||||||
|
return true
|
||||||
|
case "image/jpeg":
|
||||||
|
return true
|
||||||
|
case "image/gif":
|
||||||
|
return true
|
||||||
|
case "image/webp":
|
||||||
|
return true
|
||||||
|
case "image/svg+xml":
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,7 +2,9 @@ package tunnel
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"fmt"
|
||||||
"net/url"
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"reichard.io/conduit/store"
|
"reichard.io/conduit/store"
|
||||||
)
|
)
|
||||||
@@ -21,15 +23,24 @@ type Forwarder interface {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func NewForwarder(target string, tunnelStore store.TunnelStore) (Forwarder, error) {
|
func NewForwarder(target string, tunnelStore store.TunnelStore) (Forwarder, error) {
|
||||||
// Only parse as URL for HTTP targets. Bare host:port (e.g., "127.0.0.1:5432")
|
if !strings.Contains(target, "://") {
|
||||||
// is not a valid URL and should be treated as a raw TCP target.
|
return nil, fmt.Errorf("target must include a scheme: tcp://, http://, or https://")
|
||||||
|
}
|
||||||
|
|
||||||
targetURL, err := url.Parse(target)
|
targetURL, err := url.Parse(target)
|
||||||
if err == nil {
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("target is invalid: %w", err)
|
||||||
|
}
|
||||||
|
if targetURL.Host == "" {
|
||||||
|
return nil, fmt.Errorf("target must include a host")
|
||||||
|
}
|
||||||
|
|
||||||
switch targetURL.Scheme {
|
switch targetURL.Scheme {
|
||||||
case "http", "https":
|
case "http", "https":
|
||||||
return newHTTPForwarder(targetURL, tunnelStore)
|
return newHTTPForwarder(targetURL, tunnelStore)
|
||||||
|
case "tcp":
|
||||||
|
return newTCPForwarder(targetURL.Host, tunnelStore), nil
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("unsupported target scheme %q: use tcp://, http://, or https://", targetURL.Scheme)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return newTCPForwarder(target, tunnelStore), nil
|
|
||||||
}
|
|
||||||
|
|||||||
45
tunnel/forwarder_test.go
Normal file
45
tunnel/forwarder_test.go
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
package tunnel
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"reichard.io/conduit/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestNewForwarderRequiresExplicitScheme(t *testing.T) {
|
||||||
|
_, err := NewForwarder("localhost:8282", store.NewTunnelStore(1))
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error for target without scheme")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNewForwarderSupportsExplicitSchemes(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
target string
|
||||||
|
forwarderType ForwarderType
|
||||||
|
}{
|
||||||
|
{name: "http", target: "http://localhost:8282", forwarderType: ForwarderHTTP},
|
||||||
|
{name: "https", target: "https://localhost:8282", forwarderType: ForwarderHTTP},
|
||||||
|
{name: "tcp", target: "tcp://localhost:8282", forwarderType: ForwarderTCP},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
forwarder, err := NewForwarder(tt.target, store.NewTunnelStore(1))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if forwarder.Type() != tt.forwarderType {
|
||||||
|
t.Fatalf("expected forwarder type %v, got %v", tt.forwarderType, forwarder.Type())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNewForwarderRejectsUnsupportedScheme(t *testing.T) {
|
||||||
|
_, err := NewForwarder("udp://localhost:8282", store.NewTunnelStore(1))
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error for unsupported scheme")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ package tunnel
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"net"
|
||||||
"net/url"
|
"net/url"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
@@ -58,15 +59,31 @@ func NewClientTunnel(cfg *config.ClientConfig, forwarder Forwarder) (*Tunnel, er
|
|||||||
|
|
||||||
return &Tunnel{
|
return &Tunnel{
|
||||||
name: cfg.TunnelName,
|
name: cfg.TunnelName,
|
||||||
|
publicURL: publicTunnelURL(serverURL, cfg.TunnelName),
|
||||||
wsConn: serverConn,
|
wsConn: serverConn,
|
||||||
streams: maps.New[string, Stream](),
|
streams: maps.New[string, Stream](),
|
||||||
forwarder: forwarder,
|
forwarder: forwarder,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func publicTunnelURL(serverURL *url.URL, tunnelName string) string {
|
||||||
|
// Build Public Tunnel URL
|
||||||
|
host := serverURL.Hostname()
|
||||||
|
if host == "" {
|
||||||
|
host = serverURL.Host
|
||||||
|
}
|
||||||
|
|
||||||
|
publicHost := tunnelName + "." + host
|
||||||
|
if port := serverURL.Port(); port != "" {
|
||||||
|
publicHost = net.JoinHostPort(publicHost, port)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (&url.URL{Scheme: serverURL.Scheme, Host: publicHost}).String()
|
||||||
|
}
|
||||||
|
|
||||||
type Tunnel struct {
|
type Tunnel struct {
|
||||||
ctx context.Context
|
|
||||||
name string
|
name string
|
||||||
|
publicURL string
|
||||||
wsConn *websocket.Conn
|
wsConn *websocket.Conn
|
||||||
streams *maps.Map[string, Stream]
|
streams *maps.Map[string, Stream]
|
||||||
forwarder Forwarder
|
forwarder Forwarder
|
||||||
@@ -76,10 +93,11 @@ type Tunnel struct {
|
|||||||
|
|
||||||
func (t *Tunnel) Start(ctx context.Context) {
|
func (t *Tunnel) Start(ctx context.Context) {
|
||||||
log.Infof("initiated tunnel %q with %s", t.name, t.wsConn.RemoteAddr().String())
|
log.Infof("initiated tunnel %q with %s", t.name, t.wsConn.RemoteAddr().String())
|
||||||
|
if t.publicURL != "" {
|
||||||
|
log.Infof("tunnel available at %s", t.publicURL)
|
||||||
|
}
|
||||||
defer log.Infof("closed tunnel %q with %s", t.name, t.wsConn.RemoteAddr().String())
|
defer log.Infof("closed tunnel %q with %s", t.name, t.wsConn.RemoteAddr().String())
|
||||||
|
|
||||||
t.ctx = ctx
|
|
||||||
|
|
||||||
// Start Message Receiver
|
// Start Message Receiver
|
||||||
for {
|
for {
|
||||||
msg, err := t.readWSWithContext(ctx)
|
msg, err := t.readWSWithContext(ctx)
|
||||||
@@ -94,7 +112,7 @@ func (t *Tunnel) Start(ctx context.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Get Stream
|
// Get Stream
|
||||||
stream, err := t.getStream(msg.StreamID, msg.SourceAddr)
|
stream, err := t.getStream(ctx, msg.StreamID, msg.SourceAddr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if msg.Type != types.MessageTypeClose {
|
if msg.Type != types.MessageTypeClose {
|
||||||
log.WithError(err).Errorf("failed to get stream %s", msg.StreamID)
|
log.WithError(err).Errorf("failed to get stream %s", msg.StreamID)
|
||||||
@@ -151,13 +169,13 @@ func (t *Tunnel) Source() string {
|
|||||||
return t.wsConn.RemoteAddr().String()
|
return t.wsConn.RemoteAddr().String()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Tunnel) StartStream(stream Stream, streamID string) error {
|
func (t *Tunnel) StartStream(ctx context.Context, stream Stream, streamID string) error {
|
||||||
// Close Stream
|
// Close Stream
|
||||||
defer t.closeStream(stream, streamID)
|
defer t.closeStream(stream, streamID)
|
||||||
|
|
||||||
// Start Stream
|
// Start Stream
|
||||||
for {
|
for {
|
||||||
data, err := t.readStreamWithContext(t.ctx, stream)
|
data, err := t.readStreamWithContext(ctx, stream)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -179,7 +197,7 @@ func (t *Tunnel) closeStream(stream Stream, streamID string) error {
|
|||||||
return stream.Close()
|
return stream.Close()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Tunnel) getStream(streamID, sourceAddress string) (Stream, error) {
|
func (t *Tunnel) getStream(ctx context.Context, streamID, sourceAddress string) (Stream, error) {
|
||||||
// Check Existing Stream
|
// Check Existing Stream
|
||||||
if stream, found := t.streams.Get(streamID); found {
|
if stream, found := t.streams.Get(streamID); found {
|
||||||
return stream, nil
|
return stream, nil
|
||||||
@@ -198,7 +216,7 @@ func (t *Tunnel) getStream(streamID, sourceAddress string) (Stream, error) {
|
|||||||
if err := t.AddStream(stream, streamID); err != nil {
|
if err := t.AddStream(stream, streamID); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
go t.StartStream(stream, streamID)
|
go t.StartStream(ctx, stream, streamID)
|
||||||
return stream, nil
|
return stream, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,231 +1,17 @@
|
|||||||
package pages
|
package pages
|
||||||
|
|
||||||
import (
|
import _ "embed"
|
||||||
g "maragu.dev/gomponents"
|
|
||||||
h "maragu.dev/gomponents/html"
|
|
||||||
|
|
||||||
_ "embed"
|
//go:embed network.html
|
||||||
)
|
var networkHTML string
|
||||||
|
|
||||||
//go:embed networkScript.js
|
//go:embed networkScript.js
|
||||||
var alpineScript string
|
var networkScript string
|
||||||
|
|
||||||
func NetworkPage() g.Node {
|
func NetworkHTML() string {
|
||||||
return h.Doctype(
|
return networkHTML
|
||||||
h.HTML(
|
|
||||||
h.Head(
|
|
||||||
h.Script(g.Raw(alpineScript)),
|
|
||||||
h.Script(g.Attr("src", "//cdn.tailwindcss.com")),
|
|
||||||
h.Script(g.Attr("src", "//cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js")),
|
|
||||||
),
|
|
||||||
h.Body(
|
|
||||||
h.Div(h.Class("bg-gray-900 text-gray-100"),
|
|
||||||
networkMonitor(),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func networkMonitor() g.Node {
|
func NetworkScript() string {
|
||||||
return h.Div(
|
return networkScript
|
||||||
g.Attr("x-data", "networkMonitor()"),
|
|
||||||
h.Class("h-dvh flex flex-col"),
|
|
||||||
|
|
||||||
// Header
|
|
||||||
h.Div(
|
|
||||||
h.Class("bg-gray-800 border-b border-gray-700 px-4 py-2 flex items-center gap-4"),
|
|
||||||
h.H1(h.Class("text-lg font-semibold"), g.Text("Network")),
|
|
||||||
h.Button(
|
|
||||||
g.Attr("@click", "clear()"),
|
|
||||||
h.Class("px-3 py-1 bg-gray-700 hover:bg-gray-600 rounded text-sm"),
|
|
||||||
g.Text("Clear"),
|
|
||||||
),
|
|
||||||
h.Div(
|
|
||||||
h.Class("ml-auto text-sm text-gray-400"),
|
|
||||||
h.Span(g.Attr("x-text", "requests.length")),
|
|
||||||
g.Text(" requests"),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
|
|
||||||
// Table
|
|
||||||
h.Div(
|
|
||||||
h.Class("flex-1 overflow-auto"),
|
|
||||||
h.Table(
|
|
||||||
h.Class("w-full text-sm"),
|
|
||||||
networkTableHeader(),
|
|
||||||
networkTableBody(),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
|
|
||||||
// Details Panel
|
|
||||||
networkDetailsPanel(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
func networkTableHeader() g.Node {
|
|
||||||
return h.THead(
|
|
||||||
h.Class("bg-gray-800 sticky top-0 border-b border-gray-700"),
|
|
||||||
h.Tr(
|
|
||||||
h.Class("text-left"),
|
|
||||||
h.Th(h.Class("px-4 py-2 font-medium"), g.Text("Name")),
|
|
||||||
h.Th(h.Class("px-4 py-2 font-medium w-20"), g.Text("Method")),
|
|
||||||
h.Th(h.Class("px-4 py-2 font-medium w-20"), g.Text("Status")),
|
|
||||||
h.Th(h.Class("px-4 py-2 font-medium w-32"), g.Text("Type")),
|
|
||||||
h.Th(h.Class("px-4 py-2 font-medium w-32"), g.Text("Time")),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
func networkTableBody() g.Node {
|
|
||||||
return h.TBody(
|
|
||||||
h.Template(
|
|
||||||
g.Attr("x-for", "req in requests"),
|
|
||||||
g.Attr(":key", "req.ID"),
|
|
||||||
h.Tr(
|
|
||||||
g.Attr("@click", "selected = req"),
|
|
||||||
g.Attr(":class", "selected?.ID === req.ID ? 'bg-blue-900' : 'hover:bg-gray-800'"),
|
|
||||||
h.Class("border-b border-gray-800 cursor-pointer"),
|
|
||||||
h.Td(
|
|
||||||
h.Class("px-4 py-2 truncate max-w-md"),
|
|
||||||
g.Attr("x-text", "req.URL?.Path || req.URL"),
|
|
||||||
),
|
|
||||||
h.Td(h.Class("px-4 py-2"), g.Attr("x-text", "req.Method")),
|
|
||||||
h.Td(
|
|
||||||
h.Class("px-4 py-2"),
|
|
||||||
h.Span(
|
|
||||||
g.Attr(":class", "statusColor(req.Status)"),
|
|
||||||
g.Attr("x-text", "req.Status || '-'"),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
h.Td(
|
|
||||||
h.Class("px-4 py-2 text-gray-400"),
|
|
||||||
g.Attr("x-text", "req.ResponseBodyType || '-'"),
|
|
||||||
),
|
|
||||||
h.Td(
|
|
||||||
h.Class("px-4 py-2 text-gray-400"),
|
|
||||||
g.Attr("x-text", "formatTime(req.Time)"),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
func networkDetailsPanel() g.Node {
|
|
||||||
return h.Div(
|
|
||||||
g.Attr("x-show", "selected"),
|
|
||||||
g.Attr("x-data", "{ activeTab: 'general' }"),
|
|
||||||
h.Class("fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"),
|
|
||||||
g.Attr("@click.self", "selected = null"),
|
|
||||||
h.Div(
|
|
||||||
h.Class("bg-gray-800 rounded-lg shadow-xl w-3/4 h-3/4 flex flex-col"),
|
|
||||||
g.Attr("@click.stop", ""),
|
|
||||||
// Header
|
|
||||||
h.Div(
|
|
||||||
h.Class("flex items-center justify-between p-4 border-b border-gray-700"),
|
|
||||||
h.H2(
|
|
||||||
h.Class("text-lg font-semibold"),
|
|
||||||
g.Attr("x-text", "selected?.URL"),
|
|
||||||
),
|
|
||||||
h.Button(
|
|
||||||
g.Attr("@click", "selected = null"),
|
|
||||||
h.Class("text-gray-400 hover:text-gray-200"),
|
|
||||||
g.Text("X"),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
// Tabs
|
|
||||||
h.Div(
|
|
||||||
h.Class("flex border-b border-gray-700"),
|
|
||||||
tab("general", "General"),
|
|
||||||
tab("request", "Request"),
|
|
||||||
tab("response", "Response"),
|
|
||||||
),
|
|
||||||
// Content
|
|
||||||
h.Div(
|
|
||||||
h.Class("flex-1 overflow-auto p-4"),
|
|
||||||
generalTabContent(),
|
|
||||||
requestTabContent(),
|
|
||||||
responseTabContent(),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
func tab(name, label string) g.Node {
|
|
||||||
return h.Button(
|
|
||||||
g.Attr("@click", "activeTab = '"+name+"'"),
|
|
||||||
g.Attr(":class", "activeTab === '"+name+"' ? 'border-b-2 border-blue-500 text-blue-500' : 'text-gray-400 hover:text-gray-200'"),
|
|
||||||
h.Class("px-4 py-2 font-medium"),
|
|
||||||
g.Text(label),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
func generalTabContent() g.Node {
|
|
||||||
return h.Div(
|
|
||||||
g.Attr("x-show", "activeTab === 'general'"),
|
|
||||||
h.Class("space-y-4"),
|
|
||||||
h.H3(h.Class("font-medium"), g.Text("Details")),
|
|
||||||
h.Div(
|
|
||||||
h.Class("text-sm space-y-1 text-gray-300"),
|
|
||||||
detailRow("URL:", "selected?.URL"),
|
|
||||||
detailRow("Source:", "selected?.SourceAddr"),
|
|
||||||
detailRow("Method:", "selected?.Method"),
|
|
||||||
detailRow("Status:", "selected?.Status"),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
func requestTabContent() g.Node {
|
|
||||||
return h.Div(
|
|
||||||
g.Attr("x-show", "activeTab === 'request'"),
|
|
||||||
h.Class("space-y-4"),
|
|
||||||
h.H3(h.Class("font-medium"), g.Text("Headers")),
|
|
||||||
h.Div(
|
|
||||||
h.Class("text-sm space-y-1 text-gray-300 font-mono"),
|
|
||||||
h.Template(
|
|
||||||
g.Attr("x-for", "(values, key) in selected?.RequestHeaders"),
|
|
||||||
h.Div(
|
|
||||||
h.Span(h.Class("text-gray-500"), g.Attr("x-text", "key + ':'")),
|
|
||||||
g.Text(" "),
|
|
||||||
h.Span(g.Attr("x-text", "values.join(', ')")),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
h.H3(h.Class("font-medium"), g.Text("Body")),
|
|
||||||
h.Pre(
|
|
||||||
h.Class("text-sm text-gray-300 font-mono bg-gray-900 p-3 rounded overflow-auto max-h-96"),
|
|
||||||
h.Code(g.Attr("x-text", "formatData(selected?.RequestBody)")),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
func responseTabContent() g.Node {
|
|
||||||
return h.Div(
|
|
||||||
g.Attr("x-show", "activeTab === 'response'"),
|
|
||||||
h.Class("space-y-4"),
|
|
||||||
h.H3(h.Class("font-medium"), g.Text("Headers")),
|
|
||||||
h.Div(
|
|
||||||
h.Class("text-sm space-y-1 text-gray-300 font-mono mb-4"),
|
|
||||||
h.Template(
|
|
||||||
g.Attr("x-for", "(values, key) in selected?.ResponseHeaders"),
|
|
||||||
h.Div(
|
|
||||||
h.Span(h.Class("text-gray-500"), g.Attr("x-text", "key + ':'")),
|
|
||||||
g.Text(" "),
|
|
||||||
h.Span(g.Attr("x-text", "values.join(', ')")),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
h.H3(h.Class("font-medium"), g.Text("Body")),
|
|
||||||
h.Pre(
|
|
||||||
h.Class("text-sm text-gray-300 font-mono bg-gray-900 p-3 rounded overflow-auto max-h-96"),
|
|
||||||
h.Code(g.Attr("x-text", "formatData(selected?.ResponseBody)")),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
func detailRow(label, value string) g.Node {
|
|
||||||
return h.Div(
|
|
||||||
h.Span(h.Class("text-gray-500"), g.Text(label)),
|
|
||||||
g.Text(" "),
|
|
||||||
h.Span(g.Attr("x-text", value)),
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|||||||
13
web/pages/network.html
Normal file
13
web/pages/network.html
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en" class="h-full bg-slate-950">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<title>Conduit Monitor</title>
|
||||||
|
<script src="//cdn.tailwindcss.com"></script>
|
||||||
|
</head>
|
||||||
|
<body class="h-full bg-slate-950 text-slate-100">
|
||||||
|
<main id="app" class="min-h-full"></main>
|
||||||
|
<script src="/assets/network.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -1,47 +1,444 @@
|
|||||||
function networkMonitor() {
|
const state = {
|
||||||
return {
|
|
||||||
requests: [],
|
requests: [],
|
||||||
selected: null,
|
selectedID: null,
|
||||||
|
activeTab: "preview",
|
||||||
|
query: "",
|
||||||
|
streamStatus: "connecting",
|
||||||
|
};
|
||||||
|
|
||||||
init() {
|
const app = document.getElementById("app");
|
||||||
|
|
||||||
|
function init() {
|
||||||
|
render();
|
||||||
|
connectStream();
|
||||||
|
}
|
||||||
|
|
||||||
|
function connectStream() {
|
||||||
const es = new EventSource("/stream");
|
const es = new EventSource("/stream");
|
||||||
es.onmessage = (e) => {
|
|
||||||
const record = JSON.parse(e.data);
|
es.onopen = () => {
|
||||||
const foundIdx = this.requests.findIndex((r) => r.ID === record.ID);
|
state.streamStatus = "connected";
|
||||||
|
render();
|
||||||
|
};
|
||||||
|
|
||||||
|
es.onerror = () => {
|
||||||
|
state.streamStatus = "disconnected";
|
||||||
|
render();
|
||||||
|
};
|
||||||
|
|
||||||
|
es.onmessage = (event) => {
|
||||||
|
const record = JSON.parse(event.data);
|
||||||
|
const foundIdx = state.requests.findIndex((req) => req.ID === record.ID);
|
||||||
|
|
||||||
if (foundIdx >= 0) {
|
if (foundIdx >= 0) {
|
||||||
this.requests[foundIdx] = record;
|
state.requests[foundIdx] = record;
|
||||||
} else {
|
} else {
|
||||||
this.requests.unshift(record);
|
state.requests.unshift(record);
|
||||||
}
|
}
|
||||||
};
|
|
||||||
},
|
|
||||||
|
|
||||||
clear() {
|
render();
|
||||||
this.requests = [];
|
|
||||||
this.selected = null;
|
|
||||||
},
|
|
||||||
|
|
||||||
statusColor(status) {
|
|
||||||
if (!status) return "text-gray-400";
|
|
||||||
if (status < 300) return "text-green-400";
|
|
||||||
if (status < 400) return "text-blue-400";
|
|
||||||
if (status < 500) return "text-yellow-400";
|
|
||||||
return "text-red-400";
|
|
||||||
},
|
|
||||||
|
|
||||||
formatTime(time) {
|
|
||||||
return new Date(time).toLocaleTimeString();
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatData(base64Data) {
|
function render() {
|
||||||
if (!base64Data) return "";
|
const selected = getSelected();
|
||||||
|
|
||||||
|
app.innerHTML = `
|
||||||
|
<section class="flex min-h-dvh flex-col bg-slate-950">
|
||||||
|
${renderHeader()}
|
||||||
|
<div class="grid min-h-0 flex-1 grid-cols-1 overflow-hidden lg:grid-cols-[28rem_minmax(0,1fr)]">
|
||||||
|
${renderRequestList()}
|
||||||
|
${renderInspector(selected, false)}
|
||||||
|
</div>
|
||||||
|
${selected ? renderMobileSheet(selected) : ""}
|
||||||
|
</section>
|
||||||
|
`;
|
||||||
|
|
||||||
|
bindEvents();
|
||||||
|
renderPreview(selected);
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderHeader() {
|
||||||
|
return `
|
||||||
|
<header class="border-b border-slate-800 bg-slate-900/80 px-4 py-3 backdrop-blur">
|
||||||
|
<div class="flex flex-wrap items-center gap-3">
|
||||||
|
<div>
|
||||||
|
<h1 class="text-lg font-semibold tracking-tight">Conduit Monitor</h1>
|
||||||
|
<p class="text-xs text-slate-400">Live tunnel traffic inspector</p>
|
||||||
|
</div>
|
||||||
|
<span class="ml-auto rounded-full px-3 py-1 text-xs font-medium ${streamStatusClass()}">${state.streamStatus}</span>
|
||||||
|
<button data-action="clear" class="rounded-lg border border-slate-700 px-3 py-1.5 text-sm text-slate-200 hover:bg-slate-800">Clear</button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderRequestList() {
|
||||||
|
const filtered = filteredRequests();
|
||||||
|
|
||||||
|
return `
|
||||||
|
<aside class="min-h-0 border-r border-slate-800 bg-slate-950 lg:flex lg:flex-col">
|
||||||
|
<div class="border-b border-slate-800 p-3">
|
||||||
|
<label class="sr-only" for="search">Search requests</label>
|
||||||
|
<input id="search" data-input="query" value="${escapeAttr(state.query)}" placeholder="Search path, method, status, type..." class="w-full rounded-xl border border-slate-800 bg-slate-900 px-3 py-2 text-sm outline-none ring-blue-500 placeholder:text-slate-500 focus:ring-2" />
|
||||||
|
<div class="mt-2 text-xs text-slate-500">${filtered.length} of ${state.requests.length} requests</div>
|
||||||
|
</div>
|
||||||
|
<div class="max-h-[calc(100dvh-9rem)] overflow-auto lg:max-h-none lg:flex-1">
|
||||||
|
${filtered.length === 0 ? renderEmptyList() : filtered.map(renderRequestRow).join("")}
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderRequestRow(req) {
|
||||||
|
const selected = req.ID === state.selectedID;
|
||||||
|
const url = parseURL(req.URL);
|
||||||
|
|
||||||
|
return `
|
||||||
|
<button data-select="${req.ID}" class="block w-full border-b border-slate-900 px-4 py-3 text-left transition ${selected ? "bg-blue-950/70" : "hover:bg-slate-900"}">
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<span class="rounded-md px-2 py-0.5 text-xs font-bold ${methodClass(req.Method)}">${escapeHTML(req.Method || "-")}</span>
|
||||||
|
<span class="rounded-md px-2 py-0.5 text-xs font-semibold ${statusClass(req.Status)}">${req.Status || "pending"}</span>
|
||||||
|
<span class="ml-auto text-xs text-slate-500">${formatTime(req.Time)}</span>
|
||||||
|
</div>
|
||||||
|
<div class="mt-2 truncate font-mono text-sm text-slate-100">${escapeHTML(url.path)}</div>
|
||||||
|
<div class="mt-1 flex items-center gap-2 truncate text-xs text-slate-500">
|
||||||
|
<span class="truncate">${escapeHTML(url.host || req.SourceAddr || "unknown")}</span>
|
||||||
|
<span>•</span>
|
||||||
|
<span class="truncate">${escapeHTML(req.ResponseBodyType || req.RequestBodyType || "no content type")}</span>
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderInspector(selected, mobile) {
|
||||||
|
if (!selected) {
|
||||||
|
return `
|
||||||
|
<section class="hidden min-h-0 items-center justify-center bg-slate-950 p-8 lg:flex">
|
||||||
|
<div class="max-w-md text-center">
|
||||||
|
<div class="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-2xl bg-slate-900 text-2xl">↯</div>
|
||||||
|
<h2 class="text-lg font-semibold">No request selected</h2>
|
||||||
|
<p class="mt-2 text-sm text-slate-400">Send traffic through a tunnel, then select a request to inspect headers, bodies, and previews.</p>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const wrapperClass = mobile ? "flex h-full flex-col bg-slate-950" : "hidden min-h-0 flex-col bg-slate-950 lg:flex";
|
||||||
|
return `
|
||||||
|
<section class="${wrapperClass}">
|
||||||
|
${renderInspectorHeader(selected, mobile)}
|
||||||
|
${renderTabs()}
|
||||||
|
<div class="min-h-0 flex-1 overflow-auto p-4">
|
||||||
|
${renderActiveTab(selected)}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderMobileSheet(selected) {
|
||||||
|
return `
|
||||||
|
<div class="fixed inset-0 z-50 bg-slate-950 lg:hidden">
|
||||||
|
${renderInspector(selected, true)}
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderInspectorHeader(req, mobile) {
|
||||||
|
const url = parseURL(req.URL);
|
||||||
|
|
||||||
|
return `
|
||||||
|
<div class="border-b border-slate-800 p-4">
|
||||||
|
<div class="flex items-start gap-3">
|
||||||
|
${mobile ? `<button data-action="close" class="rounded-lg border border-slate-700 px-3 py-1.5 text-sm">Back</button>` : ""}
|
||||||
|
<div class="min-w-0 flex-1">
|
||||||
|
<div class="flex flex-wrap items-center gap-2">
|
||||||
|
<span class="rounded-md px-2 py-0.5 text-xs font-bold ${methodClass(req.Method)}">${escapeHTML(req.Method || "-")}</span>
|
||||||
|
<span class="rounded-md px-2 py-0.5 text-xs font-semibold ${statusClass(req.Status)}">${req.Status || "pending"}</span>
|
||||||
|
<span class="text-xs text-slate-500">${formatTime(req.Time)}</span>
|
||||||
|
</div>
|
||||||
|
<h2 class="mt-2 truncate font-mono text-base font-semibold">${escapeHTML(url.path)}</h2>
|
||||||
|
<p class="mt-1 truncate text-xs text-slate-500">${escapeHTML(req.URL || "")}</p>
|
||||||
|
</div>
|
||||||
|
<button data-copy="${escapeAttr(req.URL || "")}" class="rounded-lg border border-slate-700 px-3 py-1.5 text-sm hover:bg-slate-800">Copy URL</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderTabs() {
|
||||||
|
return `
|
||||||
|
<nav class="flex gap-1 overflow-x-auto border-b border-slate-800 px-3 py-2">
|
||||||
|
${["preview", "overview", "request", "response"].map((tab) => `
|
||||||
|
<button data-tab="${tab}" class="rounded-lg px-3 py-1.5 text-sm font-medium capitalize ${state.activeTab === tab ? "bg-blue-600 text-white" : "text-slate-400 hover:bg-slate-900 hover:text-slate-100"}">${tab}</button>
|
||||||
|
`).join("")}
|
||||||
|
</nav>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderActiveTab(req) {
|
||||||
|
if (state.activeTab === "overview") return renderOverview(req);
|
||||||
|
if (state.activeTab === "request") return renderMessage(req, "Request");
|
||||||
|
if (state.activeTab === "response") return renderMessage(req, "Response");
|
||||||
|
return `<div data-preview-root></div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderOverview(req) {
|
||||||
|
return `
|
||||||
|
<div class="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
|
||||||
|
${summaryCard("Method", req.Method || "-")}
|
||||||
|
${summaryCard("Status", req.Status || "pending")}
|
||||||
|
${summaryCard("Source", req.SourceAddr || "-")}
|
||||||
|
${summaryCard("Request Body", bodySummary(req, "Request"))}
|
||||||
|
${summaryCard("Response Body", bodySummary(req, "Response"))}
|
||||||
|
${summaryCard("Content Type", req.ResponseBodyType || req.RequestBodyType || "-")}
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderMessage(req, prefix) {
|
||||||
|
const headers = req[`${prefix}Headers`] || {};
|
||||||
|
const body = decodeBody(req[`${prefix}Body`]);
|
||||||
|
|
||||||
|
return `
|
||||||
|
<div class="space-y-4">
|
||||||
|
<section>
|
||||||
|
<div class="mb-2 flex items-center justify-between gap-2">
|
||||||
|
<h3 class="font-semibold">Headers</h3>
|
||||||
|
<button data-copy="${escapeAttr(formatHeaders(headers))}" class="rounded-lg border border-slate-700 px-3 py-1 text-xs hover:bg-slate-800">Copy</button>
|
||||||
|
</div>
|
||||||
|
<pre class="overflow-auto rounded-xl border border-slate-800 bg-slate-900 p-3 text-xs text-slate-300">${escapeHTML(formatHeaders(headers) || "No headers")}</pre>
|
||||||
|
</section>
|
||||||
|
<section>
|
||||||
|
<div class="mb-2 flex items-center justify-between gap-2">
|
||||||
|
<h3 class="font-semibold">Body</h3>
|
||||||
|
<button data-copy="${escapeAttr(body)}" class="rounded-lg border border-slate-700 px-3 py-1 text-xs hover:bg-slate-800">Copy</button>
|
||||||
|
</div>
|
||||||
|
<p class="mb-2 text-xs text-slate-500">${escapeHTML(bodySummary(req, prefix))}</p>
|
||||||
|
<pre class="max-h-[32rem] overflow-auto rounded-xl border border-slate-800 bg-slate-900 p-3 text-xs text-slate-300">${escapeHTML(formatBody(body, req[`${prefix}BodyType`]))}</pre>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderPreview(selected) {
|
||||||
|
const roots = document.querySelectorAll("[data-preview-root]");
|
||||||
|
if (roots.length === 0 || !selected) return;
|
||||||
|
|
||||||
|
roots.forEach((root) => renderPreviewInto(root, selected));
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderPreviewInto(root, selected) {
|
||||||
|
const contentType = selected.ResponseBodyType || "";
|
||||||
|
const body = selected.ResponseBody;
|
||||||
|
|
||||||
|
if (!selected.ResponseBodyCaptured || !body) {
|
||||||
|
root.innerHTML = renderPreviewEmpty(selected);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isImage(contentType)) {
|
||||||
|
root.innerHTML = `<div class="rounded-xl border border-slate-800 bg-slate-900 p-4"><img class="mx-auto max-h-[70dvh] max-w-full rounded-lg" alt="Response preview" src="data:${escapeAttr(contentType)};base64,${body}" /></div>`;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const decoded = decodeBody(body);
|
||||||
|
if (isHTML(contentType)) {
|
||||||
|
root.innerHTML = `<iframe title="Response HTML preview" sandbox class="h-[70dvh] w-full rounded-xl border border-slate-800 bg-white"></iframe>`;
|
||||||
|
root.querySelector("iframe").srcdoc = decoded;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
root.innerHTML = `<pre class="max-h-[70dvh] overflow-auto rounded-xl border border-slate-800 bg-slate-900 p-4 text-sm text-slate-300">${escapeHTML(formatBody(decoded, contentType))}</pre>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderPreviewEmpty(req) {
|
||||||
|
const reason = req.ResponseBodySkipped || "No captured response body is available.";
|
||||||
|
return `
|
||||||
|
<div class="rounded-xl border border-dashed border-slate-700 p-8 text-center">
|
||||||
|
<h3 class="font-semibold">Nothing to preview</h3>
|
||||||
|
<p class="mt-2 text-sm text-slate-400">${escapeHTML(reason)}</p>
|
||||||
|
<p class="mt-1 text-xs text-slate-500">${escapeHTML(bodySummary(req, "Response"))}</p>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function bindEvents() {
|
||||||
|
document.querySelectorAll("[data-select]").forEach((el) => {
|
||||||
|
el.addEventListener("click", () => {
|
||||||
|
state.selectedID = el.dataset.select;
|
||||||
|
state.activeTab = "preview";
|
||||||
|
render();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
document.querySelectorAll("[data-tab]").forEach((el) => {
|
||||||
|
el.addEventListener("click", () => {
|
||||||
|
state.activeTab = el.dataset.tab;
|
||||||
|
render();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
document.querySelectorAll("[data-action='clear']").forEach((el) => {
|
||||||
|
el.addEventListener("click", () => {
|
||||||
|
state.requests = [];
|
||||||
|
state.selectedID = null;
|
||||||
|
render();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
document.querySelectorAll("[data-action='close']").forEach((el) => {
|
||||||
|
el.addEventListener("click", () => {
|
||||||
|
state.selectedID = null;
|
||||||
|
render();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
document.querySelectorAll("[data-copy]").forEach((el) => {
|
||||||
|
el.addEventListener("click", () => navigator.clipboard?.writeText(el.dataset.copy || ""));
|
||||||
|
});
|
||||||
|
|
||||||
|
const search = document.querySelector("[data-input='query']");
|
||||||
|
if (search) {
|
||||||
|
search.addEventListener("input", (event) => {
|
||||||
|
state.query = event.target.value;
|
||||||
|
render();
|
||||||
|
document.querySelector("[data-input='query']")?.focus();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function filteredRequests() {
|
||||||
|
const query = state.query.trim().toLowerCase();
|
||||||
|
if (!query) return state.requests;
|
||||||
|
|
||||||
|
return state.requests.filter((req) => [
|
||||||
|
req.URL,
|
||||||
|
req.Method,
|
||||||
|
String(req.Status || "pending"),
|
||||||
|
req.SourceAddr,
|
||||||
|
req.RequestBodyType,
|
||||||
|
req.ResponseBodyType,
|
||||||
|
].some((value) => String(value || "").toLowerCase().includes(query)));
|
||||||
|
}
|
||||||
|
|
||||||
|
function getSelected() {
|
||||||
|
return state.requests.find((req) => req.ID === state.selectedID) || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseURL(raw) {
|
||||||
try {
|
try {
|
||||||
const decoded = atob(base64Data);
|
const parsed = new URL(raw, window.location.origin);
|
||||||
const parsed = JSON.parse(decoded);
|
return { host: parsed.host, path: `${parsed.pathname}${parsed.search}` || raw };
|
||||||
return JSON.stringify(parsed, null, 2);
|
|
||||||
} catch {
|
} catch {
|
||||||
return atob(base64Data);
|
return { host: "", path: raw || "-" };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function decodeBody(base64Data) {
|
||||||
|
if (!base64Data) return "";
|
||||||
|
const binary = atob(base64Data);
|
||||||
|
const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
|
||||||
|
return new TextDecoder().decode(bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatBody(body, contentType = "") {
|
||||||
|
if (isJSON(contentType)) {
|
||||||
|
try {
|
||||||
|
return JSON.stringify(JSON.parse(body), null, 2);
|
||||||
|
} catch {
|
||||||
|
return body;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return body || "No body";
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatHeaders(headers) {
|
||||||
|
return Object.entries(headers || {})
|
||||||
|
.map(([key, values]) => `${key}: ${Array.isArray(values) ? values.join(", ") : values}`)
|
||||||
|
.join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
function bodySummary(req, prefix) {
|
||||||
|
const size = req[`${prefix}BodySize`];
|
||||||
|
const captured = req[`${prefix}BodyCaptured`];
|
||||||
|
const truncated = req[`${prefix}BodyTruncated`];
|
||||||
|
const skipped = req[`${prefix}BodySkipped`];
|
||||||
|
|
||||||
|
if (captured) return `${formatBytes(size)} captured${truncated ? " (truncated)" : ""}`;
|
||||||
|
if (skipped) return skipped;
|
||||||
|
if (size > 0) return `${formatBytes(size)} not captured`;
|
||||||
|
return "No body";
|
||||||
|
}
|
||||||
|
|
||||||
|
function summaryCard(label, value) {
|
||||||
|
return `<div class="rounded-xl border border-slate-800 bg-slate-900 p-4"><div class="text-xs uppercase tracking-wide text-slate-500">${escapeHTML(label)}</div><div class="mt-1 break-words text-sm font-medium text-slate-100">${escapeHTML(String(value))}</div></div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderEmptyList() {
|
||||||
|
return `<div class="p-8 text-center text-sm text-slate-500">No requests yet. Start sending traffic through your tunnel.</div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isJSON(contentType) {
|
||||||
|
return /(^|\/)json($|;)|\+json($|;)/i.test(contentType || "");
|
||||||
|
}
|
||||||
|
|
||||||
|
function isHTML(contentType) {
|
||||||
|
return /text\/html/i.test(contentType || "");
|
||||||
|
}
|
||||||
|
|
||||||
|
function isImage(contentType) {
|
||||||
|
return /^image\/(png|jpe?g|gif|webp|svg\+xml)/i.test(contentType || "");
|
||||||
|
}
|
||||||
|
|
||||||
|
function methodClass(method) {
|
||||||
|
return {
|
||||||
|
GET: "bg-emerald-500/15 text-emerald-300",
|
||||||
|
POST: "bg-blue-500/15 text-blue-300",
|
||||||
|
PUT: "bg-amber-500/15 text-amber-300",
|
||||||
|
PATCH: "bg-purple-500/15 text-purple-300",
|
||||||
|
DELETE: "bg-red-500/15 text-red-300",
|
||||||
|
}[method] || "bg-slate-700 text-slate-200";
|
||||||
|
}
|
||||||
|
|
||||||
|
function statusClass(status) {
|
||||||
|
if (!status) return "bg-slate-700 text-slate-300";
|
||||||
|
if (status < 300) return "bg-emerald-500/15 text-emerald-300";
|
||||||
|
if (status < 400) return "bg-blue-500/15 text-blue-300";
|
||||||
|
if (status < 500) return "bg-amber-500/15 text-amber-300";
|
||||||
|
return "bg-red-500/15 text-red-300";
|
||||||
|
}
|
||||||
|
|
||||||
|
function streamStatusClass() {
|
||||||
|
if (state.streamStatus === "connected") return "bg-emerald-500/15 text-emerald-300";
|
||||||
|
if (state.streamStatus === "connecting") return "bg-amber-500/15 text-amber-300";
|
||||||
|
return "bg-red-500/15 text-red-300";
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatTime(time) {
|
||||||
|
if (!time) return "-";
|
||||||
|
return new Date(time).toLocaleTimeString();
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatBytes(bytes) {
|
||||||
|
if (!bytes || bytes < 0) return "unknown size";
|
||||||
|
if (bytes < 1024) return `${bytes} B`;
|
||||||
|
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KiB`;
|
||||||
|
return `${(bytes / 1024 / 1024).toFixed(1)} MiB`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function escapeHTML(value) {
|
||||||
|
return String(value ?? "").replace(/[&<>'"]/g, (char) => ({
|
||||||
|
"&": "&",
|
||||||
|
"<": "<",
|
||||||
|
">": ">",
|
||||||
|
"'": "'",
|
||||||
|
'"': """,
|
||||||
|
})[char]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function escapeAttr(value) {
|
||||||
|
return escapeHTML(value).replace(/`/g, "`");
|
||||||
|
}
|
||||||
|
|
||||||
|
init();
|
||||||
|
|||||||
13
web/web.go
13
web/web.go
@@ -26,6 +26,7 @@ func (s *WebServer) Start(ctx context.Context) error {
|
|||||||
|
|
||||||
rootMux := http.NewServeMux()
|
rootMux := http.NewServeMux()
|
||||||
rootMux.HandleFunc("/", s.handleRoot)
|
rootMux.HandleFunc("/", s.handleRoot)
|
||||||
|
rootMux.HandleFunc("/assets/network.js", s.handleNetworkScript)
|
||||||
rootMux.HandleFunc("/stream", s.handleStream)
|
rootMux.HandleFunc("/stream", s.handleStream)
|
||||||
|
|
||||||
s.server = &http.Server{
|
s.server = &http.Server{
|
||||||
@@ -69,6 +70,9 @@ func (s *WebServer) handleStream(w http.ResponseWriter, r *http.Request) {
|
|||||||
ch := s.store.Subscribe()
|
ch := s.store.Subscribe()
|
||||||
done := r.Context().Done()
|
done := r.Context().Done()
|
||||||
|
|
||||||
|
_, _ = fmt.Fprint(w, ": connected\n\n")
|
||||||
|
flusher.Flush()
|
||||||
|
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case record, ok := <-ch:
|
case record, ok := <-ch:
|
||||||
@@ -85,6 +89,11 @@ func (s *WebServer) handleStream(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *WebServer) handleRoot(w http.ResponseWriter, r *http.Request) {
|
func (s *WebServer) handleRoot(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Set("Content-Type", "text/html")
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
_ = pages.NetworkPage().Render(w)
|
_, _ = w.Write([]byte(pages.NetworkHTML()))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *WebServer) handleNetworkScript(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Content-Type", "application/javascript; charset=utf-8")
|
||||||
|
_, _ = w.Write([]byte(pages.NetworkScript()))
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user