From 96d2b88f959d0856236cefa3f16064feda01b894 Mon Sep 17 00:00:00 2001 From: bagas Date: Thu, 1 Jan 2026 21:01:15 +0700 Subject: [PATCH 01/15] WIP: gRPC integration, initial implementation --- internal/grpc/client/client.go | 186 +++++++++++++++++++++++++++++++++ 1 file changed, 186 insertions(+) create mode 100644 internal/grpc/client/client.go diff --git a/internal/grpc/client/client.go b/internal/grpc/client/client.go new file mode 100644 index 0000000..710f023 --- /dev/null +++ b/internal/grpc/client/client.go @@ -0,0 +1,186 @@ +package grpc + +import ( + "context" + "crypto/tls" + "fmt" + "log" + "time" + + "git.fossy.my.id/bagas/tunnel-please-grpc/gen" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/keepalive" +) + +type ClientConfig struct { + Address string + UseTLS bool + InsecureSkipVerify bool + Timeout time.Duration + KeepAlive bool + MaxRetries int +} + +type Client struct { + conn *grpc.ClientConn + config *ClientConfig + IdentityService gen.IdentityClient +} + +func DefaultConfig() *ClientConfig { + return &ClientConfig{ + Address: "localhost:50051", + UseTLS: false, + InsecureSkipVerify: false, + Timeout: 10 * time.Second, + KeepAlive: true, + MaxRetries: 3, + } +} + +func NewClient(config *ClientConfig) (*Client, error) { + if config == nil { + config = DefaultConfig() + } + + var opts []grpc.DialOption + + if config.UseTLS { + tlsConfig := &tls.Config{ + InsecureSkipVerify: config.InsecureSkipVerify, + } + creds := credentials.NewTLS(tlsConfig) + opts = append(opts, grpc.WithTransportCredentials(creds)) + } else { + opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials())) + } + + if config.KeepAlive { + kaParams := keepalive.ClientParameters{ + Time: 10 * time.Second, + Timeout: 3 * time.Second, + PermitWithoutStream: true, + } + opts = append(opts, grpc.WithKeepaliveParams(kaParams)) + } + + opts = append(opts, + grpc.WithDefaultCallOptions( + grpc.MaxCallRecvMsgSize(4*1024*1024), // 4MB + grpc.MaxCallSendMsgSize(4*1024*1024), // 4MB + ), + ) + + conn, err := grpc.NewClient(config.Address, opts...) + if err != nil { + return nil, fmt.Errorf("failed to connect to gRPC server at %s: %w", config.Address, err) + } + + log.Printf("Successfully connected to gRPC server at %s", config.Address) + identityService := gen.NewIdentityClient(conn) + return &Client{ + conn: conn, + config: config, + IdentityService: identityService, + }, nil +} + +func (c *Client) GetConnection() *grpc.ClientConn { + return c.conn +} + +func (c *Client) Close() error { + if c.conn != nil { + log.Printf("Closing gRPC connection to %s", c.config.Address) + return c.conn.Close() + } + return nil +} + +func (c *Client) IsConnected() bool { + if c.conn == nil { + return false + } + state := c.conn.GetState() + return state.String() == "READY" || state.String() == "IDLE" +} + +func (c *Client) Reconnect() error { + if err := c.Close(); err != nil { + log.Printf("Warning: error closing existing connection: %v", err) + } + + var opts []grpc.DialOption + + if c.config.UseTLS { + tlsConfig := &tls.Config{ + InsecureSkipVerify: c.config.InsecureSkipVerify, + } + creds := credentials.NewTLS(tlsConfig) + opts = append(opts, grpc.WithTransportCredentials(creds)) + } else { + opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials())) + } + + if c.config.KeepAlive { + kaParams := keepalive.ClientParameters{ + Time: 10 * time.Second, + Timeout: 3 * time.Second, + PermitWithoutStream: true, + } + opts = append(opts, grpc.WithKeepaliveParams(kaParams)) + } + + opts = append(opts, + grpc.WithDefaultCallOptions( + grpc.MaxCallRecvMsgSize(4*1024*1024), + grpc.MaxCallSendMsgSize(4*1024*1024), + ), + ) + + conn, err := grpc.NewClient(c.config.Address, opts...) + if err != nil { + return fmt.Errorf("failed to reconnect to gRPC server at %s: %w", c.config.Address, err) + } + + c.conn = conn + log.Printf("Successfully reconnected to gRPC server at %s", c.config.Address) + return nil +} + +func (c *Client) WaitForReady(ctx context.Context) error { + if c.conn == nil { + return fmt.Errorf("connection is nil") + } + + _, ok := ctx.Deadline() + if !ok { + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, c.config.Timeout) + defer cancel() + } + + currentState := c.conn.GetState() + for currentState.String() != "READY" { + if !c.conn.WaitForStateChange(ctx, currentState) { + return fmt.Errorf("timeout waiting for connection to be ready") + } + currentState = c.conn.GetState() + + if currentState.String() == "READY" || currentState.String() == "IDLE" { + return nil + } + + if currentState.String() == "SHUTDOWN" || currentState.String() == "TRANSIENT_FAILURE" { + return fmt.Errorf("connection is in %s state", currentState.String()) + } + } + + return nil +} + +func (c *Client) GetConfig() *ClientConfig { + return c.config +} From e1cd4ed9813668e376437a8fcec32f2e299a0363 Mon Sep 17 00:00:00 2001 From: bagas Date: Thu, 1 Jan 2026 21:03:17 +0700 Subject: [PATCH 02/15] WIP: gRPC integration, initial implementation --- go.mod | 13 +- go.sum | 32 ++++- internal/grpc/client/client.go | 193 ++++++++++++++++------------- main.go | 45 ++++++- server/server.go | 15 ++- session/interaction/interaction.go | 40 +++--- 6 files changed, 226 insertions(+), 112 deletions(-) diff --git a/go.mod b/go.mod index 11dbda1..0806c93 100644 --- a/go.mod +++ b/go.mod @@ -1,14 +1,19 @@ module tunnel_pls -go 1.24.4 +go 1.25.5 require ( + git.fossy.my.id/bagas/tunnel-please-grpc v1.0.0 github.com/caddyserver/certmagic v0.25.0 github.com/charmbracelet/bubbles v0.21.0 github.com/charmbracelet/bubbletea v1.3.10 + github.com/charmbracelet/lipgloss v1.1.0 + github.com/golang/protobuf v1.5.4 github.com/joho/godotenv v1.5.1 github.com/libdns/cloudflare v0.2.2 + github.com/muesli/termenv v0.16.0 golang.org/x/crypto v0.46.0 + google.golang.org/grpc v1.78.0 ) require ( @@ -16,7 +21,6 @@ require ( github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect github.com/caddyserver/zerossl v0.1.3 // indirect github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect - github.com/charmbracelet/lipgloss v1.1.0 // indirect github.com/charmbracelet/x/ansi v0.10.1 // indirect github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd // indirect github.com/charmbracelet/x/term v0.2.1 // indirect @@ -31,7 +35,6 @@ require ( github.com/miekg/dns v1.1.68 // indirect github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect github.com/muesli/cancelreader v0.2.2 // indirect - github.com/muesli/termenv v0.16.0 // indirect github.com/rivo/uniseg v0.4.7 // indirect github.com/sahilm/fuzzy v0.1.1 // indirect github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect @@ -45,4 +48,8 @@ require ( golang.org/x/sys v0.39.0 // indirect golang.org/x/text v0.32.0 // indirect golang.org/x/tools v0.39.0 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20251029180050-ab9386a59fda // indirect + google.golang.org/protobuf v1.36.11 // indirect ) + +replace git.fossy.my.id/bagas/tunnel-please-grpc => ../tunnel-please-grpc diff --git a/go.sum b/go.sum index 98717ab..84a22e0 100644 --- a/go.sum +++ b/go.sum @@ -28,8 +28,16 @@ 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/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4= github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM= -github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= -github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= +github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= +github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +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/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= @@ -75,6 +83,18 @@ github.com/zeebo/blake3 v0.2.4 h1:KYQPkhpRtcqh0ssGYcKLG1JYvddkEA8QwCM/yBqhaZI= github.com/zeebo/blake3 v0.2.4/go.mod h1:7eeQ6d2iXWRGF6npfaxl2CU+xy2Fjo2gxeyZGCRUjcE= github.com/zeebo/pcg v1.0.1 h1:lyqfGeWiv4ahac6ttHs+I5hwtH/+1mrhlCtVNQM2kHo= github.com/zeebo/pcg v1.0.1/go.mod h1:09F0S9iiKrwn9rlI5yjLkmrug154/YRW6KnnXVDM/l4= +go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= +go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= +go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8= +go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM= +go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA= +go.opentelemetry.io/otel/metric v1.38.0/go.mod h1:kB5n/QoRM8YwmUahxvI3bO34eVtQf2i4utNVLr9gEmI= +go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E= +go.opentelemetry.io/otel/sdk v1.38.0/go.mod h1:ghmNdGlVemJI3+ZB5iDEuk4bWA3GkTpW+DOoZMYBVVg= +go.opentelemetry.io/otel/sdk/metric v1.38.0 h1:aSH66iL0aZqo//xXzQLYozmWrXxyFkBJ6qT5wthqPoM= +go.opentelemetry.io/otel/sdk/metric v1.38.0/go.mod h1:dg9PBnW9XdQ1Hd6ZnRz689CbtrUp0wMMs9iPcgT9EZA= +go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE= +go.opentelemetry.io/otel/trace v1.38.0/go.mod h1:j1P9ivuFsTceSWe1oY+EeW3sc+Pp42sO++GHkg4wwhs= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= @@ -103,5 +123,13 @@ golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU= golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY= golang.org/x/tools v0.39.0 h1:ik4ho21kwuQln40uelmciQPp9SipgNDdrafrYA4TmQQ= golang.org/x/tools v0.39.0/go.mod h1:JnefbkDPyD8UU2kI5fuf8ZX4/yUeh9W877ZeBONxUqQ= +gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk= +gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E= +google.golang.org/genproto/googleapis/rpc v0.0.0-20251029180050-ab9386a59fda h1:i/Q+bfisr7gq6feoJnS/DlpdwEL4ihp41fvRiM3Ork0= +google.golang.org/genproto/googleapis/rpc v0.0.0-20251029180050-ab9386a59fda/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk= +google.golang.org/grpc v1.78.0 h1:K1XZG/yGDJnzMdd/uZHAkVqJE+xIDOcmdSFZkBUicNc= +google.golang.org/grpc v1.78.0/go.mod h1:I47qjTo4OKbMkjA/aOOwxDIiPSBofUtQUI5EfpWvW7U= +google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= +google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/grpc/client/client.go b/internal/grpc/client/client.go index 710f023..da76a55 100644 --- a/internal/grpc/client/client.go +++ b/internal/grpc/client/client.go @@ -1,4 +1,4 @@ -package grpc +package client import ( "context" @@ -6,15 +6,20 @@ import ( "fmt" "log" "time" + "tunnel_pls/session" "git.fossy.my.id/bagas/tunnel-please-grpc/gen" + "github.com/golang/protobuf/ptypes/empty" "google.golang.org/grpc" + "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/health/grpc_health_v1" "google.golang.org/grpc/keepalive" + "google.golang.org/grpc/status" ) -type ClientConfig struct { +type GrpcConfig struct { Address string UseTLS bool InsecureSkipVerify bool @@ -25,12 +30,14 @@ type ClientConfig struct { type Client struct { conn *grpc.ClientConn - config *ClientConfig + config *GrpcConfig + sessionRegistry session.Registry IdentityService gen.IdentityClient + eventService gen.EventServiceClient } -func DefaultConfig() *ClientConfig { - return &ClientConfig{ +func DefaultConfig() *GrpcConfig { + return &GrpcConfig{ Address: "localhost:50051", UseTLS: false, InsecureSkipVerify: false, @@ -40,7 +47,7 @@ func DefaultConfig() *ClientConfig { } } -func NewClient(config *ClientConfig) (*Client, error) { +func New(config *GrpcConfig, sessionRegistry session.Registry) (*Client, error) { if config == nil { config = DefaultConfig() } @@ -61,15 +68,15 @@ func NewClient(config *ClientConfig) (*Client, error) { kaParams := keepalive.ClientParameters{ Time: 10 * time.Second, Timeout: 3 * time.Second, - PermitWithoutStream: true, + PermitWithoutStream: false, } opts = append(opts, grpc.WithKeepaliveParams(kaParams)) } opts = append(opts, grpc.WithDefaultCallOptions( - grpc.MaxCallRecvMsgSize(4*1024*1024), // 4MB - grpc.MaxCallSendMsgSize(4*1024*1024), // 4MB + grpc.MaxCallRecvMsgSize(4*1024*1024), + grpc.MaxCallSendMsgSize(4*1024*1024), ), ) @@ -78,15 +85,98 @@ func NewClient(config *ClientConfig) (*Client, error) { return nil, fmt.Errorf("failed to connect to gRPC server at %s: %w", config.Address, err) } - log.Printf("Successfully connected to gRPC server at %s", config.Address) identityService := gen.NewIdentityClient(conn) + eventService := gen.NewEventServiceClient(conn) + return &Client{ conn: conn, config: config, IdentityService: identityService, + eventService: eventService, + sessionRegistry: sessionRegistry, }, nil } +func (c *Client) SubscribeEvents(ctx context.Context) error { + for { + if ctx.Err() != nil { + log.Println("Context cancelled, stopping event subscription") + return ctx.Err() + } + + log.Println("Subscribing to events...") + stream, err := c.eventService.Subscribe(ctx, &empty.Empty{}) + if err != nil { + log.Printf("Failed to subscribe: %v. Retrying in 10 seconds...", err) + select { + case <-time.After(10 * time.Second): + case <-ctx.Done(): + return ctx.Err() + } + continue + } + + if err := c.processEventStream(ctx, stream); err != nil { + if ctx.Err() != nil { + return ctx.Err() + } + log.Printf("Stream error: %v. Reconnecting in 10 seconds...", err) + select { + case <-time.After(10 * time.Second): + case <-ctx.Done(): + return ctx.Err() + } + } + } +} + +func (c *Client) processEventStream(ctx context.Context, stream gen.EventService_SubscribeClient) error { + for { + select { + case <-ctx.Done(): + return ctx.Err() + default: + } + + event, err := stream.Recv() + if err != nil { + st, ok := status.FromError(err) + if !ok { + return fmt.Errorf("non-gRPC error: %w", err) + } + + switch st.Code() { + case codes.Unavailable, codes.Canceled, codes.DeadlineExceeded: + return fmt.Errorf("stream closed [%s]: %s", st.Code(), st.Message()) + default: + return fmt.Errorf("gRPC error [%s]: %s", st.Code(), st.Message()) + } + } + + if event != nil { + dataEvent := event.GetDataEvent() + if dataEvent != nil { + oldSlug := dataEvent.GetOld() + newSlug := dataEvent.GetNew() + + userSession, exist := c.sessionRegistry.Get(oldSlug) + if !exist { + log.Printf("Session with slug '%s' not found, ignoring event", oldSlug) + continue + } + success := c.sessionRegistry.Update(oldSlug, newSlug) + + if success { + log.Printf("Successfully updated session slug from '%s' to '%s'", oldSlug, newSlug) + userSession.GetInteraction().Redraw() + } else { + log.Printf("Failed to update session slug from '%s' to '%s'", oldSlug, newSlug) + } + } + } + } +} + func (c *Client) GetConnection() *grpc.ClientConn { return c.conn } @@ -99,88 +189,23 @@ func (c *Client) Close() error { return nil } -func (c *Client) IsConnected() bool { - if c.conn == nil { - return false - } - state := c.conn.GetState() - return state.String() == "READY" || state.String() == "IDLE" -} +func (c *Client) CheckServerHealth(ctx context.Context) error { + healthClient := grpc_health_v1.NewHealthClient(c.GetConnection()) + resp, err := healthClient.Check(ctx, &grpc_health_v1.HealthCheckRequest{ + Service: "", + }) -func (c *Client) Reconnect() error { - if err := c.Close(); err != nil { - log.Printf("Warning: error closing existing connection: %v", err) - } - - var opts []grpc.DialOption - - if c.config.UseTLS { - tlsConfig := &tls.Config{ - InsecureSkipVerify: c.config.InsecureSkipVerify, - } - creds := credentials.NewTLS(tlsConfig) - opts = append(opts, grpc.WithTransportCredentials(creds)) - } else { - opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials())) - } - - if c.config.KeepAlive { - kaParams := keepalive.ClientParameters{ - Time: 10 * time.Second, - Timeout: 3 * time.Second, - PermitWithoutStream: true, - } - opts = append(opts, grpc.WithKeepaliveParams(kaParams)) - } - - opts = append(opts, - grpc.WithDefaultCallOptions( - grpc.MaxCallRecvMsgSize(4*1024*1024), - grpc.MaxCallSendMsgSize(4*1024*1024), - ), - ) - - conn, err := grpc.NewClient(c.config.Address, opts...) if err != nil { - return fmt.Errorf("failed to reconnect to gRPC server at %s: %w", c.config.Address, err) + return fmt.Errorf("health check failed: %w", err) } - c.conn = conn - log.Printf("Successfully reconnected to gRPC server at %s", c.config.Address) - return nil -} - -func (c *Client) WaitForReady(ctx context.Context) error { - if c.conn == nil { - return fmt.Errorf("connection is nil") - } - - _, ok := ctx.Deadline() - if !ok { - var cancel context.CancelFunc - ctx, cancel = context.WithTimeout(ctx, c.config.Timeout) - defer cancel() - } - - currentState := c.conn.GetState() - for currentState.String() != "READY" { - if !c.conn.WaitForStateChange(ctx, currentState) { - return fmt.Errorf("timeout waiting for connection to be ready") - } - currentState = c.conn.GetState() - - if currentState.String() == "READY" || currentState.String() == "IDLE" { - return nil - } - - if currentState.String() == "SHUTDOWN" || currentState.String() == "TRANSIENT_FAILURE" { - return fmt.Errorf("connection is in %s state", currentState.String()) - } + if resp.Status != grpc_health_v1.HealthCheckResponse_SERVING { + return fmt.Errorf("server not serving: %v", resp.Status) } return nil } -func (c *Client) GetConfig() *ClientConfig { +func (c *Client) GetConfig() *GrpcConfig { return c.config } diff --git a/main.go b/main.go index 60a55f1..5f7a82b 100644 --- a/main.go +++ b/main.go @@ -1,12 +1,15 @@ package main import ( + "context" "fmt" "log" "net/http" _ "net/http/pprof" "os" + "time" "tunnel_pls/internal/config" + "tunnel_pls/internal/grpc/client" "tunnel_pls/internal/key" "tunnel_pls/server" "tunnel_pls/session" @@ -61,9 +64,49 @@ func main() { sshConfig.AddHostKey(private) sessionRegistry := session.NewRegistry() - app, err := server.NewServer(sshConfig, sessionRegistry) + grpcClient, err := client.New(&client.GrpcConfig{ + Address: "localhost:8080", + UseTLS: false, + InsecureSkipVerify: false, + Timeout: 10 * time.Second, + KeepAlive: true, + MaxRetries: 3, + }, sessionRegistry) + if err != nil { + return + } + defer func(grpcClient *client.Client) { + err := grpcClient.Close() + if err != nil { + + } + }(grpcClient) + + ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) + err = grpcClient.CheckServerHealth(ctx) + if err != nil { + log.Fatalf("gRPC health check failed: %s", err) + return + } + cancel() + + ctx, cancel = context.WithCancel(context.Background()) + //go func(err error) { + // if !errors.Is(err, ctx.Err()) { + // log.Fatalf("Event subscription error: %s", err) + // } + //}(grpcClient.SubscribeEvents(ctx)) + go func() { + err := grpcClient.SubscribeEvents(ctx) + if err != nil { + return + } + }() + + app, err := server.NewServer(sshConfig, sessionRegistry, grpcClient) if err != nil { log.Fatalf("Failed to start server: %s", err) } app.Start() + cancel() } diff --git a/server/server.go b/server/server.go index 2b9fda4..53e8e3f 100644 --- a/server/server.go +++ b/server/server.go @@ -5,6 +5,7 @@ import ( "log" "net" "tunnel_pls/internal/config" + "tunnel_pls/internal/grpc/client" "tunnel_pls/session" "golang.org/x/crypto/ssh" @@ -14,9 +15,10 @@ type Server struct { conn *net.Listener config *ssh.ServerConfig sessionRegistry session.Registry + grpcClient *client.Client } -func NewServer(sshConfig *ssh.ServerConfig, sessionRegistry session.Registry) (*Server, error) { +func NewServer(sshConfig *ssh.ServerConfig, sessionRegistry session.Registry, grpcClient *client.Client) (*Server, error) { listener, err := net.Listen("tcp", fmt.Sprintf(":%s", config.Getenv("PORT", "2200"))) if err != nil { log.Fatalf("failed to listen on port 2200: %v", err) @@ -42,6 +44,7 @@ func NewServer(sshConfig *ssh.ServerConfig, sessionRegistry session.Registry) (* conn: &listener, config: sshConfig, sessionRegistry: sessionRegistry, + grpcClient: grpcClient, }, nil } @@ -69,9 +72,13 @@ func (s *Server) handleConnection(conn net.Conn) { } return } - - log.Println("SSH connection established:", sshConn.User()) - + //ctx := context.Background() + //log.Println("SSH connection established:", sshConn.User()) + //get, err := s.grpcClient.IdentityService.Get(ctx, &gen.IdentifierRequest{Id: sshConn.User()}) + //if err != nil { + // return + //} + //fmt.Println(get) sshSession := session.New(sshConn, forwardingReqs, chans, s.sessionRegistry) err = sshSession.Start() if err != nil { diff --git a/session/interaction/interaction.go b/session/interaction/interaction.go index 2b24e60..9356a3a 100644 --- a/session/interaction/interaction.go +++ b/session/interaction/interaction.go @@ -31,6 +31,7 @@ type Controller interface { SetSlugModificator(func(oldSlug, newSlug string) bool) Start() SetWH(w, h int) + Redraw() } type Forwarder interface { @@ -65,7 +66,6 @@ type commandItem struct { } type model struct { - tunnelURL string domain string protocol string tunnelType types.TunnelType @@ -84,6 +84,13 @@ type model struct { height int } +func (m *model) getTunnelURL() string { + if m.tunnelType == types.HTTP { + return buildURL(m.protocol, m.interaction.slugManager.Get(), m.domain) + } + return fmt.Sprintf("tcp://%s:%d", m.domain, m.port) +} + type keymap struct { quit key.Binding command key.Binding @@ -163,11 +170,11 @@ func tickCmd(d time.Duration) tea.Cmd { }) } -func (m model) Init() tea.Cmd { +func (m *model) Init() tea.Cmd { return tea.Batch(textinput.Blink, tea.WindowSize()) } -func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { +func (m *model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { var cmd tea.Cmd switch msg := msg.(type) { @@ -225,7 +232,6 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m, nil } - m.tunnelURL = buildURL(m.protocol, inputValue, m.domain) m.editingSlug = false m.slugError = "" return m, tea.Batch(tea.ClearScreen, textinput.Blink) @@ -291,14 +297,20 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m, nil } -func (m model) helpView() string { +func (i *Interaction) Redraw() { + if i.program != nil { + i.program.Send(tea.ClearScreen()) + } +} + +func (m *model) helpView() string { return "\n" + m.help.ShortHelpView([]key.Binding{ m.keymap.command, m.keymap.quit, }) } -func (m model) View() string { +func (m *model) View() string { if m.quitting { return "" } @@ -659,11 +671,11 @@ func (m model) View() string { MarginBottom(boxMargin). Width(boxMaxWidth) - urlDisplay := m.tunnelURL - if shouldUseCompactLayout(m.width, 80) && len(m.tunnelURL) > m.width-20 { + urlDisplay := m.getTunnelURL() + if shouldUseCompactLayout(m.width, 80) && len(urlDisplay) > m.width-20 { maxLen := m.width - 25 if maxLen > 10 { - urlDisplay = truncateString(m.tunnelURL, maxLen) + urlDisplay = truncateString(urlDisplay, maxLen) } } @@ -737,13 +749,6 @@ func (i *Interaction) Start() { tunnelType := i.forwarder.GetTunnelType() port := i.forwarder.GetForwardedPort() - var tunnelURL string - if tunnelType == types.HTTP { - tunnelURL = buildURL(protocol, i.slugManager.Get(), domain) - } else { - tunnelURL = fmt.Sprintf("tcp://%s:%d", domain, port) - } - items := []list.Item{ commandItem{name: "slug", desc: "Set custom subdomain"}, commandItem{name: "tunnel-type", desc: "Change tunnel type (Coming Soon)"}, @@ -764,8 +769,7 @@ func (i *Interaction) Start() { ti.CharLimit = 20 ti.Width = 50 - m := model{ - tunnelURL: tunnelURL, + m := &model{ domain: domain, protocol: protocol, tunnelType: tunnelType, From fd6ffc2500aa282b7d91e8170cfdbf42377d5198 Mon Sep 17 00:00:00 2001 From: bagas Date: Fri, 2 Jan 2026 18:27:48 +0700 Subject: [PATCH 03/15] feat(grpc): integrate slug edit handling --- internal/grpc/client/client.go | 245 ++++++++++++++++++----------- main.go | 8 +- server/http.go | 4 +- server/https.go | 4 +- session/interaction/constants.go | 152 ------------------ session/interaction/interaction.go | 47 +----- session/registry.go | 193 +++++++++++++++++++++-- 7 files changed, 349 insertions(+), 304 deletions(-) delete mode 100644 session/interaction/constants.go diff --git a/internal/grpc/client/client.go b/internal/grpc/client/client.go index da76a55..38835c1 100644 --- a/internal/grpc/client/client.go +++ b/internal/grpc/client/client.go @@ -3,13 +3,14 @@ package client import ( "context" "crypto/tls" + "errors" "fmt" + "io" "log" "time" "tunnel_pls/session" - "git.fossy.my.id/bagas/tunnel-please-grpc/gen" - "github.com/golang/protobuf/ptypes/empty" + proto "git.fossy.my.id/bagas/tunnel-please-grpc/gen" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" @@ -20,36 +21,59 @@ import ( ) type GrpcConfig struct { - Address string - UseTLS bool - InsecureSkipVerify bool - Timeout time.Duration - KeepAlive bool - MaxRetries int + Address string + UseTLS bool + InsecureSkipVerify bool + Timeout time.Duration + KeepAlive bool + MaxRetries int + KeepAliveTime time.Duration + KeepAliveTimeout time.Duration + PermitWithoutStream bool } type Client struct { conn *grpc.ClientConn config *GrpcConfig sessionRegistry session.Registry - IdentityService gen.IdentityClient - eventService gen.EventServiceClient + slugService proto.SlugChangeClient + eventService proto.EventServiceClient } func DefaultConfig() *GrpcConfig { return &GrpcConfig{ - Address: "localhost:50051", - UseTLS: false, - InsecureSkipVerify: false, - Timeout: 10 * time.Second, - KeepAlive: true, - MaxRetries: 3, + Address: "localhost:50051", + UseTLS: false, + InsecureSkipVerify: false, + Timeout: 10 * time.Second, + KeepAlive: true, + MaxRetries: 3, + KeepAliveTime: 2 * time.Minute, + KeepAliveTimeout: 10 * time.Second, + PermitWithoutStream: false, } } func New(config *GrpcConfig, sessionRegistry session.Registry) (*Client, error) { if config == nil { config = DefaultConfig() + } else { + defaults := DefaultConfig() + if config.Address == "" { + config.Address = defaults.Address + } + if config.Timeout == 0 { + config.Timeout = defaults.Timeout + } + if config.MaxRetries == 0 { + config.MaxRetries = defaults.MaxRetries + } + if config.KeepAliveTime == 0 { + config.KeepAliveTime = defaults.KeepAliveTime + } + if config.KeepAliveTimeout == 0 { + config.KeepAliveTimeout = defaults.KeepAliveTimeout + } } var opts []grpc.DialOption @@ -66,9 +90,9 @@ func New(config *GrpcConfig, sessionRegistry session.Registry) (*Client, error) if config.KeepAlive { kaParams := keepalive.ClientParameters{ - Time: 10 * time.Second, - Timeout: 3 * time.Second, - PermitWithoutStream: false, + Time: config.KeepAliveTime, + Timeout: config.KeepAliveTimeout, + PermitWithoutStream: config.PermitWithoutStream, } opts = append(opts, grpc.WithKeepaliveParams(kaParams)) } @@ -85,94 +109,120 @@ func New(config *GrpcConfig, sessionRegistry session.Registry) (*Client, error) return nil, fmt.Errorf("failed to connect to gRPC server at %s: %w", config.Address, err) } - identityService := gen.NewIdentityClient(conn) - eventService := gen.NewEventServiceClient(conn) + slugService := proto.NewSlugChangeClient(conn) + eventService := proto.NewEventServiceClient(conn) return &Client{ conn: conn, config: config, - IdentityService: identityService, - eventService: eventService, + slugService: slugService, sessionRegistry: sessionRegistry, + eventService: eventService, }, nil } -func (c *Client) SubscribeEvents(ctx context.Context) error { - for { - if ctx.Err() != nil { - log.Println("Context cancelled, stopping event subscription") - return ctx.Err() - } - - log.Println("Subscribing to events...") - stream, err := c.eventService.Subscribe(ctx, &empty.Empty{}) - if err != nil { - log.Printf("Failed to subscribe: %v. Retrying in 10 seconds...", err) - select { - case <-time.After(10 * time.Second): - case <-ctx.Done(): - return ctx.Err() - } - continue - } - - if err := c.processEventStream(ctx, stream); err != nil { - if ctx.Err() != nil { - return ctx.Err() - } - log.Printf("Stream error: %v. Reconnecting in 10 seconds...", err) - select { - case <-time.After(10 * time.Second): - case <-ctx.Done(): - return ctx.Err() - } - } +func (c *Client) SubscribeEvents(ctx context.Context, identity string) error { + subscribe, err := c.eventService.Subscribe(ctx) + if err != nil { + return err } + err = subscribe.Send(&proto.Client{ + Type: proto.EventType_AUTHENTICATION, + Payload: &proto.Client_AuthEvent{ + AuthEvent: &proto.Authentication{ + Identity: identity, + AuthToken: "test_auth_key", + }, + }, + }) + + if err != nil { + log.Println("Authentication failed to send to gRPC server:", err) + return err + } + log.Println("Authentication Successfully sent to gRPC server") + err = c.processEventStream(subscribe) + if err != nil { + return err + } + return nil } -func (c *Client) processEventStream(ctx context.Context, stream gen.EventService_SubscribeClient) error { +func (c *Client) processEventStream(subscribe grpc.BidiStreamingClient[proto.Client, proto.Controller]) error { for { - select { - case <-ctx.Done(): - return ctx.Err() - default: - } - - event, err := stream.Recv() + recv, err := subscribe.Recv() if err != nil { - st, ok := status.FromError(err) - if !ok { - return fmt.Errorf("non-gRPC error: %w", err) - } - - switch st.Code() { - case codes.Unavailable, codes.Canceled, codes.DeadlineExceeded: - return fmt.Errorf("stream closed [%s]: %s", st.Code(), st.Message()) - default: - return fmt.Errorf("gRPC error [%s]: %s", st.Code(), st.Message()) + if isConnectionError(err) { + log.Printf("connection error receiving from gRPC server: %v", err) + return err } + log.Printf("non-connection receive error from gRPC server: %v", err) + continue } - - if event != nil { - dataEvent := event.GetDataEvent() - if dataEvent != nil { - oldSlug := dataEvent.GetOld() - newSlug := dataEvent.GetNew() - - userSession, exist := c.sessionRegistry.Get(oldSlug) - if !exist { - log.Printf("Session with slug '%s' not found, ignoring event", oldSlug) - continue - } - success := c.sessionRegistry.Update(oldSlug, newSlug) - - if success { - log.Printf("Successfully updated session slug from '%s' to '%s'", oldSlug, newSlug) - userSession.GetInteraction().Redraw() - } else { - log.Printf("Failed to update session slug from '%s' to '%s'", oldSlug, newSlug) + switch recv.GetType() { + case proto.EventType_SLUG_CHANGE: + oldSlug := recv.GetSlugEvent().GetOld() + newSlug := recv.GetSlugEvent().GetNew() + session, err := c.sessionRegistry.Get(oldSlug) + if err != nil { + errSend := subscribe.Send(&proto.Client{ + Type: proto.EventType_SLUG_CHANGE_RESPONSE, + Payload: &proto.Client_SlugEventResponse{ + SlugEventResponse: &proto.SlugChangeEventResponse{ + Success: false, + Message: err.Error(), + }, + }, + }) + if errSend != nil { + if isConnectionError(errSend) { + log.Printf("connection error sending slug change failure: %v", errSend) + return errSend + } + log.Printf("non-connection send error for slug change failure: %v", errSend) } + continue } + err = c.sessionRegistry.Update(oldSlug, newSlug) + if err != nil { + errSend := subscribe.Send(&proto.Client{ + Type: proto.EventType_SLUG_CHANGE_RESPONSE, + Payload: &proto.Client_SlugEventResponse{ + SlugEventResponse: &proto.SlugChangeEventResponse{ + Success: false, + Message: err.Error(), + }, + }, + }) + if errSend != nil { + if isConnectionError(errSend) { + log.Printf("connection error sending slug change failure: %v", errSend) + return errSend + } + log.Printf("non-connection send error for slug change failure: %v", errSend) + } + continue + } + session.GetInteraction().Redraw() + err = subscribe.Send(&proto.Client{ + Type: proto.EventType_SLUG_CHANGE_RESPONSE, + Payload: &proto.Client_SlugEventResponse{ + SlugEventResponse: &proto.SlugChangeEventResponse{ + Success: true, + Message: "", + }, + }, + }) + if err != nil { + if isConnectionError(err) { + log.Printf("connection error sending slug change success: %v", err) + return err + } + log.Printf("non-connection send error for slug change success: %v", err) + continue + } + default: + log.Printf("Unknown event type received: %v", recv.GetType()) } } } @@ -209,3 +259,18 @@ func (c *Client) CheckServerHealth(ctx context.Context) error { func (c *Client) GetConfig() *GrpcConfig { return c.config } + +func isConnectionError(err error) bool { + if err == nil { + return false + } + if errors.Is(err, io.EOF) { + return true + } + switch status.Code(err) { + case codes.Unavailable, codes.Canceled, codes.DeadlineExceeded: + return true + default: + return false + } +} diff --git a/main.go b/main.go index 5f7a82b..1daa6e0 100644 --- a/main.go +++ b/main.go @@ -91,13 +91,9 @@ func main() { cancel() ctx, cancel = context.WithCancel(context.Background()) - //go func(err error) { - // if !errors.Is(err, ctx.Err()) { - // log.Fatalf("Event subscription error: %s", err) - // } - //}(grpcClient.SubscribeEvents(ctx)) go func() { - err := grpcClient.SubscribeEvents(ctx) + identity := config.Getenv("DOMAIN", "localhost") + err = grpcClient.SubscribeEvents(ctx, identity) if err != nil { return } diff --git a/server/http.go b/server/http.go index 433b9a0..8add118 100644 --- a/server/http.go +++ b/server/http.go @@ -313,8 +313,8 @@ func (hs *httpServer) handler(conn net.Conn) { return } - sshSession, exist := hs.sessionRegistry.Get(slug) - if !exist { + sshSession, err := hs.sessionRegistry.Get(slug) + if err != nil { _, err = conn.Write([]byte("HTTP/1.1 301 Moved Permanently\r\n" + fmt.Sprintf("Location: https://tunnl.live/tunnel-not-found?slug=%s\r\n", slug) + "Content-Length: 0\r\n" + diff --git a/server/https.go b/server/https.go index 90ffd49..3c502a5 100644 --- a/server/https.go +++ b/server/https.go @@ -89,8 +89,8 @@ func (hs *httpServer) handlerTLS(conn net.Conn) { return } - sshSession, exist := hs.sessionRegistry.Get(slug) - if !exist { + sshSession, err := hs.sessionRegistry.Get(slug) + if err != nil { _, err = conn.Write([]byte("HTTP/1.1 301 Moved Permanently\r\n" + fmt.Sprintf("Location: https://tunnl.live/tunnel-not-found?slug=%s\r\n", slug) + "Content-Length: 0\r\n" + diff --git a/session/interaction/constants.go b/session/interaction/constants.go deleted file mode 100644 index 91024d3..0000000 --- a/session/interaction/constants.go +++ /dev/null @@ -1,152 +0,0 @@ -package interaction - -const ( - backspaceChar = 8 - deleteChar = 127 - enterChar = 13 - escapeChar = 27 - ctrlC = 3 - forwardSlash = '/' - minPrintableChar = 32 - maxPrintableChar = 126 - - minSlugLength = 3 - maxSlugLength = 20 - - clearScreen = "\033[H\033[2J" - clearLine = "\033[K" - clearToLineEnd = "\r\033[K" - backspaceSeq = "\b \b" - - minBoxWidth = 50 - paddingRight = 4 -) - -var forbiddenSlugs = map[string]struct{}{ - "ping": {}, - "staging": {}, - "admin": {}, - "root": {}, - "api": {}, - "www": {}, - "support": {}, - "help": {}, - "status": {}, - "health": {}, - "login": {}, - "logout": {}, - "signup": {}, - "register": {}, - "settings": {}, - "config": {}, - "null": {}, - "undefined": {}, - "example": {}, - "test": {}, - "dev": {}, - "system": {}, - "administrator": {}, - "dashboard": {}, - "account": {}, - "profile": {}, - "user": {}, - "users": {}, - "auth": {}, - "oauth": {}, - "callback": {}, - "webhook": {}, - "webhooks": {}, - "static": {}, - "assets": {}, - "cdn": {}, - "mail": {}, - "email": {}, - "ftp": {}, - "ssh": {}, - "git": {}, - "svn": {}, - "blog": {}, - "news": {}, - "about": {}, - "contact": {}, - "terms": {}, - "privacy": {}, - "legal": {}, - "billing": {}, - "payment": {}, - "checkout": {}, - "cart": {}, - "shop": {}, - "store": {}, - "download": {}, - "uploads": {}, - "images": {}, - "img": {}, - "css": {}, - "js": {}, - "fonts": {}, - "public": {}, - "private": {}, - "internal": {}, - "external": {}, - "proxy": {}, - "cache": {}, - "debug": {}, - "metrics": {}, - "monitoring": {}, - "graphql": {}, - "rest": {}, - "rpc": {}, - "socket": {}, - "ws": {}, - "wss": {}, - "app": {}, - "apps": {}, - "mobile": {}, - "desktop": {}, - "embed": {}, - "widget": {}, - "docs": {}, - "documentation": {}, - "wiki": {}, - "forum": {}, - "community": {}, - "feedback": {}, - "report": {}, - "abuse": {}, - "spam": {}, - "security": {}, - "verify": {}, - "confirm": {}, - "reset": {}, - "password": {}, - "recovery": {}, - "unsubscribe": {}, - "subscribe": {}, - "notifications": {}, - "alerts": {}, - "messages": {}, - "inbox": {}, - "outbox": {}, - "sent": {}, - "draft": {}, - "trash": {}, - "archive": {}, - "search": {}, - "explore": {}, - "discover": {}, - "trending": {}, - "popular": {}, - "featured": {}, - "new": {}, - "latest": {}, - "top": {}, - "best": {}, - "hot": {}, - "random": {}, - "all": {}, - "any": {}, - "none": {}, - "true": {}, - "false": {}, -} diff --git a/session/interaction/interaction.go b/session/interaction/interaction.go index 9356a3a..3a36f4c 100644 --- a/session/interaction/interaction.go +++ b/session/interaction/interaction.go @@ -28,7 +28,7 @@ type Lifecycle interface { type Controller interface { SetChannel(channel ssh.Channel) SetLifecycle(lifecycle Lifecycle) - SetSlugModificator(func(oldSlug, newSlug string) bool) + SetSlugModificator(func(oldSlug, newSlug string) error) Start() SetWH(w, h int) Redraw() @@ -45,7 +45,7 @@ type Interaction struct { slugManager slug.Manager forwarder Forwarder lifecycle Lifecycle - updateClientSlug func(oldSlug, newSlug string) bool + updateClientSlug func(oldSlug, newSlug string) error program *tea.Program ctx context.Context cancel context.CancelFunc @@ -121,7 +121,7 @@ func (i *Interaction) SetChannel(channel ssh.Channel) { i.channel = channel } -func (i *Interaction) SetSlugModificator(modificator func(oldSlug, newSlug string) (success bool)) { +func (i *Interaction) SetSlugModificator(modificator func(oldSlug, newSlug string) error) { i.updateClientSlug = modificator } @@ -218,20 +218,10 @@ func (m *model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m, tea.Batch(tea.ClearScreen, textinput.Blink) case "enter": inputValue := m.slugInput.Value() - - if isForbiddenSlug(inputValue) { - m.slugError = "This subdomain is reserved. Please choose a different one." - return m, nil - } else if !isValidSlug(inputValue) { - m.slugError = "Invalid subdomain. Follow the rules." + if err := m.interaction.updateClientSlug(m.interaction.slugManager.Get(), inputValue); err != nil { + m.slugError = err.Error() return m, nil } - - if !m.interaction.updateClientSlug(m.interaction.slugManager.Get(), inputValue) { - m.slugError = "Someone already uses this subdomain." - return m, nil - } - m.editingSlug = false m.slugError = "" return m, tea.Batch(tea.ClearScreen, textinput.Blink) @@ -823,30 +813,3 @@ func buildURL(protocol, subdomain, domain string) string { func generateRandomSubdomain() string { return random.GenerateRandomString(20) } - -func isValidSlug(slug string) bool { - if len(slug) < minSlugLength || len(slug) > maxSlugLength { - return false - } - - if slug[0] == '-' || slug[len(slug)-1] == '-' { - return false - } - - for _, c := range slug { - if !isValidSlugChar(byte(c)) { - return false - } - } - - return true -} - -func isValidSlugChar(c byte) bool { - return (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-' -} - -func isForbiddenSlug(slug string) bool { - _, ok := forbiddenSlugs[slug] - return ok -} diff --git a/session/registry.go b/session/registry.go index cc1e955..8ff70fa 100644 --- a/session/registry.go +++ b/session/registry.go @@ -1,10 +1,13 @@ package session -import "sync" +import ( + "fmt" + "sync" +) type Registry interface { - Get(slug string) (session *SSHSession, exist bool) - Update(oldSlug, newSlug string) (success bool) + Get(slug string) (session *SSHSession, err error) + Update(oldSlug, newSlug string) error Register(slug string, session *SSHSession) (success bool) Remove(slug string) } @@ -19,31 +22,40 @@ func NewRegistry() Registry { } } -func (r *registry) Get(slug string) (session *SSHSession, exist bool) { +func (r *registry) Get(slug string) (session *SSHSession, err error) { r.mu.RLock() defer r.mu.RUnlock() - session, exist = r.clients[slug] - return + client, ok := r.clients[slug] + if !ok { + return nil, fmt.Errorf("session not found") + } + return client, nil } -func (r *registry) Update(oldSlug, newSlug string) (success bool) { +func (r *registry) Update(oldSlug, newSlug string) error { + if isForbiddenSlug(newSlug) { + return fmt.Errorf("this subdomain is reserved. Please choose a different one") + } else if !isValidSlug(newSlug) { + return fmt.Errorf("invalid subdomain. Follow the rules") + } + r.mu.Lock() defer r.mu.Unlock() if _, exists := r.clients[newSlug]; exists && newSlug != oldSlug { - return false + return fmt.Errorf("someone already uses this subdomain") } client, ok := r.clients[oldSlug] if !ok { - return false + return fmt.Errorf("session not found") } delete(r.clients, oldSlug) client.slugManager.Set(newSlug) r.clients[newSlug] = client - return true + return nil } func (r *registry) Register(slug string, session *SSHSession) (success bool) { @@ -64,3 +76,164 @@ func (r *registry) Remove(slug string) { delete(r.clients, slug) } + +func isValidSlug(slug string) bool { + if len(slug) < minSlugLength || len(slug) > maxSlugLength { + return false + } + + if slug[0] == '-' || slug[len(slug)-1] == '-' { + return false + } + + for _, c := range slug { + if !isValidSlugChar(byte(c)) { + return false + } + } + + return true +} + +func isValidSlugChar(c byte) bool { + return (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-' +} + +func isForbiddenSlug(slug string) bool { + _, ok := forbiddenSlugs[slug] + return ok +} + +var forbiddenSlugs = map[string]struct{}{ + "ping": {}, + "staging": {}, + "admin": {}, + "root": {}, + "api": {}, + "www": {}, + "support": {}, + "help": {}, + "status": {}, + "health": {}, + "login": {}, + "logout": {}, + "signup": {}, + "register": {}, + "settings": {}, + "config": {}, + "null": {}, + "undefined": {}, + "example": {}, + "test": {}, + "dev": {}, + "system": {}, + "administrator": {}, + "dashboard": {}, + "account": {}, + "profile": {}, + "user": {}, + "users": {}, + "auth": {}, + "oauth": {}, + "callback": {}, + "webhook": {}, + "webhooks": {}, + "static": {}, + "assets": {}, + "cdn": {}, + "mail": {}, + "email": {}, + "ftp": {}, + "ssh": {}, + "git": {}, + "svn": {}, + "blog": {}, + "news": {}, + "about": {}, + "contact": {}, + "terms": {}, + "privacy": {}, + "legal": {}, + "billing": {}, + "payment": {}, + "checkout": {}, + "cart": {}, + "shop": {}, + "store": {}, + "download": {}, + "uploads": {}, + "images": {}, + "img": {}, + "css": {}, + "js": {}, + "fonts": {}, + "public": {}, + "private": {}, + "internal": {}, + "external": {}, + "proxy": {}, + "cache": {}, + "debug": {}, + "metrics": {}, + "monitoring": {}, + "graphql": {}, + "rest": {}, + "rpc": {}, + "socket": {}, + "ws": {}, + "wss": {}, + "app": {}, + "apps": {}, + "mobile": {}, + "desktop": {}, + "embed": {}, + "widget": {}, + "docs": {}, + "documentation": {}, + "wiki": {}, + "forum": {}, + "community": {}, + "feedback": {}, + "report": {}, + "abuse": {}, + "spam": {}, + "security": {}, + "verify": {}, + "confirm": {}, + "reset": {}, + "password": {}, + "recovery": {}, + "unsubscribe": {}, + "subscribe": {}, + "notifications": {}, + "alerts": {}, + "messages": {}, + "inbox": {}, + "outbox": {}, + "sent": {}, + "draft": {}, + "trash": {}, + "archive": {}, + "search": {}, + "explore": {}, + "discover": {}, + "trending": {}, + "popular": {}, + "featured": {}, + "new": {}, + "latest": {}, + "top": {}, + "best": {}, + "hot": {}, + "random": {}, + "all": {}, + "any": {}, + "none": {}, + "true": {}, + "false": {}, +} + +var ( + minSlugLength = 3 + maxSlugLength = 20 +) From 30e84ac3b7bbbe3b2f7251ba2ee9e8d477f96f9a Mon Sep 17 00:00:00 2001 From: bagas Date: Fri, 2 Jan 2026 22:58:54 +0700 Subject: [PATCH 04/15] feat: implement get sessions by user --- internal/grpc/client/client.go | 65 +++++++++++++++++++++++----- server/server.go | 30 +++++++++---- session/lifecycle/lifecycle.go | 19 +++++++- session/registry.go | 79 ++++++++++++++++++++++++++++------ session/session.go | 24 ++++++++++- 5 files changed, 182 insertions(+), 35 deletions(-) diff --git a/internal/grpc/client/client.go b/internal/grpc/client/client.go index 38835c1..ea86b42 100644 --- a/internal/grpc/client/client.go +++ b/internal/grpc/client/client.go @@ -18,6 +18,7 @@ import ( "google.golang.org/grpc/health/grpc_health_v1" "google.golang.org/grpc/keepalive" "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/timestamppb" ) type GrpcConfig struct { @@ -33,11 +34,12 @@ type GrpcConfig struct { } type Client struct { - conn *grpc.ClientConn - config *GrpcConfig - sessionRegistry session.Registry - slugService proto.SlugChangeClient - eventService proto.EventServiceClient + conn *grpc.ClientConn + config *GrpcConfig + sessionRegistry session.Registry + slugService proto.SlugChangeClient + eventService proto.EventServiceClient + authorizeConnectionService proto.UserServiceClient } func DefaultConfig() *GrpcConfig { @@ -111,13 +113,15 @@ func New(config *GrpcConfig, sessionRegistry session.Registry) (*Client, error) slugService := proto.NewSlugChangeClient(conn) eventService := proto.NewEventServiceClient(conn) + authorizeConnectionService := proto.NewUserServiceClient(conn) return &Client{ - conn: conn, - config: config, - slugService: slugService, - sessionRegistry: sessionRegistry, - eventService: eventService, + conn: conn, + config: config, + slugService: slugService, + sessionRegistry: sessionRegistry, + eventService: eventService, + authorizeConnectionService: authorizeConnectionService, }, nil } @@ -221,6 +225,35 @@ func (c *Client) processEventStream(subscribe grpc.BidiStreamingClient[proto.Cli log.Printf("non-connection send error for slug change success: %v", err) continue } + case proto.EventType_GET_SESSIONS: + sessions := c.sessionRegistry.GetAllSessionFromUser(recv.GetGetSessionsEvent().GetIdentity()) + var details []*proto.Detail + for _, ses := range sessions { + detail := ses.Detail() + details = append(details, &proto.Detail{ + ForwardingType: detail.ForwardingType, + Slug: detail.Slug, + UserId: detail.UserID, + Active: detail.Active, + StartedAt: timestamppb.New(detail.StartedAt), + }) + } + err = subscribe.Send(&proto.Client{ + Type: proto.EventType_GET_SESSIONS, + Payload: &proto.Client_GetSessionsEvent{ + GetSessionsEvent: &proto.GetSessionsResponse{ + Details: details, + }, + }, + }) + if err != nil { + if isConnectionError(err) { + log.Printf("connection error sending sessions success: %v", err) + return err + } + log.Printf("non-connection send error for sessions success: %v", err) + continue + } default: log.Printf("Unknown event type received: %v", recv.GetType()) } @@ -231,6 +264,18 @@ func (c *Client) GetConnection() *grpc.ClientConn { return c.conn } +func (c *Client) AuthorizeConn(ctx context.Context, token string) (authorized bool, err error) { + check, err := c.authorizeConnectionService.Check(ctx, &proto.CheckRequest{AuthToken: token}) + if err != nil { + return false, err + + } + if check.GetResponse() == proto.AuthorizationResponse_MESSAGE_TYPE_UNAUTHORIZED { + return false, nil + } + return true, nil +} + func (c *Client) Close() error { if c.conn != nil { log.Printf("Closing gRPC connection to %s", c.config.Address) diff --git a/server/server.go b/server/server.go index 53e8e3f..f377a4b 100644 --- a/server/server.go +++ b/server/server.go @@ -1,6 +1,7 @@ package server import ( + "context" "fmt" "log" "net" @@ -63,6 +64,13 @@ func (s *Server) Start() { func (s *Server) handleConnection(conn net.Conn) { sshConn, chans, forwardingReqs, err := ssh.NewServerConn(conn, s.config) + defer func(sshConn *ssh.ServerConn) { + err = sshConn.Close() + if err != nil { + log.Printf("failed to close SSH server: %v", err) + } + }(sshConn) + if err != nil { log.Printf("failed to establish SSH connection: %v", err) err := conn.Close() @@ -72,14 +80,20 @@ func (s *Server) handleConnection(conn net.Conn) { } return } - //ctx := context.Background() - //log.Println("SSH connection established:", sshConn.User()) - //get, err := s.grpcClient.IdentityService.Get(ctx, &gen.IdentifierRequest{Id: sshConn.User()}) - //if err != nil { - // return - //} - //fmt.Println(get) - sshSession := session.New(sshConn, forwardingReqs, chans, s.sessionRegistry) + ctx := context.Background() + log.Println("SSH connection established:", sshConn.User()) + + //Fallback: kalau auth gagal userID di set UNAUTHORIZED + authorized, _ := s.grpcClient.AuthorizeConn(ctx, sshConn.User()) + + var userID string + if authorized { + userID = sshConn.User() + } else { + userID = "UNAUTHORIZED" + } + + sshSession := session.New(sshConn, forwardingReqs, chans, s.sessionRegistry, userID) err = sshSession.Start() if err != nil { log.Printf("SSH session ended with error: %v", err) diff --git a/session/lifecycle/lifecycle.go b/session/lifecycle/lifecycle.go index 5917ba0..f2dea50 100644 --- a/session/lifecycle/lifecycle.go +++ b/session/lifecycle/lifecycle.go @@ -4,6 +4,8 @@ import ( "errors" "io" "net" + "time" + portUtil "tunnel_pls/internal/port" "tunnel_pls/session/slug" "tunnel_pls/types" @@ -24,16 +26,18 @@ type Lifecycle struct { forwarder Forwarder slugManager slug.Manager unregisterClient func(slug string) + startedAt time.Time } func NewLifecycle(conn ssh.Conn, forwarder Forwarder, slugManager slug.Manager) *Lifecycle { return &Lifecycle{ - status: "", + status: types.INITIALIZING, conn: conn, channel: nil, forwarder: forwarder, slugManager: slugManager, unregisterClient: nil, + startedAt: time.Now(), } } @@ -48,6 +52,8 @@ type SessionLifecycle interface { GetChannel() ssh.Channel SetChannel(channel ssh.Channel) SetUnregisterClient(unregisterClient func(slug string)) + IsActive() bool + StartedAt() time.Time } func (l *Lifecycle) GetChannel() ssh.Channel { @@ -62,6 +68,9 @@ func (l *Lifecycle) GetConnection() ssh.Conn { } func (l *Lifecycle) SetStatus(status types.Status) { l.status = status + if status == types.RUNNING && l.startedAt.IsZero() { + l.startedAt = time.Now() + } } func (l *Lifecycle) Close() error { @@ -98,3 +107,11 @@ func (l *Lifecycle) Close() error { return nil } + +func (l *Lifecycle) IsActive() bool { + return l.status == types.RUNNING +} + +func (l *Lifecycle) StartedAt() time.Time { + return l.startedAt +} diff --git a/session/registry.go b/session/registry.go index 8ff70fa..b6f655d 100644 --- a/session/registry.go +++ b/session/registry.go @@ -10,15 +10,18 @@ type Registry interface { Update(oldSlug, newSlug string) error Register(slug string, session *SSHSession) (success bool) Remove(slug string) + GetAllSessionFromUser(user string) []*SSHSession } type registry struct { - mu sync.RWMutex - clients map[string]*SSHSession + mu sync.RWMutex + byUser map[string]map[string]*SSHSession + slugIndex map[string]string } func NewRegistry() Registry { return ®istry{ - clients: make(map[string]*SSHSession), + byUser: make(map[string]map[string]*SSHSession), + slugIndex: make(map[string]string), } } @@ -26,7 +29,12 @@ func (r *registry) Get(slug string) (session *SSHSession, err error) { r.mu.RLock() defer r.mu.RUnlock() - client, ok := r.clients[slug] + userID, ok := r.slugIndex[slug] + if !ok { + return nil, fmt.Errorf("session not found") + } + + client, ok := r.byUser[userID][slug] if !ok { return nil, fmt.Errorf("session not found") } @@ -43,18 +51,30 @@ func (r *registry) Update(oldSlug, newSlug string) error { r.mu.Lock() defer r.mu.Unlock() - if _, exists := r.clients[newSlug]; exists && newSlug != oldSlug { - return fmt.Errorf("someone already uses this subdomain") - } - - client, ok := r.clients[oldSlug] + userID, ok := r.slugIndex[oldSlug] if !ok { return fmt.Errorf("session not found") } - delete(r.clients, oldSlug) + if _, exists := r.slugIndex[newSlug]; exists && newSlug != oldSlug { + return fmt.Errorf("someone already uses this subdomain") + } + + client, ok := r.byUser[userID][oldSlug] + if !ok { + return fmt.Errorf("session not found") + } + + delete(r.byUser[userID], oldSlug) + delete(r.slugIndex, oldSlug) + client.slugManager.Set(newSlug) - r.clients[newSlug] = client + r.slugIndex[newSlug] = userID + + if r.byUser[userID] == nil { + r.byUser[userID] = make(map[string]*SSHSession) + } + r.byUser[userID][newSlug] = client return nil } @@ -62,19 +82,50 @@ func (r *registry) Register(slug string, session *SSHSession) (success bool) { r.mu.Lock() defer r.mu.Unlock() - if _, exists := r.clients[slug]; exists { + if _, exists := r.slugIndex[slug]; exists { return false } - r.clients[slug] = session + userID := session.userID + if r.byUser[userID] == nil { + r.byUser[userID] = make(map[string]*SSHSession) + } + + r.byUser[userID][slug] = session + r.slugIndex[slug] = userID return true } +func (r *registry) GetAllSessionFromUser(user string) []*SSHSession { + r.mu.RLock() + defer r.mu.RUnlock() + + m := r.byUser[user] + if len(m) == 0 { + return []*SSHSession{} + } + + sessions := make([]*SSHSession, 0, len(m)) + for _, s := range m { + sessions = append(sessions, s) + } + return sessions +} + func (r *registry) Remove(slug string) { r.mu.Lock() defer r.mu.Unlock() - delete(r.clients, slug) + userID, ok := r.slugIndex[slug] + if !ok { + return + } + + delete(r.byUser[userID], slug) + if len(r.byUser[userID]) == 0 { + delete(r.byUser, userID) + } + delete(r.slugIndex, slug) } func isValidSlug(slug string) bool { diff --git a/session/session.go b/session/session.go index 9a35770..45d497a 100644 --- a/session/session.go +++ b/session/session.go @@ -28,6 +28,7 @@ type SSHSession struct { forwarder forwarder.ForwardingController slugManager slug.Manager registry Registry + userID string } func (s *SSHSession) GetLifecycle() lifecycle.SessionLifecycle { @@ -46,7 +47,7 @@ func (s *SSHSession) GetSlugManager() slug.Manager { return s.slugManager } -func New(conn *ssh.ServerConn, forwardingReq <-chan *ssh.Request, sshChan <-chan ssh.NewChannel, sessionRegistry Registry) *SSHSession { +func New(conn *ssh.ServerConn, forwardingReq <-chan *ssh.Request, sshChan <-chan ssh.NewChannel, sessionRegistry Registry, userID string) *SSHSession { slugManager := slug.NewManager() forwarderManager := forwarder.NewForwarder(slugManager) interactionManager := interaction.NewInteraction(slugManager, forwarderManager) @@ -65,6 +66,25 @@ func New(conn *ssh.ServerConn, forwardingReq <-chan *ssh.Request, sshChan <-chan forwarder: forwarderManager, slugManager: slugManager, registry: sessionRegistry, + userID: userID, + } +} + +type Detail struct { + ForwardingType string `json:"forwarding_type,omitempty"` + Slug string `json:"slug,omitempty"` + UserID string `json:"user_id,omitempty"` + Active bool `json:"active,omitempty"` + StartedAt time.Time `json:"started_at,omitempty"` +} + +func (s *SSHSession) Detail() Detail { + return Detail{ + ForwardingType: string(s.forwarder.GetTunnelType()), + Slug: s.slugManager.Get(), + UserID: s.userID, + Active: s.lifecycle.IsActive(), + StartedAt: s.lifecycle.StartedAt(), } } @@ -86,7 +106,7 @@ func (s *SSHSession) Start() error { if err := s.lifecycle.Close(); err != nil { log.Printf("failed to close session: %v", err) } - return fmt.Errorf("No forwarding Request") + return fmt.Errorf("no forwarding Request") } s.lifecycle.SetChannel(ch) From 8fd9f8b567f6784fa3cfe6521e508a5f75bbc843 Mon Sep 17 00:00:00 2001 From: bagas Date: Sat, 3 Jan 2026 20:06:14 +0700 Subject: [PATCH 05/15] feat: implement sessions request from grpc server --- README.md | 4 + go.mod | 3 +- internal/grpc/client/client.go | 138 +++++++++++++++++++++++---------- main.go | 77 +++++++++++------- server/server.go | 14 ++-- 5 files changed, 155 insertions(+), 81 deletions(-) diff --git a/README.md b/README.md index dbcf475..474f430 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,10 @@ The following environment variables can be configured in the `.env` file: | `BUFFER_SIZE` | Buffer size for io.Copy operations in bytes (4096-1048576) | `32768` | No | | `PPROF_ENABLED` | Enable pprof profiling server | `false` | No | | `PPROF_PORT` | Port for pprof server | `6060` | No | +| `MODE` | Runtime mode: `standalone` (default, no gRPC/auth) or `node` (enable gRPC + auth) | `standalone` | No | +| `GRPC_ADDRESS` | gRPC server address/host used in `node` mode | `localhost` | No | +| `GRPC_PORT` | gRPC server port used in `node` mode | `8080` | No | +| `NODE_TOKEN` | Authentication token sent to controller in `node` mode | - (required in `node`) | Yes (node mode) | **Note:** All environment variables now use UPPERCASE naming. The application includes sensible defaults for all variables, so you can run it without a `.env` file for basic functionality. diff --git a/go.mod b/go.mod index 0806c93..87897ae 100644 --- a/go.mod +++ b/go.mod @@ -8,12 +8,12 @@ require ( github.com/charmbracelet/bubbles v0.21.0 github.com/charmbracelet/bubbletea v1.3.10 github.com/charmbracelet/lipgloss v1.1.0 - github.com/golang/protobuf v1.5.4 github.com/joho/godotenv v1.5.1 github.com/libdns/cloudflare v0.2.2 github.com/muesli/termenv v0.16.0 golang.org/x/crypto v0.46.0 google.golang.org/grpc v1.78.0 + google.golang.org/protobuf v1.36.11 ) require ( @@ -49,7 +49,6 @@ require ( golang.org/x/text v0.32.0 // indirect golang.org/x/tools v0.39.0 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20251029180050-ab9386a59fda // indirect - google.golang.org/protobuf v1.36.11 // indirect ) replace git.fossy.my.id/bagas/tunnel-please-grpc => ../tunnel-please-grpc diff --git a/internal/grpc/client/client.go b/internal/grpc/client/client.go index ea86b42..0883a86 100644 --- a/internal/grpc/client/client.go +++ b/internal/grpc/client/client.go @@ -8,6 +8,8 @@ import ( "io" "log" "time" + "tunnel_pls/internal/config" + "tunnel_pls/session" proto "git.fossy.my.id/bagas/tunnel-please-grpc/gen" @@ -125,34 +127,86 @@ func New(config *GrpcConfig, sessionRegistry session.Registry) (*Client, error) }, nil } -func (c *Client) SubscribeEvents(ctx context.Context, identity string) error { - subscribe, err := c.eventService.Subscribe(ctx) - if err != nil { - return err - } - err = subscribe.Send(&proto.Client{ - Type: proto.EventType_AUTHENTICATION, - Payload: &proto.Client_AuthEvent{ - AuthEvent: &proto.Authentication{ - Identity: identity, - AuthToken: "test_auth_key", - }, - }, - }) +func (c *Client) SubscribeEvents(ctx context.Context, identity, authToken string) error { + const ( + baseBackoff = time.Second + maxBackoff = 30 * time.Second + ) - if err != nil { - log.Println("Authentication failed to send to gRPC server:", err) - return err + backoff := baseBackoff + wait := func() error { + if backoff <= 0 { + return nil + } + select { + case <-time.After(backoff): + return nil + case <-ctx.Done(): + return ctx.Err() + } } - log.Println("Authentication Successfully sent to gRPC server") - err = c.processEventStream(subscribe) - if err != nil { - return err + growBackoff := func() { + backoff *= 2 + if backoff > maxBackoff { + backoff = maxBackoff + } + } + + for { + subscribe, err := c.eventService.Subscribe(ctx) + if err != nil { + if !isConnectionError(err) { + return err + } + if status.Code(err) == codes.Unauthenticated { + return err + } + if err := wait(); err != nil { + return err + } + growBackoff() + continue + } + + err = subscribe.Send(&proto.Node{ + Type: proto.EventType_AUTHENTICATION, + Payload: &proto.Node_AuthEvent{ + AuthEvent: &proto.Authentication{ + Identity: identity, + AuthToken: authToken, + }, + }, + }) + + if err != nil { + log.Println("Authentication failed to send to gRPC server:", err) + if isConnectionError(err) { + if err := wait(); err != nil { + return err + } + growBackoff() + continue + } + return err + } + log.Println("Authentication Successfully sent to gRPC server") + backoff = baseBackoff + + if err = c.processEventStream(subscribe); err != nil { + if isConnectionError(err) { + log.Printf("Reconnect to controller within %v sec", backoff.Seconds()) + if err := wait(); err != nil { + return err + } + growBackoff() + continue + } + return err + } } - return nil } -func (c *Client) processEventStream(subscribe grpc.BidiStreamingClient[proto.Client, proto.Controller]) error { +func (c *Client) processEventStream(subscribe grpc.BidiStreamingClient[proto.Node, proto.Events]) error { for { recv, err := subscribe.Recv() if err != nil { @@ -160,6 +214,10 @@ func (c *Client) processEventStream(subscribe grpc.BidiStreamingClient[proto.Cli log.Printf("connection error receiving from gRPC server: %v", err) return err } + if status.Code(err) == codes.Unauthenticated { + log.Printf("Authentication failed: %v", err) + return err + } log.Printf("non-connection receive error from gRPC server: %v", err) continue } @@ -167,11 +225,11 @@ func (c *Client) processEventStream(subscribe grpc.BidiStreamingClient[proto.Cli case proto.EventType_SLUG_CHANGE: oldSlug := recv.GetSlugEvent().GetOld() newSlug := recv.GetSlugEvent().GetNew() - session, err := c.sessionRegistry.Get(oldSlug) + sess, err := c.sessionRegistry.Get(oldSlug) if err != nil { - errSend := subscribe.Send(&proto.Client{ + errSend := subscribe.Send(&proto.Node{ Type: proto.EventType_SLUG_CHANGE_RESPONSE, - Payload: &proto.Client_SlugEventResponse{ + Payload: &proto.Node_SlugEventResponse{ SlugEventResponse: &proto.SlugChangeEventResponse{ Success: false, Message: err.Error(), @@ -189,9 +247,9 @@ func (c *Client) processEventStream(subscribe grpc.BidiStreamingClient[proto.Cli } err = c.sessionRegistry.Update(oldSlug, newSlug) if err != nil { - errSend := subscribe.Send(&proto.Client{ + errSend := subscribe.Send(&proto.Node{ Type: proto.EventType_SLUG_CHANGE_RESPONSE, - Payload: &proto.Client_SlugEventResponse{ + Payload: &proto.Node_SlugEventResponse{ SlugEventResponse: &proto.SlugChangeEventResponse{ Success: false, Message: err.Error(), @@ -207,10 +265,10 @@ func (c *Client) processEventStream(subscribe grpc.BidiStreamingClient[proto.Cli } continue } - session.GetInteraction().Redraw() - err = subscribe.Send(&proto.Client{ + sess.GetInteraction().Redraw() + err = subscribe.Send(&proto.Node{ Type: proto.EventType_SLUG_CHANGE_RESPONSE, - Payload: &proto.Client_SlugEventResponse{ + Payload: &proto.Node_SlugEventResponse{ SlugEventResponse: &proto.SlugChangeEventResponse{ Success: true, Message: "", @@ -231,6 +289,7 @@ func (c *Client) processEventStream(subscribe grpc.BidiStreamingClient[proto.Cli for _, ses := range sessions { detail := ses.Detail() details = append(details, &proto.Detail{ + Node: config.Getenv("domain", "localhost"), ForwardingType: detail.ForwardingType, Slug: detail.Slug, UserId: detail.UserID, @@ -238,9 +297,9 @@ func (c *Client) processEventStream(subscribe grpc.BidiStreamingClient[proto.Cli StartedAt: timestamppb.New(detail.StartedAt), }) } - err = subscribe.Send(&proto.Client{ + err = subscribe.Send(&proto.Node{ Type: proto.EventType_GET_SESSIONS, - Payload: &proto.Client_GetSessionsEvent{ + Payload: &proto.Node_GetSessionsEvent{ GetSessionsEvent: &proto.GetSessionsResponse{ Details: details, }, @@ -264,16 +323,16 @@ func (c *Client) GetConnection() *grpc.ClientConn { return c.conn } -func (c *Client) AuthorizeConn(ctx context.Context, token string) (authorized bool, err error) { +func (c *Client) AuthorizeConn(ctx context.Context, token string) (authorized bool, user string, err error) { check, err := c.authorizeConnectionService.Check(ctx, &proto.CheckRequest{AuthToken: token}) if err != nil { - return false, err + return false, "UNAUTHORIZED", err + } - } if check.GetResponse() == proto.AuthorizationResponse_MESSAGE_TYPE_UNAUTHORIZED { - return false, nil + return false, "UNAUTHORIZED", nil } - return true, nil + return true, check.GetUser(), nil } func (c *Client) Close() error { @@ -289,15 +348,12 @@ func (c *Client) CheckServerHealth(ctx context.Context) error { resp, err := healthClient.Check(ctx, &grpc_health_v1.HealthCheckRequest{ Service: "", }) - if err != nil { return fmt.Errorf("health check failed: %w", err) } - if resp.Status != grpc_health_v1.HealthCheckResponse_SERVING { return fmt.Errorf("server not serving: %v", resp.Status) } - return nil } diff --git a/main.go b/main.go index 1daa6e0..36ec8ca 100644 --- a/main.go +++ b/main.go @@ -7,6 +7,7 @@ import ( "net/http" _ "net/http/pprof" "os" + "strings" "time" "tunnel_pls/internal/config" "tunnel_pls/internal/grpc/client" @@ -29,6 +30,9 @@ func main() { log.Printf("Starting %s", version.GetVersion()) + mode := strings.ToLower(config.Getenv("MODE", "standalone")) + isNodeMode := mode == "node" + pprofEnabled := config.Getenv("PPROF_ENABLED", "false") if pprofEnabled == "true" { pprofPort := config.Getenv("PPROF_PORT", "6060") @@ -64,40 +68,55 @@ func main() { sshConfig.AddHostKey(private) sessionRegistry := session.NewRegistry() - grpcClient, err := client.New(&client.GrpcConfig{ - Address: "localhost:8080", - UseTLS: false, - InsecureSkipVerify: false, - Timeout: 10 * time.Second, - KeepAlive: true, - MaxRetries: 3, - }, sessionRegistry) - if err != nil { - return - } - defer func(grpcClient *client.Client) { - err := grpcClient.Close() - if err != nil { + var grpcClient *client.Client + var cancel context.CancelFunc = func() {} + var ctx context.Context = context.Background() + if isNodeMode { + grpcHost := config.Getenv("GRPC_ADDRESS", "localhost") + grpcPort := config.Getenv("GRPC_PORT", "8080") + grpcAddr := fmt.Sprintf("%s:%s", grpcHost, grpcPort) + nodeToken := config.Getenv("NODE_TOKEN", "") + if nodeToken == "" { + log.Fatalf("NODE_TOKEN is required in node mode") + return } - }(grpcClient) - - ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) - err = grpcClient.CheckServerHealth(ctx) - if err != nil { - log.Fatalf("gRPC health check failed: %s", err) - return - } - cancel() - - ctx, cancel = context.WithCancel(context.Background()) - go func() { - identity := config.Getenv("DOMAIN", "localhost") - err = grpcClient.SubscribeEvents(ctx, identity) + + grpcClient, err = client.New(&client.GrpcConfig{ + Address: grpcAddr, + UseTLS: false, + InsecureSkipVerify: false, + Timeout: 10 * time.Second, + KeepAlive: true, + MaxRetries: 3, + }, sessionRegistry) if err != nil { return } - }() + defer func(grpcClient *client.Client) { + err := grpcClient.Close() + if err != nil { + + } + }(grpcClient) + + ctx, cancel = context.WithTimeout(context.Background(), time.Second*5) + err = grpcClient.CheckServerHealth(ctx) + if err != nil { + log.Fatalf("gRPC health check failed: %s", err) + return + } + cancel() + + ctx, cancel = context.WithCancel(context.Background()) + go func() { + identity := config.Getenv("DOMAIN", "localhost") + err = grpcClient.SubscribeEvents(ctx, identity, nodeToken) + if err != nil { + return + } + }() + } app, err := server.NewServer(sshConfig, sessionRegistry, grpcClient) if err != nil { diff --git a/server/server.go b/server/server.go index f377a4b..0ee111c 100644 --- a/server/server.go +++ b/server/server.go @@ -83,17 +83,13 @@ func (s *Server) handleConnection(conn net.Conn) { ctx := context.Background() log.Println("SSH connection established:", sshConn.User()) - //Fallback: kalau auth gagal userID di set UNAUTHORIZED - authorized, _ := s.grpcClient.AuthorizeConn(ctx, sshConn.User()) - - var userID string - if authorized { - userID = sshConn.User() - } else { - userID = "UNAUTHORIZED" + user := "UNAUTHORIZED" + if s.grpcClient != nil { + _, u, _ := s.grpcClient.AuthorizeConn(ctx, sshConn.User()) + user = u } - sshSession := session.New(sshConn, forwardingReqs, chans, s.sessionRegistry, userID) + sshSession := session.New(sshConn, forwardingReqs, chans, s.sessionRegistry, user) err = sshSession.Start() if err != nil { log.Printf("SSH session ended with error: %v", err) From 5b603d83176af6d0633ff3f111e2bc7007fd3c73 Mon Sep 17 00:00:00 2001 From: bagas Date: Sat, 3 Jan 2026 21:17:01 +0700 Subject: [PATCH 06/15] feat: implement sessions request from grpc server --- go.mod | 33 ++++++++++++++--------------- go.sum | 65 ++++++++++++++++++++++++++++++++-------------------------- 2 files changed, 53 insertions(+), 45 deletions(-) diff --git a/go.mod b/go.mod index 87897ae..e169929 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module tunnel_pls go 1.25.5 require ( - git.fossy.my.id/bagas/tunnel-please-grpc v1.0.0 + git.fossy.my.id/bagas/tunnel-please-grpc v1.2.0 github.com/caddyserver/certmagic v0.25.0 github.com/charmbracelet/bubbles v0.21.0 github.com/charmbracelet/bubbletea v1.3.10 @@ -20,19 +20,22 @@ require ( github.com/atotto/clipboard v0.1.4 // indirect github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect github.com/caddyserver/zerossl v0.1.3 // indirect - github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect - github.com/charmbracelet/x/ansi v0.10.1 // indirect - github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd // indirect - github.com/charmbracelet/x/term v0.2.1 // indirect + github.com/charmbracelet/colorprofile v0.4.1 // indirect + github.com/charmbracelet/x/ansi v0.11.3 // indirect + github.com/charmbracelet/x/cellbuf v0.0.14 // indirect + github.com/charmbracelet/x/term v0.2.2 // indirect + github.com/clipperhouse/displaywidth v0.6.2 // indirect + github.com/clipperhouse/stringish v0.1.1 // indirect + github.com/clipperhouse/uax29/v2 v2.3.0 // indirect github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect github.com/klauspost/cpuid/v2 v2.3.0 // indirect github.com/libdns/libdns v1.1.1 // indirect - github.com/lucasb-eyer/go-colorful v1.2.0 // indirect + github.com/lucasb-eyer/go-colorful v1.3.0 // indirect github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-localereader v0.0.1 // indirect - github.com/mattn/go-runewidth v0.0.16 // indirect - github.com/mholt/acmez/v3 v3.1.3 // indirect - github.com/miekg/dns v1.1.68 // indirect + github.com/mattn/go-runewidth v0.0.19 // indirect + github.com/mholt/acmez/v3 v3.1.4 // indirect + github.com/miekg/dns v1.1.69 // indirect github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect github.com/muesli/cancelreader v0.2.2 // indirect github.com/rivo/uniseg v0.4.7 // indirect @@ -40,15 +43,13 @@ require ( github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect github.com/zeebo/blake3 v0.2.4 // indirect go.uber.org/multierr v1.11.0 // indirect - go.uber.org/zap v1.27.0 // indirect + go.uber.org/zap v1.27.1 // indirect go.uber.org/zap/exp v0.3.0 // indirect - golang.org/x/mod v0.30.0 // indirect - golang.org/x/net v0.47.0 // indirect + golang.org/x/mod v0.31.0 // indirect + golang.org/x/net v0.48.0 // indirect golang.org/x/sync v0.19.0 // indirect golang.org/x/sys v0.39.0 // indirect golang.org/x/text v0.32.0 // indirect - golang.org/x/tools v0.39.0 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20251029180050-ab9386a59fda // indirect + golang.org/x/tools v0.40.0 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b // indirect ) - -replace git.fossy.my.id/bagas/tunnel-please-grpc => ../tunnel-please-grpc diff --git a/go.sum b/go.sum index 84a22e0..ff64d7e 100644 --- a/go.sum +++ b/go.sum @@ -1,3 +1,5 @@ +git.fossy.my.id/bagas/tunnel-please-grpc v1.2.0 h1:BS1dJU3wa2ILgTGwkV95Knle0il0OQtErGqyb6xV7SU= +git.fossy.my.id/bagas/tunnel-please-grpc v1.2.0/go.mod h1:fG+VkArdkceGB0bNA7IFQus9GetLAwdF5Oi4jdMlXtY= github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= @@ -12,18 +14,24 @@ github.com/charmbracelet/bubbles v0.21.0 h1:9TdC97SdRVg/1aaXNVWfFH3nnLAwOXr8Fn6u github.com/charmbracelet/bubbles v0.21.0/go.mod h1:HF+v6QUR4HkEpz62dx7ym2xc71/KBHg+zKwJtMw+qtg= github.com/charmbracelet/bubbletea v1.3.10 h1:otUDHWMMzQSB0Pkc87rm691KZ3SWa4KUlvF9nRvCICw= github.com/charmbracelet/bubbletea v1.3.10/go.mod h1:ORQfo0fk8U+po9VaNvnV95UPWA1BitP1E0N6xJPlHr4= -github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs= -github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk= +github.com/charmbracelet/colorprofile v0.4.1 h1:a1lO03qTrSIRaK8c3JRxJDZOvhvIeSco3ej+ngLk1kk= +github.com/charmbracelet/colorprofile v0.4.1/go.mod h1:U1d9Dljmdf9DLegaJ0nGZNJvoXAhayhmidOdcBwAvKk= github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY= github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30= -github.com/charmbracelet/x/ansi v0.10.1 h1:rL3Koar5XvX0pHGfovN03f5cxLbCF2YvLeyz7D2jVDQ= -github.com/charmbracelet/x/ansi v0.10.1/go.mod h1:3RQDQ6lDnROptfpWuUVIUG64bD2g2BgntdxH0Ya5TeE= -github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd h1:vy0GVL4jeHEwG5YOXDmi86oYw2yuYUGqz6a8sLwg0X8= -github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs= +github.com/charmbracelet/x/ansi v0.11.3 h1:6DcVaqWI82BBVM/atTyq6yBoRLZFBsnoDoX9GCu2YOI= +github.com/charmbracelet/x/ansi v0.11.3/go.mod h1:yI7Zslym9tCJcedxz5+WBq+eUGMJT0bM06Fqy1/Y4dI= +github.com/charmbracelet/x/cellbuf v0.0.14 h1:iUEMryGyFTelKW3THW4+FfPgi4fkmKnnaLOXuc+/Kj4= +github.com/charmbracelet/x/cellbuf v0.0.14/go.mod h1:P447lJl49ywBbil/KjCk2HexGh4tEY9LH0/1QrZZ9rA= github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91 h1:payRxjMjKgx2PaCWLZ4p3ro9y97+TVLZNaRZgJwSVDQ= github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91/go.mod h1:wDlXFlCrmJ8J+swcL/MnGUuYnqgQdW9rhSD61oNMb6U= -github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ= -github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg= +github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk= +github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI= +github.com/clipperhouse/displaywidth v0.6.2 h1:ZDpTkFfpHOKte4RG5O/BOyf3ysnvFswpyYrV7z2uAKo= +github.com/clipperhouse/displaywidth v0.6.2/go.mod h1:R+kHuzaYWFkTm7xoMmK1lFydbci4X2CicfbGstSGg0o= +github.com/clipperhouse/stringish v0.1.1 h1:+NSqMOr3GR6k1FdRhhnXrLfztGzuG+VuFDfatpWHKCs= +github.com/clipperhouse/stringish v0.1.1/go.mod h1:v/WhFtE1q0ovMta2+m+UbpZ+2/HEXNWYXQgCt4hdOzA= +github.com/clipperhouse/uax29/v2 v2.3.0 h1:SNdx9DVUqMoBuBoW3iLOj4FQv3dN5mDtuqwuhIGpJy4= +github.com/clipperhouse/uax29/v2 v2.3.0/go.mod h1:Wn1g7MK6OoeDT0vL+Q0SQLDz/KpfsVRgg6W7ihQeh4g= 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/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4= @@ -48,18 +56,18 @@ github.com/libdns/cloudflare v0.2.2 h1:XWHv+C1dDcApqazlh08Q6pjytYLgR2a+Y3xrXFu0v github.com/libdns/cloudflare v0.2.2/go.mod h1:w9uTmRCDlAoafAsTPnn2nJ0XHK/eaUMh86DUk8BWi60= github.com/libdns/libdns v1.1.1 h1:wPrHrXILoSHKWJKGd0EiAVmiJbFShguILTg9leS/P/U= github.com/libdns/libdns v1.1.1/go.mod h1:4Bj9+5CQiNMVGf87wjX4CY3HQJypUHRuLvlsfsZqLWQ= -github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= -github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= +github.com/lucasb-eyer/go-colorful v1.3.0 h1:2/yBRLdWBZKrf7gB40FoiKfAWYQ0lqNcbuQwVHXptag= +github.com/lucasb-eyer/go-colorful v1.3.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4= github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88= -github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc= -github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= -github.com/mholt/acmez/v3 v3.1.3 h1:gUl789rjbJSuM5hYzOFnNaGgWPV1xVfnOs59o0dZEcc= -github.com/mholt/acmez/v3 v3.1.3/go.mod h1:L1wOU06KKvq7tswuMDwKdcHeKpFFgkppZy/y0DFxagQ= -github.com/miekg/dns v1.1.68 h1:jsSRkNozw7G/mnmXULynzMNIsgY2dHC8LO6U6Ij2JEA= -github.com/miekg/dns v1.1.68/go.mod h1:fujopn7TB3Pu3JM69XaawiU0wqjpL9/8xGop5UrTPps= +github.com/mattn/go-runewidth v0.0.19 h1:v++JhqYnZuu5jSKrk9RbgF5v4CGUjqRfBm05byFGLdw= +github.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs= +github.com/mholt/acmez/v3 v3.1.4 h1:DyzZe/RnAzT3rpZj/2Ii5xZpiEvvYk3cQEN/RmqxwFQ= +github.com/mholt/acmez/v3 v3.1.4/go.mod h1:L1wOU06KKvq7tswuMDwKdcHeKpFFgkppZy/y0DFxagQ= +github.com/miekg/dns v1.1.69 h1:Kb7Y/1Jo+SG+a2GtfoFUfDkG//csdRPwRLkCsxDG9Sc= +github.com/miekg/dns v1.1.69/go.mod h1:7OyjD9nEba5OkqQ/hB4fy3PIoxafSZJtducccIelz3g= github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI= github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo= github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA= @@ -68,7 +76,6 @@ github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk= 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/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= github.com/sahilm/fuzzy v0.1.1 h1:ceu5RHF8DGgoi+/dR5PsECjCDH1BE3Fnmpo7aVXOdRA= @@ -99,18 +106,18 @@ go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= -go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8= -go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= +go.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc= +go.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= go.uber.org/zap/exp v0.3.0 h1:6JYzdifzYkGmTdRR59oYH+Ng7k49H9qVpWwNSsGJj3U= go.uber.org/zap/exp v0.3.0/go.mod h1:5I384qq7XGxYyByIhHm6jg5CHkGY0nsTfbDLgDDlgJQ= golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU= golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0= -golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561 h1:MDc5xs78ZrZr3HMQugiXOAkSZtfTpbJLDr/lwfgO53E= -golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561/go.mod h1:cyybsKvd6eL0RnXn6p/Grxp8F5bW7iYuBgsNCOHpMYE= -golang.org/x/mod v0.30.0 h1:fDEXFVZ/fmCKProc/yAXXUijritrDzahmwwefnjoPFk= -golang.org/x/mod v0.30.0/go.mod h1:lAsf5O2EvJeSFMiBxXDki7sCgAxEUcZHXoXMKT4GJKc= -golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY= -golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU= +golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI= +golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo= +golang.org/x/mod v0.31.0 h1:HaW9xtz0+kOcWKwli0ZXy79Ix+UW/vOfmWI5QVd2tgI= +golang.org/x/mod v0.31.0/go.mod h1:43JraMp9cGx1Rx3AqioxrbrhNsLl2l/iNAvuBkrezpg= +golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU= +golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY= golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4= golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -121,12 +128,12 @@ golang.org/x/term v0.38.0 h1:PQ5pkm/rLO6HnxFR7N2lJHOZX6Kez5Y1gDSJla6jo7Q= golang.org/x/term v0.38.0/go.mod h1:bSEAKrOT1W+VSu9TSCMtoGEOUcKxOKgl3LE5QEF/xVg= golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU= golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY= -golang.org/x/tools v0.39.0 h1:ik4ho21kwuQln40uelmciQPp9SipgNDdrafrYA4TmQQ= -golang.org/x/tools v0.39.0/go.mod h1:JnefbkDPyD8UU2kI5fuf8ZX4/yUeh9W877ZeBONxUqQ= +golang.org/x/tools v0.40.0 h1:yLkxfA+Qnul4cs9QA3KnlFu0lVmd8JJfoq+E41uSutA= +golang.org/x/tools v0.40.0/go.mod h1:Ik/tzLRlbscWpqqMRjyWYDisX8bG13FrdXp3o4Sr9lc= gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk= gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E= -google.golang.org/genproto/googleapis/rpc v0.0.0-20251029180050-ab9386a59fda h1:i/Q+bfisr7gq6feoJnS/DlpdwEL4ihp41fvRiM3Ork0= -google.golang.org/genproto/googleapis/rpc v0.0.0-20251029180050-ab9386a59fda/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk= +google.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b h1:Mv8VFug0MP9e5vUxfBcE3vUkV6CImK3cMNMIDFjmzxU= +google.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ= google.golang.org/grpc v1.78.0 h1:K1XZG/yGDJnzMdd/uZHAkVqJE+xIDOcmdSFZkBUicNc= google.golang.org/grpc v1.78.0/go.mod h1:I47qjTo4OKbMkjA/aOOwxDIiPSBofUtQUI5EfpWvW7U= google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= From 5edb3c8086b005d5b14d66415fde59a381ecef5f Mon Sep 17 00:00:00 2001 From: bagas Date: Sun, 4 Jan 2026 15:19:03 +0700 Subject: [PATCH 07/15] fix: startup order --- internal/grpc/client/client.go | 47 ++++++++++++----------- main.go | 68 ++++++++++++++++++++-------------- 2 files changed, 64 insertions(+), 51 deletions(-) diff --git a/internal/grpc/client/client.go b/internal/grpc/client/client.go index 0883a86..f056ad7 100644 --- a/internal/grpc/client/client.go +++ b/internal/grpc/client/client.go @@ -42,6 +42,7 @@ type Client struct { slugService proto.SlugChangeClient eventService proto.EventServiceClient authorizeConnectionService proto.UserServiceClient + closing bool } func DefaultConfig() *GrpcConfig { @@ -155,16 +156,17 @@ func (c *Client) SubscribeEvents(ctx context.Context, identity, authToken string for { subscribe, err := c.eventService.Subscribe(ctx) if err != nil { - if !isConnectionError(err) { + if errors.Is(err, context.Canceled) || status.Code(err) == codes.Canceled || ctx.Err() != nil { return err } - if status.Code(err) == codes.Unauthenticated { + if !c.isConnectionError(err) || status.Code(err) == codes.Unauthenticated { return err } - if err := wait(); err != nil { + if err = wait(); err != nil { return err } growBackoff() + log.Printf("Reconnect to controller within %v sec", backoff.Seconds()) continue } @@ -180,8 +182,8 @@ func (c *Client) SubscribeEvents(ctx context.Context, identity, authToken string if err != nil { log.Println("Authentication failed to send to gRPC server:", err) - if isConnectionError(err) { - if err := wait(); err != nil { + if c.isConnectionError(err) { + if err = wait(); err != nil { return err } growBackoff() @@ -193,9 +195,13 @@ func (c *Client) SubscribeEvents(ctx context.Context, identity, authToken string backoff = baseBackoff if err = c.processEventStream(subscribe); err != nil { - if isConnectionError(err) { + if errors.Is(err, context.Canceled) || status.Code(err) == codes.Canceled || ctx.Err() != nil { + return err + } + if c.isConnectionError(err) { log.Printf("Reconnect to controller within %v sec", backoff.Seconds()) - if err := wait(); err != nil { + if err = wait(); err != nil { + fmt.Println(err) return err } growBackoff() @@ -210,16 +216,7 @@ func (c *Client) processEventStream(subscribe grpc.BidiStreamingClient[proto.Nod for { recv, err := subscribe.Recv() if err != nil { - if isConnectionError(err) { - log.Printf("connection error receiving from gRPC server: %v", err) - return err - } - if status.Code(err) == codes.Unauthenticated { - log.Printf("Authentication failed: %v", err) - return err - } - log.Printf("non-connection receive error from gRPC server: %v", err) - continue + return err } switch recv.GetType() { case proto.EventType_SLUG_CHANGE: @@ -237,8 +234,7 @@ func (c *Client) processEventStream(subscribe grpc.BidiStreamingClient[proto.Nod }, }) if errSend != nil { - if isConnectionError(errSend) { - log.Printf("connection error sending slug change failure: %v", errSend) + if c.isConnectionError(errSend) { return errSend } log.Printf("non-connection send error for slug change failure: %v", errSend) @@ -257,8 +253,7 @@ func (c *Client) processEventStream(subscribe grpc.BidiStreamingClient[proto.Nod }, }) if errSend != nil { - if isConnectionError(errSend) { - log.Printf("connection error sending slug change failure: %v", errSend) + if c.isConnectionError(errSend) { return errSend } log.Printf("non-connection send error for slug change failure: %v", errSend) @@ -276,7 +271,7 @@ func (c *Client) processEventStream(subscribe grpc.BidiStreamingClient[proto.Nod }, }) if err != nil { - if isConnectionError(err) { + if c.isConnectionError(err) { log.Printf("connection error sending slug change success: %v", err) return err } @@ -306,7 +301,7 @@ func (c *Client) processEventStream(subscribe grpc.BidiStreamingClient[proto.Nod }, }) if err != nil { - if isConnectionError(err) { + if c.isConnectionError(err) { log.Printf("connection error sending sessions success: %v", err) return err } @@ -338,6 +333,7 @@ func (c *Client) AuthorizeConn(ctx context.Context, token string) (authorized bo func (c *Client) Close() error { if c.conn != nil { log.Printf("Closing gRPC connection to %s", c.config.Address) + c.closing = true return c.conn.Close() } return nil @@ -361,7 +357,10 @@ func (c *Client) GetConfig() *GrpcConfig { return c.config } -func isConnectionError(err error) bool { +func (c *Client) isConnectionError(err error) bool { + if c.closing { + return false + } if err == nil { return false } diff --git a/main.go b/main.go index 36ec8ca..e069f7c 100644 --- a/main.go +++ b/main.go @@ -7,7 +7,9 @@ import ( "net/http" _ "net/http/pprof" "os" + "os/signal" "strings" + "syscall" "time" "tunnel_pls/internal/config" "tunnel_pls/internal/grpc/client" @@ -68,10 +70,14 @@ func main() { sshConfig.AddHostKey(private) sessionRegistry := session.NewRegistry() - var grpcClient *client.Client - var cancel context.CancelFunc = func() {} - var ctx context.Context = context.Background() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + errChan := make(chan error, 2) + shutdownChan := make(chan os.Signal, 1) + signal.Notify(shutdownChan, os.Interrupt, syscall.SIGTERM) + + var grpcClient *client.Client if isNodeMode { grpcHost := config.Getenv("GRPC_ADDRESS", "localhost") grpcPort := config.Getenv("GRPC_PORT", "8080") @@ -79,10 +85,9 @@ func main() { nodeToken := config.Getenv("NODE_TOKEN", "") if nodeToken == "" { log.Fatalf("NODE_TOKEN is required in node mode") - return } - - grpcClient, err = client.New(&client.GrpcConfig{ + + c, err := client.New(&client.GrpcConfig{ Address: grpcAddr, UseTLS: false, InsecureSkipVerify: false, @@ -91,37 +96,46 @@ func main() { MaxRetries: 3, }, sessionRegistry) if err != nil { - return + log.Fatalf("failed to create grpc client: %v", err) } - defer func(grpcClient *client.Client) { - err := grpcClient.Close() - if err != nil { + grpcClient = c - } - }(grpcClient) - - ctx, cancel = context.WithTimeout(context.Background(), time.Second*5) - err = grpcClient.CheckServerHealth(ctx) - if err != nil { - log.Fatalf("gRPC health check failed: %s", err) - return + healthCtx, healthCancel := context.WithTimeout(ctx, 5*time.Second) + if err := grpcClient.CheckServerHealth(healthCtx); err != nil { + healthCancel() + log.Fatalf("gRPC health check failed: %v", err) } - cancel() + healthCancel() - ctx, cancel = context.WithCancel(context.Background()) go func() { identity := config.Getenv("DOMAIN", "localhost") - err = grpcClient.SubscribeEvents(ctx, identity, nodeToken) - if err != nil { - return + if err := grpcClient.SubscribeEvents(ctx, identity, nodeToken); err != nil { + errChan <- fmt.Errorf("failed to subscribe to events: %w", err) } }() } - app, err := server.NewServer(sshConfig, sessionRegistry, grpcClient) - if err != nil { - log.Fatalf("Failed to start server: %s", err) + go func() { + app, err := server.NewServer(sshConfig, sessionRegistry, grpcClient) + if err != nil { + errChan <- fmt.Errorf("failed to start server: %s", err) + return + } + app.Start() + }() + + select { + case err := <-errChan: + log.Printf("error happen : %s", err) + case sig := <-shutdownChan: + log.Printf("received signal %s, shutting down", sig) } - app.Start() + cancel() + + if grpcClient != nil { + if err := grpcClient.Close(); err != nil { + log.Printf("failed to close grpc conn : %s", err) + } + } } From d666ae55451cef143bd389fab9d9326e637564ef Mon Sep 17 00:00:00 2001 From: bagas Date: Sun, 4 Jan 2026 18:21:34 +0700 Subject: [PATCH 08/15] fix: use correct environment variable key --- internal/grpc/client/client.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/grpc/client/client.go b/internal/grpc/client/client.go index f056ad7..1aad1d2 100644 --- a/internal/grpc/client/client.go +++ b/internal/grpc/client/client.go @@ -284,7 +284,7 @@ func (c *Client) processEventStream(subscribe grpc.BidiStreamingClient[proto.Nod for _, ses := range sessions { detail := ses.Detail() details = append(details, &proto.Detail{ - Node: config.Getenv("domain", "localhost"), + Node: config.Getenv("DOMAIN", "localhost"), ForwardingType: detail.ForwardingType, Slug: detail.Slug, UserId: detail.UserID, From 8cc70fa45ef47b39ead15240211be5249d913d94 Mon Sep 17 00:00:00 2001 From: bagas Date: Mon, 5 Jan 2026 00:50:42 +0700 Subject: [PATCH 09/15] feat(session): use session key for registry --- internal/grpc/client/client.go | 18 ++++++-- server/http.go | 6 ++- server/https.go | 6 ++- server/server.go | 1 - session/handler.go | 28 +++++++++++-- session/lifecycle/lifecycle.go | 11 ++--- session/registry.go | 77 ++++++++++++++++++++-------------- session/session.go | 11 ++++- types/types.go | 5 +++ 9 files changed, 114 insertions(+), 49 deletions(-) diff --git a/internal/grpc/client/client.go b/internal/grpc/client/client.go index 1aad1d2..79c1113 100644 --- a/internal/grpc/client/client.go +++ b/internal/grpc/client/client.go @@ -9,6 +9,7 @@ import ( "log" "time" "tunnel_pls/internal/config" + "tunnel_pls/types" "tunnel_pls/session" @@ -201,7 +202,6 @@ func (c *Client) SubscribeEvents(ctx context.Context, identity, authToken string if c.isConnectionError(err) { log.Printf("Reconnect to controller within %v sec", backoff.Seconds()) if err = wait(); err != nil { - fmt.Println(err) return err } growBackoff() @@ -222,7 +222,11 @@ func (c *Client) processEventStream(subscribe grpc.BidiStreamingClient[proto.Nod case proto.EventType_SLUG_CHANGE: oldSlug := recv.GetSlugEvent().GetOld() newSlug := recv.GetSlugEvent().GetNew() - sess, err := c.sessionRegistry.Get(oldSlug) + var userSession *session.SSHSession + userSession, err = c.sessionRegistry.Get(types.SessionKey{ + Id: oldSlug, + Type: types.HTTP, + }) if err != nil { errSend := subscribe.Send(&proto.Node{ Type: proto.EventType_SLUG_CHANGE_RESPONSE, @@ -241,7 +245,13 @@ func (c *Client) processEventStream(subscribe grpc.BidiStreamingClient[proto.Nod } continue } - err = c.sessionRegistry.Update(oldSlug, newSlug) + err = c.sessionRegistry.Update(types.SessionKey{ + Id: oldSlug, + Type: types.HTTP, + }, types.SessionKey{ + Id: newSlug, + Type: types.HTTP, + }) if err != nil { errSend := subscribe.Send(&proto.Node{ Type: proto.EventType_SLUG_CHANGE_RESPONSE, @@ -260,7 +270,7 @@ func (c *Client) processEventStream(subscribe grpc.BidiStreamingClient[proto.Nod } continue } - sess.GetInteraction().Redraw() + userSession.GetInteraction().Redraw() err = subscribe.Send(&proto.Node{ Type: proto.EventType_SLUG_CHANGE_RESPONSE, Payload: &proto.Node_SlugEventResponse{ diff --git a/server/http.go b/server/http.go index 8add118..2420686 100644 --- a/server/http.go +++ b/server/http.go @@ -13,6 +13,7 @@ import ( "time" "tunnel_pls/internal/config" "tunnel_pls/session" + "tunnel_pls/types" "golang.org/x/crypto/ssh" ) @@ -313,7 +314,10 @@ func (hs *httpServer) handler(conn net.Conn) { return } - sshSession, err := hs.sessionRegistry.Get(slug) + sshSession, err := hs.sessionRegistry.Get(types.SessionKey{ + Id: slug, + Type: types.HTTP, + }) if err != nil { _, err = conn.Write([]byte("HTTP/1.1 301 Moved Permanently\r\n" + fmt.Sprintf("Location: https://tunnl.live/tunnel-not-found?slug=%s\r\n", slug) + diff --git a/server/https.go b/server/https.go index 3c502a5..2758172 100644 --- a/server/https.go +++ b/server/https.go @@ -9,6 +9,7 @@ import ( "net" "strings" "tunnel_pls/internal/config" + "tunnel_pls/types" ) func (hs *httpServer) ListenAndServeTLS() error { @@ -89,7 +90,10 @@ func (hs *httpServer) handlerTLS(conn net.Conn) { return } - sshSession, err := hs.sessionRegistry.Get(slug) + sshSession, err := hs.sessionRegistry.Get(types.SessionKey{ + Id: slug, + Type: types.HTTP, + }) if err != nil { _, err = conn.Write([]byte("HTTP/1.1 301 Moved Permanently\r\n" + fmt.Sprintf("Location: https://tunnl.live/tunnel-not-found?slug=%s\r\n", slug) + diff --git a/server/server.go b/server/server.go index 0ee111c..9439d90 100644 --- a/server/server.go +++ b/server/server.go @@ -88,7 +88,6 @@ func (s *Server) handleConnection(conn net.Conn) { _, u, _ := s.grpcClient.AuthorizeConn(ctx, sshConn.User()) user = u } - sshSession := session.New(sshConn, forwardingReqs, chans, s.sessionRegistry, user) err = sshSession.Start() if err != nil { diff --git a/session/handler.go b/session/handler.go index 30458fb..ca080d8 100644 --- a/session/handler.go +++ b/session/handler.go @@ -164,8 +164,9 @@ func (s *SSHSession) HandleTCPIPForward(req *ssh.Request) { func (s *SSHSession) HandleHTTPForward(req *ssh.Request, portToBind uint16) { slug := random.GenerateRandomString(20) + key := types.SessionKey{Id: slug, Type: types.HTTP} - if !s.registry.Register(slug, s) { + if !s.registry.Register(key, s) { log.Printf("Failed to register client with slug: %s", slug) err := req.Reply(false, nil) if err != nil { @@ -178,7 +179,7 @@ func (s *SSHSession) HandleHTTPForward(req *ssh.Request, portToBind uint16) { err := binary.Write(buf, binary.BigEndian, uint32(portToBind)) if err != nil { log.Println("Failed to write port to buffer:", err) - s.registry.Remove(slug) + s.registry.Remove(key) err = req.Reply(false, nil) if err != nil { log.Println("Failed to reply to request:", err) @@ -190,7 +191,7 @@ func (s *SSHSession) HandleHTTPForward(req *ssh.Request, portToBind uint16) { err = req.Reply(true, buf.Bytes()) if err != nil { log.Println("Failed to reply to request:", err) - s.registry.Remove(slug) + s.registry.Remove(key) err = req.Reply(false, nil) if err != nil { log.Println("Failed to reply to request:", err) @@ -225,10 +226,29 @@ func (s *SSHSession) HandleTCPForward(req *ssh.Request, addr string, portToBind return } + key := types.SessionKey{Id: fmt.Sprintf("%d", portToBind), Type: types.TCP} + + if !s.registry.Register(key, s) { + log.Printf("Failed to register TCP client with id: %s", key.Id) + if setErr := portUtil.Default.SetPortStatus(portToBind, false); setErr != nil { + log.Printf("Failed to reset port status: %v", setErr) + } + if closeErr := listener.Close(); closeErr != nil { + log.Printf("Failed to close listener: %s", closeErr) + } + err = req.Reply(false, nil) + if err != nil { + log.Println("Failed to reply to request:", err) + } + _ = s.lifecycle.Close() + return + } + buf := new(bytes.Buffer) err = binary.Write(buf, binary.BigEndian, uint32(portToBind)) if err != nil { log.Println("Failed to write port to buffer:", err) + s.registry.Remove(key) if setErr := portUtil.Default.SetPortStatus(portToBind, false); setErr != nil { log.Printf("Failed to reset port status: %v", setErr) } @@ -244,6 +264,7 @@ func (s *SSHSession) HandleTCPForward(req *ssh.Request, addr string, portToBind err = req.Reply(true, buf.Bytes()) if err != nil { log.Println("Failed to reply to request:", err) + s.registry.Remove(key) if setErr := portUtil.Default.SetPortStatus(portToBind, false); setErr != nil { log.Printf("Failed to reset port status: %v", setErr) } @@ -258,6 +279,7 @@ func (s *SSHSession) HandleTCPForward(req *ssh.Request, addr string, portToBind s.forwarder.SetType(types.TCP) s.forwarder.SetListener(listener) s.forwarder.SetForwardedPort(portToBind) + s.slugManager.Set(key.Id) s.lifecycle.SetStatus(types.RUNNING) go s.forwarder.AcceptTCPConnections() s.interaction.Start() diff --git a/session/lifecycle/lifecycle.go b/session/lifecycle/lifecycle.go index f2dea50..ea96081 100644 --- a/session/lifecycle/lifecycle.go +++ b/session/lifecycle/lifecycle.go @@ -25,7 +25,7 @@ type Lifecycle struct { channel ssh.Channel forwarder Forwarder slugManager slug.Manager - unregisterClient func(slug string) + unregisterClient func(key types.SessionKey) startedAt time.Time } @@ -41,7 +41,7 @@ func NewLifecycle(conn ssh.Conn, forwarder Forwarder, slugManager slug.Manager) } } -func (l *Lifecycle) SetUnregisterClient(unregisterClient func(slug string)) { +func (l *Lifecycle) SetUnregisterClient(unregisterClient func(key types.SessionKey)) { l.unregisterClient = unregisterClient } @@ -51,7 +51,7 @@ type SessionLifecycle interface { GetConnection() ssh.Conn GetChannel() ssh.Channel SetChannel(channel ssh.Channel) - SetUnregisterClient(unregisterClient func(slug string)) + SetUnregisterClient(unregisterClient func(key types.SessionKey)) IsActive() bool StartedAt() time.Time } @@ -94,8 +94,9 @@ func (l *Lifecycle) Close() error { } clientSlug := l.slugManager.Get() - if clientSlug != "" { - l.unregisterClient(clientSlug) + if clientSlug != "" && l.unregisterClient != nil { + key := types.SessionKey{Id: clientSlug, Type: l.forwarder.GetTunnelType()} + l.unregisterClient(key) } if l.forwarder.GetTunnelType() == types.TCP { diff --git a/session/registry.go b/session/registry.go index b6f655d..6a607f9 100644 --- a/session/registry.go +++ b/session/registry.go @@ -3,96 +3,109 @@ package session import ( "fmt" "sync" + "tunnel_pls/types" ) +type Key = types.SessionKey + type Registry interface { - Get(slug string) (session *SSHSession, err error) - Update(oldSlug, newSlug string) error - Register(slug string, session *SSHSession) (success bool) - Remove(slug string) + Get(key Key) (session *SSHSession, err error) + Update(oldKey, newKey Key) error + Register(key Key, session *SSHSession) (success bool) + Remove(key Key) GetAllSessionFromUser(user string) []*SSHSession } type registry struct { mu sync.RWMutex - byUser map[string]map[string]*SSHSession - slugIndex map[string]string + byUser map[string]map[Key]*SSHSession + slugIndex map[Key]string } func NewRegistry() Registry { return ®istry{ - byUser: make(map[string]map[string]*SSHSession), - slugIndex: make(map[string]string), + byUser: make(map[string]map[Key]*SSHSession), + slugIndex: make(map[Key]string), } } -func (r *registry) Get(slug string) (session *SSHSession, err error) { +func (r *registry) Get(key Key) (session *SSHSession, err error) { r.mu.RLock() defer r.mu.RUnlock() - userID, ok := r.slugIndex[slug] + userID, ok := r.slugIndex[key] if !ok { return nil, fmt.Errorf("session not found") } - client, ok := r.byUser[userID][slug] + client, ok := r.byUser[userID][key] if !ok { return nil, fmt.Errorf("session not found") } return client, nil } -func (r *registry) Update(oldSlug, newSlug string) error { - if isForbiddenSlug(newSlug) { +func (r *registry) Update(oldKey, newKey Key) error { + if oldKey.Type != newKey.Type { + return fmt.Errorf("tunnel type cannot change") + } + + if newKey.Type != types.HTTP { + return fmt.Errorf("non http tunnel cannot change slug") + } + + if isForbiddenSlug(newKey.Id) { return fmt.Errorf("this subdomain is reserved. Please choose a different one") - } else if !isValidSlug(newSlug) { + } + + if !isValidSlug(newKey.Id) { return fmt.Errorf("invalid subdomain. Follow the rules") } r.mu.Lock() defer r.mu.Unlock() - userID, ok := r.slugIndex[oldSlug] + userID, ok := r.slugIndex[oldKey] if !ok { return fmt.Errorf("session not found") } - if _, exists := r.slugIndex[newSlug]; exists && newSlug != oldSlug { + if _, exists := r.slugIndex[newKey]; exists && newKey != oldKey { return fmt.Errorf("someone already uses this subdomain") } - client, ok := r.byUser[userID][oldSlug] + client, ok := r.byUser[userID][oldKey] if !ok { return fmt.Errorf("session not found") } - delete(r.byUser[userID], oldSlug) - delete(r.slugIndex, oldSlug) + delete(r.byUser[userID], oldKey) + delete(r.slugIndex, oldKey) - client.slugManager.Set(newSlug) - r.slugIndex[newSlug] = userID + client.slugManager.Set(newKey.Id) + r.slugIndex[newKey] = userID if r.byUser[userID] == nil { - r.byUser[userID] = make(map[string]*SSHSession) + r.byUser[userID] = make(map[Key]*SSHSession) } - r.byUser[userID][newSlug] = client + r.byUser[userID][newKey] = client return nil } -func (r *registry) Register(slug string, session *SSHSession) (success bool) { +func (r *registry) Register(key Key, session *SSHSession) (success bool) { r.mu.Lock() defer r.mu.Unlock() - if _, exists := r.slugIndex[slug]; exists { + if _, exists := r.slugIndex[key]; exists { return false } userID := session.userID if r.byUser[userID] == nil { - r.byUser[userID] = make(map[string]*SSHSession) + r.byUser[userID] = make(map[Key]*SSHSession) } - r.byUser[userID][slug] = session - r.slugIndex[slug] = userID + r.byUser[userID][key] = session + r.slugIndex[key] = userID return true } @@ -112,20 +125,20 @@ func (r *registry) GetAllSessionFromUser(user string) []*SSHSession { return sessions } -func (r *registry) Remove(slug string) { +func (r *registry) Remove(key Key) { r.mu.Lock() defer r.mu.Unlock() - userID, ok := r.slugIndex[slug] + userID, ok := r.slugIndex[key] if !ok { return } - delete(r.byUser[userID], slug) + delete(r.byUser[userID], key) if len(r.byUser[userID]) == 0 { delete(r.byUser, userID) } - delete(r.slugIndex, slug) + delete(r.slugIndex, key) } func isValidSlug(slug string) bool { diff --git a/session/session.go b/session/session.go index 45d497a..d406160 100644 --- a/session/session.go +++ b/session/session.go @@ -9,6 +9,7 @@ import ( "tunnel_pls/session/interaction" "tunnel_pls/session/lifecycle" "tunnel_pls/session/slug" + "tunnel_pls/types" "golang.org/x/crypto/ssh" ) @@ -54,9 +55,15 @@ func New(conn *ssh.ServerConn, forwardingReq <-chan *ssh.Request, sshChan <-chan lifecycleManager := lifecycle.NewLifecycle(conn, forwarderManager, slugManager) interactionManager.SetLifecycle(lifecycleManager) - interactionManager.SetSlugModificator(sessionRegistry.Update) + interactionManager.SetSlugModificator(func(oldSlug, newSlug string) error { + oldKey := types.SessionKey{Id: oldSlug, Type: forwarderManager.GetTunnelType()} + newKey := types.SessionKey{Id: newSlug, Type: forwarderManager.GetTunnelType()} + return sessionRegistry.Update(oldKey, newKey) + }) forwarderManager.SetLifecycle(lifecycleManager) - lifecycleManager.SetUnregisterClient(sessionRegistry.Remove) + lifecycleManager.SetUnregisterClient(func(key types.SessionKey) { + sessionRegistry.Remove(key) + }) return &SSHSession{ initialReq: forwardingReq, diff --git a/types/types.go b/types/types.go index f909da5..5c4eece 100644 --- a/types/types.go +++ b/types/types.go @@ -15,6 +15,11 @@ const ( TCP TunnelType = "TCP" ) +type SessionKey struct { + Id string + Type TunnelType +} + var BadGatewayResponse = []byte("HTTP/1.1 502 Bad Gateway\r\n" + "Content-Length: 11\r\n" + "Content-Type: text/plain\r\n\r\n" + From 6de0a618eea6865f6d230006dae758657090e2a7 Mon Sep 17 00:00:00 2001 From: bagas Date: Mon, 5 Jan 2026 00:55:51 +0700 Subject: [PATCH 10/15] update: proto file to v1.3.0 --- go.mod | 2 +- go.sum | 4 ++-- internal/grpc/client/client.go | 3 --- 3 files changed, 3 insertions(+), 6 deletions(-) diff --git a/go.mod b/go.mod index e169929..ae797c0 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module tunnel_pls go 1.25.5 require ( - git.fossy.my.id/bagas/tunnel-please-grpc v1.2.0 + git.fossy.my.id/bagas/tunnel-please-grpc v1.3.0 github.com/caddyserver/certmagic v0.25.0 github.com/charmbracelet/bubbles v0.21.0 github.com/charmbracelet/bubbletea v1.3.10 diff --git a/go.sum b/go.sum index ff64d7e..1ce04dc 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,5 @@ -git.fossy.my.id/bagas/tunnel-please-grpc v1.2.0 h1:BS1dJU3wa2ILgTGwkV95Knle0il0OQtErGqyb6xV7SU= -git.fossy.my.id/bagas/tunnel-please-grpc v1.2.0/go.mod h1:fG+VkArdkceGB0bNA7IFQus9GetLAwdF5Oi4jdMlXtY= +git.fossy.my.id/bagas/tunnel-please-grpc v1.3.0 h1:RhcBKUG41/om4jgN+iF/vlY/RojTeX1QhBa4p4428ec= +git.fossy.my.id/bagas/tunnel-please-grpc v1.3.0/go.mod h1:fG+VkArdkceGB0bNA7IFQus9GetLAwdF5Oi4jdMlXtY= github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= diff --git a/internal/grpc/client/client.go b/internal/grpc/client/client.go index 79c1113..2243951 100644 --- a/internal/grpc/client/client.go +++ b/internal/grpc/client/client.go @@ -40,7 +40,6 @@ type Client struct { conn *grpc.ClientConn config *GrpcConfig sessionRegistry session.Registry - slugService proto.SlugChangeClient eventService proto.EventServiceClient authorizeConnectionService proto.UserServiceClient closing bool @@ -115,14 +114,12 @@ func New(config *GrpcConfig, sessionRegistry session.Registry) (*Client, error) return nil, fmt.Errorf("failed to connect to gRPC server at %s: %w", config.Address, err) } - slugService := proto.NewSlugChangeClient(conn) eventService := proto.NewEventServiceClient(conn) authorizeConnectionService := proto.NewUserServiceClient(conn) return &Client{ conn: conn, config: config, - slugService: slugService, sessionRegistry: sessionRegistry, eventService: eventService, authorizeConnectionService: authorizeConnectionService, From 4ffaec9d9a6ce678c4859fbb9d41c56e10c3282f Mon Sep 17 00:00:00 2001 From: bagas Date: Mon, 5 Jan 2026 16:44:03 +0700 Subject: [PATCH 11/15] refactor: inject SessionRegistry interface instead of individual functions --- go.mod | 4 +-- go.sum | 2 ++ internal/grpc/client/client.go | 3 +- session/interaction/interaction.go | 55 ++++++++++++++++++------------ session/lifecycle/lifecycle.go | 55 ++++++++++++++++++------------ session/registry.go | 24 +++++-------- session/session.go | 19 +++-------- 7 files changed, 86 insertions(+), 76 deletions(-) diff --git a/go.mod b/go.mod index ae797c0..fe62062 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module tunnel_pls go 1.25.5 require ( - git.fossy.my.id/bagas/tunnel-please-grpc v1.3.0 + git.fossy.my.id/bagas/tunnel-please-grpc v1.4.0 github.com/caddyserver/certmagic v0.25.0 github.com/charmbracelet/bubbles v0.21.0 github.com/charmbracelet/bubbletea v1.3.10 @@ -52,4 +52,4 @@ require ( golang.org/x/text v0.32.0 // indirect golang.org/x/tools v0.40.0 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b // indirect -) +) \ No newline at end of file diff --git a/go.sum b/go.sum index 1ce04dc..d477230 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,7 @@ git.fossy.my.id/bagas/tunnel-please-grpc v1.3.0 h1:RhcBKUG41/om4jgN+iF/vlY/RojTeX1QhBa4p4428ec= git.fossy.my.id/bagas/tunnel-please-grpc v1.3.0/go.mod h1:fG+VkArdkceGB0bNA7IFQus9GetLAwdF5Oi4jdMlXtY= +git.fossy.my.id/bagas/tunnel-please-grpc v1.4.0 h1:tpJSKjaSmV+vxxbVx6qnStjxFVXjj2M0rygWXxLb99o= +git.fossy.my.id/bagas/tunnel-please-grpc v1.4.0/go.mod h1:fG+VkArdkceGB0bNA7IFQus9GetLAwdF5Oi4jdMlXtY= github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= diff --git a/internal/grpc/client/client.go b/internal/grpc/client/client.go index 2243951..00eac89 100644 --- a/internal/grpc/client/client.go +++ b/internal/grpc/client/client.go @@ -217,6 +217,7 @@ func (c *Client) processEventStream(subscribe grpc.BidiStreamingClient[proto.Nod } switch recv.GetType() { case proto.EventType_SLUG_CHANGE: + user := recv.GetSlugEvent().GetUser() oldSlug := recv.GetSlugEvent().GetOld() newSlug := recv.GetSlugEvent().GetNew() var userSession *session.SSHSession @@ -242,7 +243,7 @@ func (c *Client) processEventStream(subscribe grpc.BidiStreamingClient[proto.Nod } continue } - err = c.sessionRegistry.Update(types.SessionKey{ + err = c.sessionRegistry.Update(user, types.SessionKey{ Id: oldSlug, Type: types.HTTP, }, types.SessionKey{ diff --git a/session/interaction/interaction.go b/session/interaction/interaction.go index 3a36f4c..99723c0 100644 --- a/session/interaction/interaction.go +++ b/session/interaction/interaction.go @@ -23,15 +23,20 @@ import ( type Lifecycle interface { Close() error + GetUser() string +} + +type SessionRegistry interface { + Update(user string, oldKey, newKey types.SessionKey) error } type Controller interface { SetChannel(channel ssh.Channel) SetLifecycle(lifecycle Lifecycle) - SetSlugModificator(func(oldSlug, newSlug string) error) Start() SetWH(w, h int) Redraw() + SetSessionRegistry(registry SessionRegistry) } type Forwarder interface { @@ -41,14 +46,14 @@ type Forwarder interface { } type Interaction struct { - channel ssh.Channel - slugManager slug.Manager - forwarder Forwarder - lifecycle Lifecycle - updateClientSlug func(oldSlug, newSlug string) error - program *tea.Program - ctx context.Context - cancel context.CancelFunc + channel ssh.Channel + slugManager slug.Manager + forwarder Forwarder + lifecycle Lifecycle + sessionRegistry SessionRegistry + program *tea.Program + ctx context.Context + cancel context.CancelFunc } func (i *Interaction) SetWH(w, h int) { @@ -102,17 +107,21 @@ type tickMsg time.Time func NewInteraction(slugManager slug.Manager, forwarder Forwarder) *Interaction { ctx, cancel := context.WithCancel(context.Background()) return &Interaction{ - channel: nil, - slugManager: slugManager, - forwarder: forwarder, - lifecycle: nil, - updateClientSlug: nil, - program: nil, - ctx: ctx, - cancel: cancel, + channel: nil, + slugManager: slugManager, + forwarder: forwarder, + lifecycle: nil, + sessionRegistry: nil, + program: nil, + ctx: ctx, + cancel: cancel, } } +func (i *Interaction) SetSessionRegistry(registry SessionRegistry) { + i.sessionRegistry = registry +} + func (i *Interaction) SetLifecycle(lifecycle Lifecycle) { i.lifecycle = lifecycle } @@ -121,10 +130,6 @@ func (i *Interaction) SetChannel(channel ssh.Channel) { i.channel = channel } -func (i *Interaction) SetSlugModificator(modificator func(oldSlug, newSlug string) error) { - i.updateClientSlug = modificator -} - func (i *Interaction) Stop() { if i.cancel != nil { i.cancel() @@ -218,7 +223,13 @@ func (m *model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m, tea.Batch(tea.ClearScreen, textinput.Blink) case "enter": inputValue := m.slugInput.Value() - if err := m.interaction.updateClientSlug(m.interaction.slugManager.Get(), inputValue); err != nil { + if err := m.interaction.sessionRegistry.Update(m.interaction.lifecycle.GetUser(), types.SessionKey{ + Id: m.interaction.slugManager.Get(), + Type: types.HTTP, + }, types.SessionKey{ + Id: inputValue, + Type: types.HTTP, + }); err != nil { m.slugError = err.Error() return m, nil } diff --git a/session/lifecycle/lifecycle.go b/session/lifecycle/lifecycle.go index ea96081..ccc01f0 100644 --- a/session/lifecycle/lifecycle.go +++ b/session/lifecycle/lifecycle.go @@ -19,30 +19,36 @@ type Forwarder interface { GetForwardedPort() uint16 } -type Lifecycle struct { - status types.Status - conn ssh.Conn - channel ssh.Channel - forwarder Forwarder - slugManager slug.Manager - unregisterClient func(key types.SessionKey) - startedAt time.Time +type SessionRegistry interface { + Remove(key types.SessionKey) } -func NewLifecycle(conn ssh.Conn, forwarder Forwarder, slugManager slug.Manager) *Lifecycle { +type Lifecycle struct { + status types.Status + conn ssh.Conn + channel ssh.Channel + forwarder Forwarder + sessionRegistry SessionRegistry + slugManager slug.Manager + startedAt time.Time + user string +} + +func NewLifecycle(conn ssh.Conn, forwarder Forwarder, slugManager slug.Manager, user string) *Lifecycle { return &Lifecycle{ - status: types.INITIALIZING, - conn: conn, - channel: nil, - forwarder: forwarder, - slugManager: slugManager, - unregisterClient: nil, - startedAt: time.Now(), + status: types.INITIALIZING, + conn: conn, + channel: nil, + forwarder: forwarder, + slugManager: slugManager, + sessionRegistry: nil, + startedAt: time.Now(), + user: user, } } -func (l *Lifecycle) SetUnregisterClient(unregisterClient func(key types.SessionKey)) { - l.unregisterClient = unregisterClient +func (l *Lifecycle) SetSessionRegistry(registry SessionRegistry) { + l.sessionRegistry = registry } type SessionLifecycle interface { @@ -50,12 +56,17 @@ type SessionLifecycle interface { SetStatus(status types.Status) GetConnection() ssh.Conn GetChannel() ssh.Channel + GetUser() string SetChannel(channel ssh.Channel) - SetUnregisterClient(unregisterClient func(key types.SessionKey)) + SetSessionRegistry(registry SessionRegistry) IsActive() bool StartedAt() time.Time } +func (l *Lifecycle) GetUser() string { + return l.user +} + func (l *Lifecycle) GetChannel() ssh.Channel { return l.channel } @@ -94,13 +105,13 @@ func (l *Lifecycle) Close() error { } clientSlug := l.slugManager.Get() - if clientSlug != "" && l.unregisterClient != nil { + if clientSlug != "" && l.sessionRegistry.Remove != nil { key := types.SessionKey{Id: clientSlug, Type: l.forwarder.GetTunnelType()} - l.unregisterClient(key) + l.sessionRegistry.Remove(key) } if l.forwarder.GetTunnelType() == types.TCP { - err := portUtil.Default.SetPortStatus(l.forwarder.GetForwardedPort(), false) + err = portUtil.Default.SetPortStatus(l.forwarder.GetForwardedPort(), false) if err != nil { return err } diff --git a/session/registry.go b/session/registry.go index 6a607f9..60b86d3 100644 --- a/session/registry.go +++ b/session/registry.go @@ -10,7 +10,7 @@ type Key = types.SessionKey type Registry interface { Get(key Key) (session *SSHSession, err error) - Update(oldKey, newKey Key) error + Update(user string, oldKey, newKey Key) error Register(key Key, session *SSHSession) (success bool) Remove(key Key) GetAllSessionFromUser(user string) []*SSHSession @@ -44,7 +44,7 @@ func (r *registry) Get(key Key) (session *SSHSession, err error) { return client, nil } -func (r *registry) Update(oldKey, newKey Key) error { +func (r *registry) Update(user string, oldKey, newKey Key) error { if oldKey.Type != newKey.Type { return fmt.Errorf("tunnel type cannot change") } @@ -64,30 +64,24 @@ func (r *registry) Update(oldKey, newKey Key) error { r.mu.Lock() defer r.mu.Unlock() - userID, ok := r.slugIndex[oldKey] - if !ok { - return fmt.Errorf("session not found") - } - if _, exists := r.slugIndex[newKey]; exists && newKey != oldKey { return fmt.Errorf("someone already uses this subdomain") } - - client, ok := r.byUser[userID][oldKey] + client, ok := r.byUser[user][oldKey] if !ok { return fmt.Errorf("session not found") } - delete(r.byUser[userID], oldKey) + delete(r.byUser[user], oldKey) delete(r.slugIndex, oldKey) client.slugManager.Set(newKey.Id) - r.slugIndex[newKey] = userID + r.slugIndex[newKey] = user - if r.byUser[userID] == nil { - r.byUser[userID] = make(map[Key]*SSHSession) + if r.byUser[user] == nil { + r.byUser[user] = make(map[Key]*SSHSession) } - r.byUser[userID][newKey] = client + r.byUser[user][newKey] = client return nil } @@ -99,7 +93,7 @@ func (r *registry) Register(key Key, session *SSHSession) (success bool) { return false } - userID := session.userID + userID := session.lifecycle.GetUser() if r.byUser[userID] == nil { r.byUser[userID] = make(map[Key]*SSHSession) } diff --git a/session/session.go b/session/session.go index d406160..b1a9ac5 100644 --- a/session/session.go +++ b/session/session.go @@ -9,7 +9,6 @@ import ( "tunnel_pls/session/interaction" "tunnel_pls/session/lifecycle" "tunnel_pls/session/slug" - "tunnel_pls/types" "golang.org/x/crypto/ssh" ) @@ -29,7 +28,6 @@ type SSHSession struct { forwarder forwarder.ForwardingController slugManager slug.Manager registry Registry - userID string } func (s *SSHSession) GetLifecycle() lifecycle.SessionLifecycle { @@ -48,22 +46,16 @@ func (s *SSHSession) GetSlugManager() slug.Manager { return s.slugManager } -func New(conn *ssh.ServerConn, forwardingReq <-chan *ssh.Request, sshChan <-chan ssh.NewChannel, sessionRegistry Registry, userID string) *SSHSession { +func New(conn *ssh.ServerConn, forwardingReq <-chan *ssh.Request, sshChan <-chan ssh.NewChannel, sessionRegistry Registry, user string) *SSHSession { slugManager := slug.NewManager() forwarderManager := forwarder.NewForwarder(slugManager) interactionManager := interaction.NewInteraction(slugManager, forwarderManager) - lifecycleManager := lifecycle.NewLifecycle(conn, forwarderManager, slugManager) + lifecycleManager := lifecycle.NewLifecycle(conn, forwarderManager, slugManager, user) interactionManager.SetLifecycle(lifecycleManager) - interactionManager.SetSlugModificator(func(oldSlug, newSlug string) error { - oldKey := types.SessionKey{Id: oldSlug, Type: forwarderManager.GetTunnelType()} - newKey := types.SessionKey{Id: newSlug, Type: forwarderManager.GetTunnelType()} - return sessionRegistry.Update(oldKey, newKey) - }) forwarderManager.SetLifecycle(lifecycleManager) - lifecycleManager.SetUnregisterClient(func(key types.SessionKey) { - sessionRegistry.Remove(key) - }) + interactionManager.SetSessionRegistry(sessionRegistry) + lifecycleManager.SetSessionRegistry(sessionRegistry) return &SSHSession{ initialReq: forwardingReq, @@ -73,7 +65,6 @@ func New(conn *ssh.ServerConn, forwardingReq <-chan *ssh.Request, sshChan <-chan forwarder: forwarderManager, slugManager: slugManager, registry: sessionRegistry, - userID: userID, } } @@ -89,7 +80,7 @@ func (s *SSHSession) Detail() Detail { return Detail{ ForwardingType: string(s.forwarder.GetTunnelType()), Slug: s.slugManager.Get(), - UserID: s.userID, + UserID: s.lifecycle.GetUser(), Active: s.lifecycle.IsActive(), StartedAt: s.lifecycle.StartedAt(), } From 6213ff8a3096bb595699316b2cd5ab201e236dfc Mon Sep 17 00:00:00 2001 From: bagas Date: Tue, 6 Jan 2026 18:32:48 +0700 Subject: [PATCH 12/15] feat: implement forwarder session termination --- go.mod | 2 +- go.sum | 2 + internal/grpc/client/client.go | 90 ++++++++++++++++++++++++++++++++++ session/registry.go | 12 +++++ 4 files changed, 105 insertions(+), 1 deletion(-) diff --git a/go.mod b/go.mod index fe62062..ba15d04 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module tunnel_pls go 1.25.5 require ( - git.fossy.my.id/bagas/tunnel-please-grpc v1.4.0 + git.fossy.my.id/bagas/tunnel-please-grpc v1.5.0 github.com/caddyserver/certmagic v0.25.0 github.com/charmbracelet/bubbles v0.21.0 github.com/charmbracelet/bubbletea v1.3.10 diff --git a/go.sum b/go.sum index d477230..96c2ea5 100644 --- a/go.sum +++ b/go.sum @@ -2,6 +2,8 @@ git.fossy.my.id/bagas/tunnel-please-grpc v1.3.0 h1:RhcBKUG41/om4jgN+iF/vlY/RojTe git.fossy.my.id/bagas/tunnel-please-grpc v1.3.0/go.mod h1:fG+VkArdkceGB0bNA7IFQus9GetLAwdF5Oi4jdMlXtY= git.fossy.my.id/bagas/tunnel-please-grpc v1.4.0 h1:tpJSKjaSmV+vxxbVx6qnStjxFVXjj2M0rygWXxLb99o= git.fossy.my.id/bagas/tunnel-please-grpc v1.4.0/go.mod h1:fG+VkArdkceGB0bNA7IFQus9GetLAwdF5Oi4jdMlXtY= +git.fossy.my.id/bagas/tunnel-please-grpc v1.5.0 h1:3xszIhck4wo9CoeRq9vnkar4PhY7kz9QrR30qj2XszA= +git.fossy.my.id/bagas/tunnel-please-grpc v1.5.0/go.mod h1:Weh6ZujgWmT8XxD3Qba7sJ6r5eyUMB9XSWynqdyOoLo= github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= diff --git a/internal/grpc/client/client.go b/internal/grpc/client/client.go index 00eac89..8aaf949 100644 --- a/internal/grpc/client/client.go +++ b/internal/grpc/client/client.go @@ -316,6 +316,96 @@ func (c *Client) processEventStream(subscribe grpc.BidiStreamingClient[proto.Nod log.Printf("non-connection send error for sessions success: %v", err) continue } + case proto.EventType_TERMINATE_SESSION: + user := recv.GetTerminateSessionEvent().GetUser() + tunnelTypeRaw := recv.GetTerminateSessionEvent().GetTunnelType() + slug := recv.GetTerminateSessionEvent().GetSlug() + + var userSession *session.SSHSession + var tunnelType types.TunnelType + if tunnelTypeRaw == proto.TunnelType_HTTP { + tunnelType = types.HTTP + } else if tunnelTypeRaw == proto.TunnelType_TCP { + tunnelType = types.TCP + } else { + err = subscribe.Send(&proto.Node{ + Type: proto.EventType_TERMINATE_SESSION, + Payload: &proto.Node_TerminateSessionEventResponse{ + TerminateSessionEventResponse: &proto.TerminateSessionEventResponse{ + Success: false, + Message: "unknown tunnel type recived", + }, + }, + }) + if err != nil { + if c.isConnectionError(err) { + log.Printf("connection error sending sessions success: %v", err) + return err + } + log.Printf("non-connection send error for sessions success: %v", err) + } + continue + } + userSession, err = c.sessionRegistry.GetWithUser(user, types.SessionKey{ + Id: slug, + Type: tunnelType, + }) + if err != nil { + err = subscribe.Send(&proto.Node{ + Type: proto.EventType_TERMINATE_SESSION, + Payload: &proto.Node_TerminateSessionEventResponse{ + TerminateSessionEventResponse: &proto.TerminateSessionEventResponse{ + Success: false, + Message: err.Error(), + }, + }, + }) + if err != nil { + if c.isConnectionError(err) { + log.Printf("connection error sending sessions success: %v", err) + return err + } + log.Printf("non-connection send error for sessions success: %v", err) + } + continue + } + err = userSession.GetLifecycle().Close() + if err != nil { + err = subscribe.Send(&proto.Node{ + Type: proto.EventType_TERMINATE_SESSION, + Payload: &proto.Node_TerminateSessionEventResponse{ + TerminateSessionEventResponse: &proto.TerminateSessionEventResponse{ + Success: false, + Message: err.Error(), + }, + }, + }) + if err != nil { + if c.isConnectionError(err) { + log.Printf("connection error sending sessions success: %v", err) + return err + } + log.Printf("non-connection send error for sessions success: %v", err) + } + continue + } + err = subscribe.Send(&proto.Node{ + Type: proto.EventType_TERMINATE_SESSION, + Payload: &proto.Node_TerminateSessionEventResponse{ + TerminateSessionEventResponse: &proto.TerminateSessionEventResponse{ + Success: true, + Message: "", + }, + }, + }) + if err != nil { + if c.isConnectionError(err) { + log.Printf("connection error sending sessions success: %v", err) + return err + } + log.Printf("non-connection send error for sessions success: %v", err) + continue + } default: log.Printf("Unknown event type received: %v", recv.GetType()) } diff --git a/session/registry.go b/session/registry.go index 60b86d3..3113dd6 100644 --- a/session/registry.go +++ b/session/registry.go @@ -10,6 +10,7 @@ type Key = types.SessionKey type Registry interface { Get(key Key) (session *SSHSession, err error) + GetWithUser(user string, key Key) (session *SSHSession, err error) Update(user string, oldKey, newKey Key) error Register(key Key, session *SSHSession) (success bool) Remove(key Key) @@ -44,6 +45,17 @@ func (r *registry) Get(key Key) (session *SSHSession, err error) { return client, nil } +func (r *registry) GetWithUser(user string, key Key) (session *SSHSession, err error) { + r.mu.RLock() + defer r.mu.RUnlock() + + client, ok := r.byUser[user][key] + if !ok { + return nil, fmt.Errorf("session not found") + } + return client, nil +} + func (r *registry) Update(user string, oldKey, newKey Key) error { if oldKey.Type != newKey.Type { return fmt.Errorf("tunnel type cannot change") From 16d48ff906b7eeaf57bb5b13168206fe01b89280 Mon Sep 17 00:00:00 2001 From: bagas Date: Tue, 6 Jan 2026 20:14:56 +0700 Subject: [PATCH 13/15] refactor(grpc/client): simplify processEventStream with per-event handlers - Extract eventHandlers dispatch table - Add per-event handlers: handleSlugChange, handleGetSessions, handleTerminateSession - Introduce sendNode helper to centralize send/error handling and preserve connection-error propagation - Add protoToTunnelType for tunnel-type validation - Map unknown proto.TunnelType to types.UNKNOWN in protoToTunnelType and return a descriptive error - Reduce boilerplate and improve readability of processEventStream --- internal/grpc/client/client.go | 329 ++++++++++++++------------------- types/types.go | 5 +- 2 files changed, 141 insertions(+), 193 deletions(-) diff --git a/internal/grpc/client/client.go b/internal/grpc/client/client.go index 8aaf949..3d3d1c2 100644 --- a/internal/grpc/client/client.go +++ b/internal/grpc/client/client.go @@ -210,205 +210,152 @@ func (c *Client) SubscribeEvents(ctx context.Context, identity, authToken string } func (c *Client) processEventStream(subscribe grpc.BidiStreamingClient[proto.Node, proto.Events]) error { + handlers := c.eventHandlers(subscribe) + for { recv, err := subscribe.Recv() if err != nil { return err } - switch recv.GetType() { - case proto.EventType_SLUG_CHANGE: - user := recv.GetSlugEvent().GetUser() - oldSlug := recv.GetSlugEvent().GetOld() - newSlug := recv.GetSlugEvent().GetNew() - var userSession *session.SSHSession - userSession, err = c.sessionRegistry.Get(types.SessionKey{ - Id: oldSlug, - Type: types.HTTP, - }) - if err != nil { - errSend := subscribe.Send(&proto.Node{ - Type: proto.EventType_SLUG_CHANGE_RESPONSE, - Payload: &proto.Node_SlugEventResponse{ - SlugEventResponse: &proto.SlugChangeEventResponse{ - Success: false, - Message: err.Error(), - }, - }, - }) - if errSend != nil { - if c.isConnectionError(errSend) { - return errSend - } - log.Printf("non-connection send error for slug change failure: %v", errSend) - } - continue - } - err = c.sessionRegistry.Update(user, types.SessionKey{ - Id: oldSlug, - Type: types.HTTP, - }, types.SessionKey{ - Id: newSlug, - Type: types.HTTP, - }) - if err != nil { - errSend := subscribe.Send(&proto.Node{ - Type: proto.EventType_SLUG_CHANGE_RESPONSE, - Payload: &proto.Node_SlugEventResponse{ - SlugEventResponse: &proto.SlugChangeEventResponse{ - Success: false, - Message: err.Error(), - }, - }, - }) - if errSend != nil { - if c.isConnectionError(errSend) { - return errSend - } - log.Printf("non-connection send error for slug change failure: %v", errSend) - } - continue - } - userSession.GetInteraction().Redraw() - err = subscribe.Send(&proto.Node{ - Type: proto.EventType_SLUG_CHANGE_RESPONSE, - Payload: &proto.Node_SlugEventResponse{ - SlugEventResponse: &proto.SlugChangeEventResponse{ - Success: true, - Message: "", - }, - }, - }) - if err != nil { - if c.isConnectionError(err) { - log.Printf("connection error sending slug change success: %v", err) - return err - } - log.Printf("non-connection send error for slug change success: %v", err) - continue - } - case proto.EventType_GET_SESSIONS: - sessions := c.sessionRegistry.GetAllSessionFromUser(recv.GetGetSessionsEvent().GetIdentity()) - var details []*proto.Detail - for _, ses := range sessions { - detail := ses.Detail() - details = append(details, &proto.Detail{ - Node: config.Getenv("DOMAIN", "localhost"), - ForwardingType: detail.ForwardingType, - Slug: detail.Slug, - UserId: detail.UserID, - Active: detail.Active, - StartedAt: timestamppb.New(detail.StartedAt), - }) - } - err = subscribe.Send(&proto.Node{ - Type: proto.EventType_GET_SESSIONS, - Payload: &proto.Node_GetSessionsEvent{ - GetSessionsEvent: &proto.GetSessionsResponse{ - Details: details, - }, - }, - }) - if err != nil { - if c.isConnectionError(err) { - log.Printf("connection error sending sessions success: %v", err) - return err - } - log.Printf("non-connection send error for sessions success: %v", err) - continue - } - case proto.EventType_TERMINATE_SESSION: - user := recv.GetTerminateSessionEvent().GetUser() - tunnelTypeRaw := recv.GetTerminateSessionEvent().GetTunnelType() - slug := recv.GetTerminateSessionEvent().GetSlug() - var userSession *session.SSHSession - var tunnelType types.TunnelType - if tunnelTypeRaw == proto.TunnelType_HTTP { - tunnelType = types.HTTP - } else if tunnelTypeRaw == proto.TunnelType_TCP { - tunnelType = types.TCP - } else { - err = subscribe.Send(&proto.Node{ - Type: proto.EventType_TERMINATE_SESSION, - Payload: &proto.Node_TerminateSessionEventResponse{ - TerminateSessionEventResponse: &proto.TerminateSessionEventResponse{ - Success: false, - Message: "unknown tunnel type recived", - }, - }, - }) - if err != nil { - if c.isConnectionError(err) { - log.Printf("connection error sending sessions success: %v", err) - return err - } - log.Printf("non-connection send error for sessions success: %v", err) - } - continue - } - userSession, err = c.sessionRegistry.GetWithUser(user, types.SessionKey{ - Id: slug, - Type: tunnelType, - }) - if err != nil { - err = subscribe.Send(&proto.Node{ - Type: proto.EventType_TERMINATE_SESSION, - Payload: &proto.Node_TerminateSessionEventResponse{ - TerminateSessionEventResponse: &proto.TerminateSessionEventResponse{ - Success: false, - Message: err.Error(), - }, - }, - }) - if err != nil { - if c.isConnectionError(err) { - log.Printf("connection error sending sessions success: %v", err) - return err - } - log.Printf("non-connection send error for sessions success: %v", err) - } - continue - } - err = userSession.GetLifecycle().Close() - if err != nil { - err = subscribe.Send(&proto.Node{ - Type: proto.EventType_TERMINATE_SESSION, - Payload: &proto.Node_TerminateSessionEventResponse{ - TerminateSessionEventResponse: &proto.TerminateSessionEventResponse{ - Success: false, - Message: err.Error(), - }, - }, - }) - if err != nil { - if c.isConnectionError(err) { - log.Printf("connection error sending sessions success: %v", err) - return err - } - log.Printf("non-connection send error for sessions success: %v", err) - } - continue - } - err = subscribe.Send(&proto.Node{ - Type: proto.EventType_TERMINATE_SESSION, - Payload: &proto.Node_TerminateSessionEventResponse{ - TerminateSessionEventResponse: &proto.TerminateSessionEventResponse{ - Success: true, - Message: "", - }, - }, - }) - if err != nil { - if c.isConnectionError(err) { - log.Printf("connection error sending sessions success: %v", err) - return err - } - log.Printf("non-connection send error for sessions success: %v", err) - continue - } - default: + handler, ok := handlers[recv.GetType()] + if !ok { log.Printf("Unknown event type received: %v", recv.GetType()) + continue } + + if err = handler(recv); err != nil { + return err + } + } +} + +func (c *Client) eventHandlers(subscribe grpc.BidiStreamingClient[proto.Node, proto.Events]) map[proto.EventType]func(*proto.Events) error { + return map[proto.EventType]func(*proto.Events) error{ + proto.EventType_SLUG_CHANGE: func(evt *proto.Events) error { return c.handleSlugChange(subscribe, evt) }, + proto.EventType_GET_SESSIONS: func(evt *proto.Events) error { return c.handleGetSessions(subscribe, evt) }, + proto.EventType_TERMINATE_SESSION: func(evt *proto.Events) error { return c.handleTerminateSession(subscribe, evt) }, + } +} + +func (c *Client) handleSlugChange(subscribe grpc.BidiStreamingClient[proto.Node, proto.Events], evt *proto.Events) error { + slugEvent := evt.GetSlugEvent() + user := slugEvent.GetUser() + oldSlug := slugEvent.GetOld() + newSlug := slugEvent.GetNew() + + userSession, err := c.sessionRegistry.Get(types.SessionKey{Id: oldSlug, Type: types.HTTP}) + if err != nil { + return c.sendNode(subscribe, &proto.Node{ + Type: proto.EventType_SLUG_CHANGE_RESPONSE, + Payload: &proto.Node_SlugEventResponse{ + SlugEventResponse: &proto.SlugChangeEventResponse{Success: false, Message: err.Error()}, + }, + }, "slug change failure response") + } + + if err = c.sessionRegistry.Update(user, types.SessionKey{Id: oldSlug, Type: types.HTTP}, types.SessionKey{Id: newSlug, Type: types.HTTP}); err != nil { + return c.sendNode(subscribe, &proto.Node{ + Type: proto.EventType_SLUG_CHANGE_RESPONSE, + Payload: &proto.Node_SlugEventResponse{ + SlugEventResponse: &proto.SlugChangeEventResponse{Success: false, Message: err.Error()}, + }, + }, "slug change failure response") + } + + userSession.GetInteraction().Redraw() + return c.sendNode(subscribe, &proto.Node{ + Type: proto.EventType_SLUG_CHANGE_RESPONSE, + Payload: &proto.Node_SlugEventResponse{ + SlugEventResponse: &proto.SlugChangeEventResponse{Success: true, Message: ""}, + }, + }, "slug change success response") +} + +func (c *Client) handleGetSessions(subscribe grpc.BidiStreamingClient[proto.Node, proto.Events], evt *proto.Events) error { + sessions := c.sessionRegistry.GetAllSessionFromUser(evt.GetGetSessionsEvent().GetIdentity()) + + var details []*proto.Detail + for _, ses := range sessions { + detail := ses.Detail() + details = append(details, &proto.Detail{ + Node: config.Getenv("DOMAIN", "localhost"), + ForwardingType: detail.ForwardingType, + Slug: detail.Slug, + UserId: detail.UserID, + Active: detail.Active, + StartedAt: timestamppb.New(detail.StartedAt), + }) + } + + return c.sendNode(subscribe, &proto.Node{ + Type: proto.EventType_GET_SESSIONS, + Payload: &proto.Node_GetSessionsEvent{ + GetSessionsEvent: &proto.GetSessionsResponse{Details: details}, + }, + }, "send get sessions response") +} + +func (c *Client) handleTerminateSession(subscribe grpc.BidiStreamingClient[proto.Node, proto.Events], evt *proto.Events) error { + terminate := evt.GetTerminateSessionEvent() + user := terminate.GetUser() + slug := terminate.GetSlug() + + tunnelType, err := c.protoToTunnelType(terminate.GetTunnelType()) + if err != nil { + return c.sendNode(subscribe, &proto.Node{ + Type: proto.EventType_TERMINATE_SESSION, + Payload: &proto.Node_TerminateSessionEventResponse{ + TerminateSessionEventResponse: &proto.TerminateSessionEventResponse{Success: false, Message: err.Error()}, + }, + }, "terminate session invalid tunnel type") + } + + userSession, err := c.sessionRegistry.GetWithUser(user, types.SessionKey{Id: slug, Type: tunnelType}) + if err != nil { + return c.sendNode(subscribe, &proto.Node{ + Type: proto.EventType_TERMINATE_SESSION, + Payload: &proto.Node_TerminateSessionEventResponse{ + TerminateSessionEventResponse: &proto.TerminateSessionEventResponse{Success: false, Message: err.Error()}, + }, + }, "terminate session fetch failed") + } + + if err = userSession.GetLifecycle().Close(); err != nil { + return c.sendNode(subscribe, &proto.Node{ + Type: proto.EventType_TERMINATE_SESSION, + Payload: &proto.Node_TerminateSessionEventResponse{ + TerminateSessionEventResponse: &proto.TerminateSessionEventResponse{Success: false, Message: err.Error()}, + }, + }, "terminate session close failed") + } + + return c.sendNode(subscribe, &proto.Node{ + Type: proto.EventType_TERMINATE_SESSION, + Payload: &proto.Node_TerminateSessionEventResponse{ + TerminateSessionEventResponse: &proto.TerminateSessionEventResponse{Success: true, Message: ""}, + }, + }, "terminate session success response") +} + +func (c *Client) sendNode(subscribe grpc.BidiStreamingClient[proto.Node, proto.Events], node *proto.Node, context string) error { + if err := subscribe.Send(node); err != nil { + if c.isConnectionError(err) { + return err + } + log.Printf("%s: %v", context, err) + } + return nil +} + +func (c *Client) protoToTunnelType(t proto.TunnelType) (types.TunnelType, error) { + switch t { + case proto.TunnelType_HTTP: + return types.HTTP, nil + case proto.TunnelType_TCP: + return types.TCP, nil + default: + return types.UNKNOWN, fmt.Errorf("unknown tunnel type received") } } diff --git a/types/types.go b/types/types.go index 5c4eece..7d3f4de 100644 --- a/types/types.go +++ b/types/types.go @@ -11,8 +11,9 @@ const ( type TunnelType string const ( - HTTP TunnelType = "HTTP" - TCP TunnelType = "TCP" + UNKNOWN TunnelType = "UNKNOWN" + HTTP TunnelType = "HTTP" + TCP TunnelType = "TCP" ) type SessionKey struct { From 6b4127f0efd9584a086150994ad1acd18060e916 Mon Sep 17 00:00:00 2001 From: bagas Date: Wed, 7 Jan 2026 23:07:02 +0700 Subject: [PATCH 14/15] feat: add authenticated user info and restructure handleConnection - Display authenticated username in welcome page information box - Refactor handleConnection function for better structure and clarity --- server/server.go | 24 ++++++++++++---------- session/interaction/interaction.go | 32 ++++++++++++++++++++---------- 2 files changed, 35 insertions(+), 21 deletions(-) diff --git a/server/server.go b/server/server.go index 9439d90..759bac9 100644 --- a/server/server.go +++ b/server/server.go @@ -2,9 +2,11 @@ package server import ( "context" + "errors" "fmt" "log" "net" + "time" "tunnel_pls/internal/config" "tunnel_pls/internal/grpc/client" "tunnel_pls/session" @@ -64,30 +66,32 @@ func (s *Server) Start() { func (s *Server) handleConnection(conn net.Conn) { sshConn, chans, forwardingReqs, err := ssh.NewServerConn(conn, s.config) - defer func(sshConn *ssh.ServerConn) { - err = sshConn.Close() - if err != nil { - log.Printf("failed to close SSH server: %v", err) - } - }(sshConn) - if err != nil { log.Printf("failed to establish SSH connection: %v", err) - err := conn.Close() + err = conn.Close() if err != nil { log.Printf("failed to close SSH connection: %v", err) return } return } - ctx := context.Background() - log.Println("SSH connection established:", sshConn.User()) + + defer func(sshConn *ssh.ServerConn) { + err = sshConn.Close() + if err != nil && !errors.Is(err, net.ErrClosed) { + log.Printf("failed to close SSH server: %v", err) + } + }(sshConn) user := "UNAUTHORIZED" if s.grpcClient != nil { + ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) _, u, _ := s.grpcClient.AuthorizeConn(ctx, sshConn.User()) user = u + cancel() } + + log.Println("SSH connection established:", sshConn.User()) sshSession := session.New(sshConn, forwardingReqs, chans, s.sessionRegistry, user) err = sshSession.Start() if err != nil { diff --git a/session/interaction/interaction.go b/session/interaction/interaction.go index 99723c0..874fbf2 100644 --- a/session/interaction/interaction.go +++ b/session/interaction/interaction.go @@ -672,22 +672,32 @@ func (m *model) View() string { MarginBottom(boxMargin). Width(boxMaxWidth) - urlDisplay := m.getTunnelURL() - if shouldUseCompactLayout(m.width, 80) && len(urlDisplay) > m.width-20 { - maxLen := m.width - 25 - if maxLen > 10 { - urlDisplay = truncateString(urlDisplay, maxLen) - } - } + authenticatedUser := m.interaction.lifecycle.GetUser() + + userInfoStyle := lipgloss.NewStyle(). + Foreground(lipgloss.Color("#FAFAFA")). + Bold(true) + + sectionHeaderStyle := lipgloss.NewStyle(). + Foreground(lipgloss.Color("#888888")). + Bold(true) + + addressStyle := lipgloss.NewStyle(). + Foreground(lipgloss.Color("#FAFAFA")) var infoContent string if shouldUseCompactLayout(m.width, 70) { - infoContent = fmt.Sprintf("🌐 %s", urlBoxStyle.Render(urlDisplay)) - } else if isCompact { - infoContent = fmt.Sprintf("🌐 Forwarding to:\n\n %s", urlBoxStyle.Render(urlDisplay)) + infoContent = fmt.Sprintf("👤 %s\n\n%s\n%s", + userInfoStyle.Render(authenticatedUser), + sectionHeaderStyle.Render("🌐 FORWARDING ADDRESS:"), + addressStyle.Render(fmt.Sprintf(" %s", urlBoxStyle.Render(m.getTunnelURL())))) } else { - infoContent = fmt.Sprintf("🌐 F O R W A R D I N G T O:\n\n %s", urlBoxStyle.Render(urlDisplay)) + infoContent = fmt.Sprintf("👤 Authenticated as: %s\n\n%s\n %s", + userInfoStyle.Render(authenticatedUser), + sectionHeaderStyle.Render("🌐 FORWARDING ADDRESS:"), + addressStyle.Render(urlBoxStyle.Render(m.getTunnelURL()))) } + b.WriteString(responsiveInfoBox.Render(infoContent)) b.WriteString("\n") From b8acb6da4cd345e1ba60c18c94829e14858265fb Mon Sep 17 00:00:00 2001 From: bagas Date: Thu, 8 Jan 2026 12:55:15 +0700 Subject: [PATCH 15/15] ci: remove renovate --- .gitea/workflows/renovate.yml | 21 --------------------- renovate-config.js | 8 -------- 2 files changed, 29 deletions(-) delete mode 100644 .gitea/workflows/renovate.yml delete mode 100644 renovate-config.js diff --git a/.gitea/workflows/renovate.yml b/.gitea/workflows/renovate.yml deleted file mode 100644 index 49008b4..0000000 --- a/.gitea/workflows/renovate.yml +++ /dev/null @@ -1,21 +0,0 @@ -name: renovate - -on: - schedule: - - cron: "0 0 * * *" - push: - branches: - - staging - -jobs: - renovate: - runs-on: ubuntu-latest - container: git.fossy.my.id/renovate-clanker/renovate:latest - steps: - - uses: actions/checkout@v6 - - run: renovate - env: - RENOVATE_CONFIG_FILE: ${{ gitea.workspace }}/renovate-config.js - LOG_LEVEL: "debug" - RENOVATE_TOKEN: ${{ secrets.RENOVATE_TOKEN }} - GITHUB_COM_TOKEN: ${{ secrets.COM_TOKEN }} \ No newline at end of file diff --git a/renovate-config.js b/renovate-config.js deleted file mode 100644 index 212cb36..0000000 --- a/renovate-config.js +++ /dev/null @@ -1,8 +0,0 @@ -module.exports = { - "endpoint": "https://git.fossy.my.id/api/v1", - "gitAuthor": "Renovate-Clanker ", - "platform": "gitea", - "onboardingConfigFileName": "renovate.json", - "autodiscover": true, - "optimizeForDisabled": true, -}; \ No newline at end of file