Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2b9bca65d5 | |||
| 6587dc0f39 | |||
| 6969d6823a | |||
| 1a04af8873 | |||
| 19135ceb42 | |||
| edb11dbc51 | |||
| 819f044275 | |||
| a7ebf2c5db | |||
| 64c1038f4b | |||
| aafea49975 |
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
FROM golang:1.25.5-alpine AS go_builder
|
FROM golang:1.25.6-alpine AS go_builder
|
||||||
|
|
||||||
ARG VERSION=dev
|
ARG VERSION=dev
|
||||||
ARG BUILD_DATE=unknown
|
ARG BUILD_DATE=unknown
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ require (
|
|||||||
github.com/joho/godotenv v1.5.1
|
github.com/joho/godotenv v1.5.1
|
||||||
github.com/libdns/cloudflare v0.2.2
|
github.com/libdns/cloudflare v0.2.2
|
||||||
github.com/muesli/termenv v0.16.0
|
github.com/muesli/termenv v0.16.0
|
||||||
golang.org/x/crypto v0.46.0
|
golang.org/x/crypto v0.47.0
|
||||||
google.golang.org/grpc v1.78.0
|
google.golang.org/grpc v1.78.0
|
||||||
google.golang.org/protobuf v1.36.11
|
google.golang.org/protobuf v1.36.11
|
||||||
)
|
)
|
||||||
@@ -48,8 +48,8 @@ require (
|
|||||||
golang.org/x/mod v0.31.0 // indirect
|
golang.org/x/mod v0.31.0 // indirect
|
||||||
golang.org/x/net v0.48.0 // indirect
|
golang.org/x/net v0.48.0 // indirect
|
||||||
golang.org/x/sync v0.19.0 // indirect
|
golang.org/x/sync v0.19.0 // indirect
|
||||||
golang.org/x/sys v0.39.0 // indirect
|
golang.org/x/sys v0.40.0 // indirect
|
||||||
golang.org/x/text v0.32.0 // indirect
|
golang.org/x/text v0.33.0 // indirect
|
||||||
golang.org/x/tools v0.40.0 // indirect
|
golang.org/x/tools v0.40.0 // indirect
|
||||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b // indirect
|
google.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b // indirect
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -120,6 +120,8 @@ go.uber.org/zap/exp v0.3.0 h1:6JYzdifzYkGmTdRR59oYH+Ng7k49H9qVpWwNSsGJj3U=
|
|||||||
go.uber.org/zap/exp v0.3.0/go.mod h1:5I384qq7XGxYyByIhHm6jg5CHkGY0nsTfbDLgDDlgJQ=
|
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 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
|
||||||
golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
|
golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
|
||||||
|
golang.org/x/crypto v0.47.0 h1:V6e3FRj+n4dbpw86FJ8Fv7XVOql7TEwpHapKoMJ/GO8=
|
||||||
|
golang.org/x/crypto v0.47.0/go.mod h1:ff3Y9VzzKbwSSEzWqJsJVBnWmRwRSHt/6Op5n9bQc4A=
|
||||||
golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI=
|
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/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 h1:HaW9xtz0+kOcWKwli0ZXy79Ix+UW/vOfmWI5QVd2tgI=
|
||||||
@@ -132,10 +134,14 @@ golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBc
|
|||||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
|
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
|
||||||
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||||
|
golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ=
|
||||||
|
golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||||
golang.org/x/term v0.38.0 h1:PQ5pkm/rLO6HnxFR7N2lJHOZX6Kez5Y1gDSJla6jo7Q=
|
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/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 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
|
||||||
golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
|
golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
|
||||||
|
golang.org/x/text v0.33.0 h1:B3njUFyqtHDUI5jMn1YIr5B0IE2U0qck04r6d4KPAxE=
|
||||||
|
golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8=
|
||||||
golang.org/x/tools v0.40.0 h1:yLkxfA+Qnul4cs9QA3KnlFu0lVmd8JJfoq+E41uSutA=
|
golang.org/x/tools v0.40.0 h1:yLkxfA+Qnul4cs9QA3KnlFu0lVmd8JJfoq+E41uSutA=
|
||||||
golang.org/x/tools v0.40.0/go.mod h1:Ik/tzLRlbscWpqqMRjyWYDisX8bG13FrdXp3o4Sr9lc=
|
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 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ package client
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
@@ -16,7 +15,6 @@ import (
|
|||||||
proto "git.fossy.my.id/bagas/tunnel-please-grpc/gen"
|
proto "git.fossy.my.id/bagas/tunnel-please-grpc/gen"
|
||||||
"google.golang.org/grpc"
|
"google.golang.org/grpc"
|
||||||
"google.golang.org/grpc/codes"
|
"google.golang.org/grpc/codes"
|
||||||
"google.golang.org/grpc/credentials"
|
|
||||||
"google.golang.org/grpc/credentials/insecure"
|
"google.golang.org/grpc/credentials/insecure"
|
||||||
"google.golang.org/grpc/health/grpc_health_v1"
|
"google.golang.org/grpc/health/grpc_health_v1"
|
||||||
"google.golang.org/grpc/keepalive"
|
"google.golang.org/grpc/keepalive"
|
||||||
@@ -24,83 +22,34 @@ import (
|
|||||||
"google.golang.org/protobuf/types/known/timestamppb"
|
"google.golang.org/protobuf/types/known/timestamppb"
|
||||||
)
|
)
|
||||||
|
|
||||||
type GrpcConfig struct {
|
type Client interface {
|
||||||
Address string
|
SubscribeEvents(ctx context.Context, identity, authToken string) error
|
||||||
UseTLS bool
|
ClientConn() *grpc.ClientConn
|
||||||
InsecureSkipVerify bool
|
AuthorizeConn(ctx context.Context, token string) (authorized bool, user string, err error)
|
||||||
Timeout time.Duration
|
Close() error
|
||||||
KeepAlive bool
|
CheckServerHealth(ctx context.Context) error
|
||||||
MaxRetries int
|
|
||||||
KeepAliveTime time.Duration
|
|
||||||
KeepAliveTimeout time.Duration
|
|
||||||
PermitWithoutStream bool
|
|
||||||
}
|
}
|
||||||
|
type client struct {
|
||||||
type Client struct {
|
|
||||||
conn *grpc.ClientConn
|
conn *grpc.ClientConn
|
||||||
config *GrpcConfig
|
address string
|
||||||
sessionRegistry session.Registry
|
sessionRegistry session.Registry
|
||||||
eventService proto.EventServiceClient
|
eventService proto.EventServiceClient
|
||||||
authorizeConnectionService proto.UserServiceClient
|
authorizeConnectionService proto.UserServiceClient
|
||||||
closing bool
|
closing bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func DefaultConfig() *GrpcConfig {
|
func New(address string, sessionRegistry session.Registry) (Client, error) {
|
||||||
return &GrpcConfig{
|
|
||||||
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
|
var opts []grpc.DialOption
|
||||||
|
|
||||||
if config.UseTLS {
|
opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||||
tlsConfig := &tls.Config{
|
|
||||||
InsecureSkipVerify: config.InsecureSkipVerify,
|
kaParams := keepalive.ClientParameters{
|
||||||
}
|
Time: 2 * time.Minute,
|
||||||
creds := credentials.NewTLS(tlsConfig)
|
Timeout: 10 * time.Second,
|
||||||
opts = append(opts, grpc.WithTransportCredentials(creds))
|
PermitWithoutStream: false,
|
||||||
} else {
|
|
||||||
opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if config.KeepAlive {
|
opts = append(opts, grpc.WithKeepaliveParams(kaParams))
|
||||||
kaParams := keepalive.ClientParameters{
|
|
||||||
Time: config.KeepAliveTime,
|
|
||||||
Timeout: config.KeepAliveTimeout,
|
|
||||||
PermitWithoutStream: config.PermitWithoutStream,
|
|
||||||
}
|
|
||||||
opts = append(opts, grpc.WithKeepaliveParams(kaParams))
|
|
||||||
}
|
|
||||||
|
|
||||||
opts = append(opts,
|
opts = append(opts,
|
||||||
grpc.WithDefaultCallOptions(
|
grpc.WithDefaultCallOptions(
|
||||||
@@ -109,24 +58,24 @@ func New(config *GrpcConfig, sessionRegistry session.Registry) (*Client, error)
|
|||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
conn, err := grpc.NewClient(config.Address, opts...)
|
conn, err := grpc.NewClient(address, opts...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("failed to connect to gRPC server at %s: %w", config.Address, err)
|
return nil, fmt.Errorf("failed to connect to gRPC server at %s: %w", address, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
eventService := proto.NewEventServiceClient(conn)
|
eventService := proto.NewEventServiceClient(conn)
|
||||||
authorizeConnectionService := proto.NewUserServiceClient(conn)
|
authorizeConnectionService := proto.NewUserServiceClient(conn)
|
||||||
|
|
||||||
return &Client{
|
return &client{
|
||||||
conn: conn,
|
conn: conn,
|
||||||
config: config,
|
address: address,
|
||||||
sessionRegistry: sessionRegistry,
|
sessionRegistry: sessionRegistry,
|
||||||
eventService: eventService,
|
eventService: eventService,
|
||||||
authorizeConnectionService: authorizeConnectionService,
|
authorizeConnectionService: authorizeConnectionService,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) SubscribeEvents(ctx context.Context, identity, authToken string) error {
|
func (c *client) SubscribeEvents(ctx context.Context, identity, authToken string) error {
|
||||||
const (
|
const (
|
||||||
baseBackoff = time.Second
|
baseBackoff = time.Second
|
||||||
maxBackoff = 30 * time.Second
|
maxBackoff = 30 * time.Second
|
||||||
@@ -209,7 +158,7 @@ func (c *Client) SubscribeEvents(ctx context.Context, identity, authToken string
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) processEventStream(subscribe grpc.BidiStreamingClient[proto.Node, proto.Events]) error {
|
func (c *client) processEventStream(subscribe grpc.BidiStreamingClient[proto.Node, proto.Events]) error {
|
||||||
handlers := c.eventHandlers(subscribe)
|
handlers := c.eventHandlers(subscribe)
|
||||||
|
|
||||||
for {
|
for {
|
||||||
@@ -230,7 +179,7 @@ func (c *Client) processEventStream(subscribe grpc.BidiStreamingClient[proto.Nod
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) eventHandlers(subscribe grpc.BidiStreamingClient[proto.Node, proto.Events]) map[proto.EventType]func(*proto.Events) error {
|
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{
|
return map[proto.EventType]func(*proto.Events) error{
|
||||||
proto.EventType_SLUG_CHANGE: func(evt *proto.Events) error { return c.handleSlugChange(subscribe, evt) },
|
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_GET_SESSIONS: func(evt *proto.Events) error { return c.handleGetSessions(subscribe, evt) },
|
||||||
@@ -238,7 +187,7 @@ func (c *Client) eventHandlers(subscribe grpc.BidiStreamingClient[proto.Node, pr
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) handleSlugChange(subscribe grpc.BidiStreamingClient[proto.Node, proto.Events], evt *proto.Events) error {
|
func (c *client) handleSlugChange(subscribe grpc.BidiStreamingClient[proto.Node, proto.Events], evt *proto.Events) error {
|
||||||
slugEvent := evt.GetSlugEvent()
|
slugEvent := evt.GetSlugEvent()
|
||||||
user := slugEvent.GetUser()
|
user := slugEvent.GetUser()
|
||||||
oldSlug := slugEvent.GetOld()
|
oldSlug := slugEvent.GetOld()
|
||||||
@@ -272,7 +221,7 @@ func (c *Client) handleSlugChange(subscribe grpc.BidiStreamingClient[proto.Node,
|
|||||||
}, "slug change success response")
|
}, "slug change success response")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) handleGetSessions(subscribe grpc.BidiStreamingClient[proto.Node, proto.Events], evt *proto.Events) error {
|
func (c *client) handleGetSessions(subscribe grpc.BidiStreamingClient[proto.Node, proto.Events], evt *proto.Events) error {
|
||||||
sessions := c.sessionRegistry.GetAllSessionFromUser(evt.GetGetSessionsEvent().GetIdentity())
|
sessions := c.sessionRegistry.GetAllSessionFromUser(evt.GetGetSessionsEvent().GetIdentity())
|
||||||
|
|
||||||
var details []*proto.Detail
|
var details []*proto.Detail
|
||||||
@@ -296,7 +245,7 @@ func (c *Client) handleGetSessions(subscribe grpc.BidiStreamingClient[proto.Node
|
|||||||
}, "send get sessions response")
|
}, "send get sessions response")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) handleTerminateSession(subscribe grpc.BidiStreamingClient[proto.Node, proto.Events], evt *proto.Events) error {
|
func (c *client) handleTerminateSession(subscribe grpc.BidiStreamingClient[proto.Node, proto.Events], evt *proto.Events) error {
|
||||||
terminate := evt.GetTerminateSessionEvent()
|
terminate := evt.GetTerminateSessionEvent()
|
||||||
user := terminate.GetUser()
|
user := terminate.GetUser()
|
||||||
slug := terminate.GetSlug()
|
slug := terminate.GetSlug()
|
||||||
@@ -338,7 +287,7 @@ func (c *Client) handleTerminateSession(subscribe grpc.BidiStreamingClient[proto
|
|||||||
}, "terminate session success response")
|
}, "terminate session success response")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) sendNode(subscribe grpc.BidiStreamingClient[proto.Node, proto.Events], node *proto.Node, context string) error {
|
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 err := subscribe.Send(node); err != nil {
|
||||||
if c.isConnectionError(err) {
|
if c.isConnectionError(err) {
|
||||||
return err
|
return err
|
||||||
@@ -348,7 +297,7 @@ func (c *Client) sendNode(subscribe grpc.BidiStreamingClient[proto.Node, proto.E
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) protoToTunnelType(t proto.TunnelType) (types.TunnelType, error) {
|
func (c *client) protoToTunnelType(t proto.TunnelType) (types.TunnelType, error) {
|
||||||
switch t {
|
switch t {
|
||||||
case proto.TunnelType_HTTP:
|
case proto.TunnelType_HTTP:
|
||||||
return types.HTTP, nil
|
return types.HTTP, nil
|
||||||
@@ -359,11 +308,11 @@ func (c *Client) protoToTunnelType(t proto.TunnelType) (types.TunnelType, error)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) GetConnection() *grpc.ClientConn {
|
func (c *client) ClientConn() *grpc.ClientConn {
|
||||||
return c.conn
|
return c.conn
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) AuthorizeConn(ctx context.Context, token string) (authorized bool, user string, 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})
|
check, err := c.authorizeConnectionService.Check(ctx, &proto.CheckRequest{AuthToken: token})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, "UNAUTHORIZED", err
|
return false, "UNAUTHORIZED", err
|
||||||
@@ -375,17 +324,8 @@ func (c *Client) AuthorizeConn(ctx context.Context, token string) (authorized bo
|
|||||||
return true, check.GetUser(), nil
|
return true, check.GetUser(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) Close() error {
|
func (c *client) CheckServerHealth(ctx context.Context) error {
|
||||||
if c.conn != nil {
|
healthClient := grpc_health_v1.NewHealthClient(c.ClientConn())
|
||||||
log.Printf("Closing gRPC connection to %s", c.config.Address)
|
|
||||||
c.closing = true
|
|
||||||
return c.conn.Close()
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Client) CheckServerHealth(ctx context.Context) error {
|
|
||||||
healthClient := grpc_health_v1.NewHealthClient(c.GetConnection())
|
|
||||||
resp, err := healthClient.Check(ctx, &grpc_health_v1.HealthCheckRequest{
|
resp, err := healthClient.Check(ctx, &grpc_health_v1.HealthCheckRequest{
|
||||||
Service: "",
|
Service: "",
|
||||||
})
|
})
|
||||||
@@ -398,11 +338,16 @@ func (c *Client) CheckServerHealth(ctx context.Context) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) GetConfig() *GrpcConfig {
|
func (c *client) Close() error {
|
||||||
return c.config
|
if c.conn != nil {
|
||||||
|
log.Printf("Closing gRPC connection to %s", c.address)
|
||||||
|
c.closing = true
|
||||||
|
return c.conn.Close()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) isConnectionError(err error) bool {
|
func (c *client) isConnectionError(err error) bool {
|
||||||
if c.closing {
|
if c.closing {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|||||||
+13
-13
@@ -1,18 +1,18 @@
|
|||||||
package random
|
package random
|
||||||
|
|
||||||
import (
|
import "crypto/rand"
|
||||||
mathrand "math/rand"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
func GenerateRandomString(length int) string {
|
func GenerateRandomString(length int) (string, error) {
|
||||||
const charset = "abcdefghijklmnopqrstuvwxyz"
|
const charset = "abcdefghijklmnopqrstuvwxyz0123456789"
|
||||||
seededRand := mathrand.New(mathrand.NewSource(time.Now().UnixNano() + int64(mathrand.Intn(9999))))
|
b := make([]byte, length)
|
||||||
var result strings.Builder
|
|
||||||
for i := 0; i < length; i++ {
|
if _, err := rand.Read(b); err != nil {
|
||||||
randomIndex := seededRand.Intn(len(charset))
|
return "", err
|
||||||
result.WriteString(string(charset[randomIndex]))
|
|
||||||
}
|
}
|
||||||
return result.String()
|
|
||||||
|
for i := range b {
|
||||||
|
b[i] = charset[int(b[i])%len(charset)]
|
||||||
|
}
|
||||||
|
|
||||||
|
return string(b), nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -49,7 +49,7 @@ func main() {
|
|||||||
|
|
||||||
sshConfig := &ssh.ServerConfig{
|
sshConfig := &ssh.ServerConfig{
|
||||||
NoClientAuth: true,
|
NoClientAuth: true,
|
||||||
ServerVersion: fmt.Sprintf("SSH-2.0-TunnlPls-%s", version.GetShortVersion()),
|
ServerVersion: fmt.Sprintf("SSH-2.0-TunnelPlease-%s", version.GetShortVersion()),
|
||||||
}
|
}
|
||||||
|
|
||||||
sshKeyPath := "certs/ssh/id_rsa"
|
sshKeyPath := "certs/ssh/id_rsa"
|
||||||
@@ -77,7 +77,7 @@ func main() {
|
|||||||
shutdownChan := make(chan os.Signal, 1)
|
shutdownChan := make(chan os.Signal, 1)
|
||||||
signal.Notify(shutdownChan, os.Interrupt, syscall.SIGTERM)
|
signal.Notify(shutdownChan, os.Interrupt, syscall.SIGTERM)
|
||||||
|
|
||||||
var grpcClient *client.Client
|
var grpcClient client.Client
|
||||||
if isNodeMode {
|
if isNodeMode {
|
||||||
grpcHost := config.Getenv("GRPC_ADDRESS", "localhost")
|
grpcHost := config.Getenv("GRPC_ADDRESS", "localhost")
|
||||||
grpcPort := config.Getenv("GRPC_PORT", "8080")
|
grpcPort := config.Getenv("GRPC_PORT", "8080")
|
||||||
@@ -87,21 +87,13 @@ func main() {
|
|||||||
log.Fatalf("NODE_TOKEN is required in node mode")
|
log.Fatalf("NODE_TOKEN is required in node mode")
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err := client.New(&client.GrpcConfig{
|
grpcClient, err = client.New(grpcAddr, sessionRegistry)
|
||||||
Address: grpcAddr,
|
|
||||||
UseTLS: false,
|
|
||||||
InsecureSkipVerify: false,
|
|
||||||
Timeout: 10 * time.Second,
|
|
||||||
KeepAlive: true,
|
|
||||||
MaxRetries: 3,
|
|
||||||
}, sessionRegistry)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("failed to create grpc client: %v", err)
|
log.Fatalf("failed to create grpc client: %v", err)
|
||||||
}
|
}
|
||||||
grpcClient = c
|
|
||||||
|
|
||||||
healthCtx, healthCancel := context.WithTimeout(ctx, 5*time.Second)
|
healthCtx, healthCancel := context.WithTimeout(ctx, 5*time.Second)
|
||||||
if err := grpcClient.CheckServerHealth(healthCtx); err != nil {
|
if err = grpcClient.CheckServerHealth(healthCtx); err != nil {
|
||||||
healthCancel()
|
healthCancel()
|
||||||
log.Fatalf("gRPC health check failed: %v", err)
|
log.Fatalf("gRPC health check failed: %v", err)
|
||||||
}
|
}
|
||||||
@@ -109,14 +101,15 @@ func main() {
|
|||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
identity := config.Getenv("DOMAIN", "localhost")
|
identity := config.Getenv("DOMAIN", "localhost")
|
||||||
if err := grpcClient.SubscribeEvents(ctx, identity, nodeToken); err != nil {
|
if err = grpcClient.SubscribeEvents(ctx, identity, nodeToken); err != nil {
|
||||||
errChan <- fmt.Errorf("failed to subscribe to events: %w", err)
|
errChan <- fmt.Errorf("failed to subscribe to events: %w", err)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var app server.Server
|
||||||
go func() {
|
go func() {
|
||||||
app, err := server.NewServer(sshConfig, sessionRegistry, grpcClient)
|
app, err = server.New(sshConfig, sessionRegistry, grpcClient)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
errChan <- fmt.Errorf("failed to start server: %s", err)
|
errChan <- fmt.Errorf("failed to start server: %s", err)
|
||||||
return
|
return
|
||||||
@@ -125,7 +118,7 @@ func main() {
|
|||||||
}()
|
}()
|
||||||
|
|
||||||
select {
|
select {
|
||||||
case err := <-errChan:
|
case err = <-errChan:
|
||||||
log.Printf("error happen : %s", err)
|
log.Printf("error happen : %s", err)
|
||||||
case sig := <-shutdownChan:
|
case sig := <-shutdownChan:
|
||||||
log.Printf("received signal %s, shutting down", sig)
|
log.Printf("received signal %s, shutting down", sig)
|
||||||
@@ -133,8 +126,14 @@ func main() {
|
|||||||
|
|
||||||
cancel()
|
cancel()
|
||||||
|
|
||||||
|
if app != nil {
|
||||||
|
if err = app.Close(); err != nil {
|
||||||
|
log.Printf("failed to close server : %s", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if grpcClient != nil {
|
if grpcClient != nil {
|
||||||
if err := grpcClient.Close(); err != nil {
|
if err = grpcClient.Close(); err != nil {
|
||||||
log.Printf("failed to close grpc conn : %s", err)
|
log.Printf("failed to close grpc conn : %s", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+21
-9
@@ -14,14 +14,18 @@ import (
|
|||||||
"golang.org/x/crypto/ssh"
|
"golang.org/x/crypto/ssh"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Server struct {
|
type Server interface {
|
||||||
conn *net.Listener
|
Start()
|
||||||
|
Close() error
|
||||||
|
}
|
||||||
|
type server struct {
|
||||||
|
listener net.Listener
|
||||||
config *ssh.ServerConfig
|
config *ssh.ServerConfig
|
||||||
sessionRegistry session.Registry
|
sessionRegistry session.Registry
|
||||||
grpcClient *client.Client
|
grpcClient client.Client
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewServer(sshConfig *ssh.ServerConfig, sessionRegistry session.Registry, grpcClient *client.Client) (*Server, error) {
|
func New(sshConfig *ssh.ServerConfig, sessionRegistry session.Registry, grpcClient client.Client) (Server, error) {
|
||||||
listener, err := net.Listen("tcp", fmt.Sprintf(":%s", config.Getenv("PORT", "2200")))
|
listener, err := net.Listen("tcp", fmt.Sprintf(":%s", config.Getenv("PORT", "2200")))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("failed to listen on port 2200: %v", err)
|
log.Fatalf("failed to listen on port 2200: %v", err)
|
||||||
@@ -43,19 +47,23 @@ func NewServer(sshConfig *ssh.ServerConfig, sessionRegistry session.Registry, gr
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return &Server{
|
return &server{
|
||||||
conn: &listener,
|
listener: listener,
|
||||||
config: sshConfig,
|
config: sshConfig,
|
||||||
sessionRegistry: sessionRegistry,
|
sessionRegistry: sessionRegistry,
|
||||||
grpcClient: grpcClient,
|
grpcClient: grpcClient,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) Start() {
|
func (s *server) Start() {
|
||||||
log.Println("SSH server is starting on port 2200...")
|
log.Println("SSH server is starting on port 2200...")
|
||||||
for {
|
for {
|
||||||
conn, err := (*s.conn).Accept()
|
conn, err := s.listener.Accept()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
if errors.Is(err, net.ErrClosed) {
|
||||||
|
log.Println("listener closed, stopping server")
|
||||||
|
return
|
||||||
|
}
|
||||||
log.Printf("failed to accept connection: %v", err)
|
log.Printf("failed to accept connection: %v", err)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -64,7 +72,11 @@ func (s *Server) Start() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) handleConnection(conn net.Conn) {
|
func (s *server) Close() error {
|
||||||
|
return s.listener.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *server) handleConnection(conn net.Conn) {
|
||||||
sshConn, chans, forwardingReqs, err := ssh.NewServerConn(conn, s.config)
|
sshConn, chans, forwardingReqs, err := ssh.NewServerConn(conn, s.config)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("failed to establish SSH connection: %v", err)
|
log.Printf("failed to establish SSH connection: %v", err)
|
||||||
|
|||||||
+4
-10
@@ -301,22 +301,16 @@ func (tm *tlsManager) initCertMagic() error {
|
|||||||
func (tm *tlsManager) getTLSConfig() *tls.Config {
|
func (tm *tlsManager) getTLSConfig() *tls.Config {
|
||||||
return &tls.Config{
|
return &tls.Config{
|
||||||
GetCertificate: tm.getCertificate,
|
GetCertificate: tm.getCertificate,
|
||||||
MinVersion: tls.VersionTLS13,
|
|
||||||
MaxVersion: tls.VersionTLS13,
|
|
||||||
|
|
||||||
SessionTicketsDisabled: false,
|
MinVersion: tls.VersionTLS13,
|
||||||
|
MaxVersion: tls.VersionTLS13,
|
||||||
CipherSuites: []uint16{
|
|
||||||
tls.TLS_AES_128_GCM_SHA256,
|
|
||||||
tls.TLS_CHACHA20_POLY1305_SHA256,
|
|
||||||
},
|
|
||||||
|
|
||||||
CurvePreferences: []tls.CurveID{
|
CurvePreferences: []tls.CurveID{
|
||||||
tls.X25519,
|
tls.X25519,
|
||||||
},
|
},
|
||||||
|
|
||||||
ClientAuth: tls.NoClientCert,
|
SessionTicketsDisabled: false,
|
||||||
NextProtos: nil,
|
ClientAuth: tls.NoClientCert,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,252 +0,0 @@
|
|||||||
package session
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"encoding/binary"
|
|
||||||
"fmt"
|
|
||||||
"log"
|
|
||||||
"net"
|
|
||||||
portUtil "tunnel_pls/internal/port"
|
|
||||||
"tunnel_pls/internal/random"
|
|
||||||
"tunnel_pls/types"
|
|
||||||
|
|
||||||
"golang.org/x/crypto/ssh"
|
|
||||||
)
|
|
||||||
|
|
||||||
var blockedReservedPorts = []uint16{1080, 1433, 1521, 1900, 2049, 3306, 3389, 5432, 5900, 6379, 8080, 8443, 9000, 9200, 27017}
|
|
||||||
|
|
||||||
func (s *session) HandleGlobalRequest(GlobalRequest <-chan *ssh.Request) {
|
|
||||||
for req := range GlobalRequest {
|
|
||||||
switch req.Type {
|
|
||||||
case "shell", "pty-req":
|
|
||||||
err := req.Reply(true, nil)
|
|
||||||
if err != nil {
|
|
||||||
log.Println("Failed to reply to request:", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
case "window-change":
|
|
||||||
p := req.Payload
|
|
||||||
if len(p) < 16 {
|
|
||||||
log.Println("invalid window-change payload")
|
|
||||||
err := req.Reply(false, nil)
|
|
||||||
if err != nil {
|
|
||||||
log.Println("Failed to reply to request:", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
cols := binary.BigEndian.Uint32(p[0:4])
|
|
||||||
rows := binary.BigEndian.Uint32(p[4:8])
|
|
||||||
|
|
||||||
s.interaction.SetWH(int(cols), int(rows))
|
|
||||||
|
|
||||||
err := req.Reply(true, nil)
|
|
||||||
if err != nil {
|
|
||||||
log.Println("Failed to reply to request:", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
log.Println("Unknown request type:", req.Type)
|
|
||||||
err := req.Reply(false, nil)
|
|
||||||
if err != nil {
|
|
||||||
log.Println("Failed to reply to request:", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *session) HandleTCPIPForward(req *ssh.Request) {
|
|
||||||
log.Println("Port forwarding request detected")
|
|
||||||
|
|
||||||
fail := func(msg string) {
|
|
||||||
log.Println(msg)
|
|
||||||
if err := req.Reply(false, nil); err != nil {
|
|
||||||
log.Println("Failed to reply to request:", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err := s.lifecycle.Close(); err != nil {
|
|
||||||
log.Printf("failed to close session: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
reader := bytes.NewReader(req.Payload)
|
|
||||||
|
|
||||||
addr, err := readSSHString(reader)
|
|
||||||
if err != nil {
|
|
||||||
fail(fmt.Sprintf("Failed to read address from payload: %v", err))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var rawPortToBind uint32
|
|
||||||
if err = binary.Read(reader, binary.BigEndian, &rawPortToBind); err != nil {
|
|
||||||
fail(fmt.Sprintf("Failed to read port from payload: %v", err))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if rawPortToBind > 65535 {
|
|
||||||
fail(fmt.Sprintf("Port %d is larger than allowed port of 65535", rawPortToBind))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
portToBind := uint16(rawPortToBind)
|
|
||||||
if isBlockedPort(portToBind) {
|
|
||||||
fail(fmt.Sprintf("Port %d is blocked or restricted", portToBind))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
switch portToBind {
|
|
||||||
case 80, 443:
|
|
||||||
s.HandleHTTPForward(req, portToBind)
|
|
||||||
default:
|
|
||||||
s.HandleTCPForward(req, addr, portToBind)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *session) HandleHTTPForward(req *ssh.Request, portToBind uint16) {
|
|
||||||
fail := func(msg string, key *types.SessionKey) {
|
|
||||||
log.Println(msg)
|
|
||||||
if key != nil {
|
|
||||||
s.registry.Remove(*key)
|
|
||||||
}
|
|
||||||
if err := req.Reply(false, nil); err != nil {
|
|
||||||
log.Println("Failed to reply to request:", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
slug := random.GenerateRandomString(20)
|
|
||||||
key := types.SessionKey{Id: slug, Type: types.HTTP}
|
|
||||||
if !s.registry.Register(key, s) {
|
|
||||||
fail(fmt.Sprintf("Failed to register client with slug: %s", slug), nil)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
buf := new(bytes.Buffer)
|
|
||||||
err := binary.Write(buf, binary.BigEndian, uint32(portToBind))
|
|
||||||
if err != nil {
|
|
||||||
fail(fmt.Sprintf("Failed to write port to buffer: %v", err), &key)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
log.Printf("HTTP forwarding approved on port: %d", portToBind)
|
|
||||||
|
|
||||||
err = req.Reply(true, buf.Bytes())
|
|
||||||
if err != nil {
|
|
||||||
fail(fmt.Sprintf("Failed to reply to request: %v", err), &key)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
s.forwarder.SetType(types.HTTP)
|
|
||||||
s.forwarder.SetForwardedPort(portToBind)
|
|
||||||
s.slug.Set(slug)
|
|
||||||
s.lifecycle.SetStatus(types.RUNNING)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *session) HandleTCPForward(req *ssh.Request, addr string, portToBind uint16) {
|
|
||||||
fail := func(msg string) {
|
|
||||||
log.Println(msg)
|
|
||||||
if err := req.Reply(false, nil); err != nil {
|
|
||||||
log.Println("Failed to reply to request:", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err := s.lifecycle.Close(); err != nil {
|
|
||||||
log.Printf("failed to close session: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
cleanup := func(msg string, port uint16, listener net.Listener, key *types.SessionKey) {
|
|
||||||
log.Println(msg)
|
|
||||||
if key != nil {
|
|
||||||
s.registry.Remove(*key)
|
|
||||||
}
|
|
||||||
if port != 0 {
|
|
||||||
if setErr := portUtil.Default.SetPortStatus(port, false); setErr != nil {
|
|
||||||
log.Printf("Failed to reset port status: %v", setErr)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if listener != nil {
|
|
||||||
if closeErr := listener.Close(); closeErr != nil {
|
|
||||||
log.Printf("Failed to close listener: %v", closeErr)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err := req.Reply(false, nil); err != nil {
|
|
||||||
log.Println("Failed to reply to request:", err)
|
|
||||||
}
|
|
||||||
_ = s.lifecycle.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
if portToBind == 0 {
|
|
||||||
unassigned, ok := portUtil.Default.GetUnassignedPort()
|
|
||||||
if !ok {
|
|
||||||
fail("No available port")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
portToBind = unassigned
|
|
||||||
}
|
|
||||||
|
|
||||||
if claimed := portUtil.Default.ClaimPort(portToBind); !claimed {
|
|
||||||
fail(fmt.Sprintf("Port %d is already in use or restricted", portToBind))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Printf("Requested forwarding on %s:%d", addr, portToBind)
|
|
||||||
listener, err := net.Listen("tcp", fmt.Sprintf("0.0.0.0:%d", portToBind))
|
|
||||||
if err != nil {
|
|
||||||
cleanup(fmt.Sprintf("Port %d is already in use or restricted", portToBind), portToBind, nil, nil)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
key := types.SessionKey{Id: fmt.Sprintf("%d", portToBind), Type: types.TCP}
|
|
||||||
|
|
||||||
if !s.registry.Register(key, s) {
|
|
||||||
cleanup(fmt.Sprintf("Failed to register TCP client with id: %s", key.Id), portToBind, listener, nil)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
buf := new(bytes.Buffer)
|
|
||||||
err = binary.Write(buf, binary.BigEndian, uint32(portToBind))
|
|
||||||
if err != nil {
|
|
||||||
cleanup(fmt.Sprintf("Failed to write port to buffer: %v", err), portToBind, listener, &key)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Printf("TCP forwarding approved on port: %d", portToBind)
|
|
||||||
err = req.Reply(true, buf.Bytes())
|
|
||||||
if err != nil {
|
|
||||||
cleanup(fmt.Sprintf("Failed to reply to request: %v", err), portToBind, listener, &key)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
s.forwarder.SetType(types.TCP)
|
|
||||||
s.forwarder.SetListener(listener)
|
|
||||||
s.forwarder.SetForwardedPort(portToBind)
|
|
||||||
s.slug.Set(key.Id)
|
|
||||||
s.lifecycle.SetStatus(types.RUNNING)
|
|
||||||
go s.forwarder.AcceptTCPConnections()
|
|
||||||
}
|
|
||||||
|
|
||||||
func readSSHString(reader *bytes.Reader) (string, error) {
|
|
||||||
var length uint32
|
|
||||||
if err := binary.Read(reader, binary.BigEndian, &length); err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
strBytes := make([]byte, length)
|
|
||||||
if _, err := reader.Read(strBytes); err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
return string(strBytes), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func isBlockedPort(port uint16) bool {
|
|
||||||
if port == 80 || port == 443 {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if port < 1024 && port != 0 {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
for _, p := range blockedReservedPorts {
|
|
||||||
if p == port {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
package interaction
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/charmbracelet/bubbles/textinput"
|
||||||
|
tea "github.com/charmbracelet/bubbletea"
|
||||||
|
"github.com/charmbracelet/lipgloss"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (m *model) comingSoonUpdate(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
|
||||||
|
m.showingComingSoon = false
|
||||||
|
return m, tea.Batch(tea.ClearScreen, textinput.Blink)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *model) comingSoonView() string {
|
||||||
|
isCompact := shouldUseCompactLayout(m.width, 60)
|
||||||
|
|
||||||
|
var boxPadding int
|
||||||
|
var boxMargin int
|
||||||
|
if isCompact {
|
||||||
|
boxPadding = 1
|
||||||
|
boxMargin = 1
|
||||||
|
} else {
|
||||||
|
boxPadding = 3
|
||||||
|
boxMargin = 2
|
||||||
|
}
|
||||||
|
|
||||||
|
titleStyle := lipgloss.NewStyle().
|
||||||
|
Bold(true).
|
||||||
|
Foreground(lipgloss.Color("#7D56F4")).
|
||||||
|
PaddingTop(1).
|
||||||
|
PaddingBottom(1)
|
||||||
|
|
||||||
|
messageBoxWidth := getResponsiveWidth(m.width, 10, 30, 60)
|
||||||
|
messageBoxStyle := lipgloss.NewStyle().
|
||||||
|
Foreground(lipgloss.Color("#FAFAFA")).
|
||||||
|
Background(lipgloss.Color("#1A1A2E")).
|
||||||
|
Bold(true).
|
||||||
|
Border(lipgloss.RoundedBorder()).
|
||||||
|
BorderForeground(lipgloss.Color("#7D56F4")).
|
||||||
|
Padding(1, boxPadding).
|
||||||
|
MarginTop(boxMargin).
|
||||||
|
MarginBottom(boxMargin).
|
||||||
|
Width(messageBoxWidth).
|
||||||
|
Align(lipgloss.Center)
|
||||||
|
|
||||||
|
helpStyle := lipgloss.NewStyle().
|
||||||
|
Foreground(lipgloss.Color("#666666")).
|
||||||
|
Italic(true).
|
||||||
|
MarginTop(1)
|
||||||
|
|
||||||
|
var b strings.Builder
|
||||||
|
b.WriteString("\n\n")
|
||||||
|
|
||||||
|
var title string
|
||||||
|
if shouldUseCompactLayout(m.width, 40) {
|
||||||
|
title = "Coming Soon"
|
||||||
|
} else {
|
||||||
|
title = "⏳ Coming Soon"
|
||||||
|
}
|
||||||
|
b.WriteString(titleStyle.Render(title))
|
||||||
|
b.WriteString("\n\n")
|
||||||
|
|
||||||
|
var message string
|
||||||
|
if shouldUseCompactLayout(m.width, 50) {
|
||||||
|
message = "Coming soon!\nStay tuned."
|
||||||
|
} else {
|
||||||
|
message = "🚀 This feature is coming very soon!\n Stay tuned for updates."
|
||||||
|
}
|
||||||
|
b.WriteString(messageBoxStyle.Render(message))
|
||||||
|
b.WriteString("\n\n")
|
||||||
|
|
||||||
|
var helpText string
|
||||||
|
if shouldUseCompactLayout(m.width, 60) {
|
||||||
|
helpText = "Press any key..."
|
||||||
|
} else {
|
||||||
|
helpText = "This message will disappear in 5 seconds or press any key..."
|
||||||
|
}
|
||||||
|
b.WriteString(helpStyle.Render(helpText))
|
||||||
|
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
package interaction
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/charmbracelet/bubbles/key"
|
||||||
|
"github.com/charmbracelet/bubbles/textinput"
|
||||||
|
tea "github.com/charmbracelet/bubbletea"
|
||||||
|
"github.com/charmbracelet/lipgloss"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (m *model) commandsUpdate(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
|
||||||
|
var cmd tea.Cmd
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case key.Matches(msg, m.keymap.quit):
|
||||||
|
m.showingCommands = false
|
||||||
|
return m, tea.Batch(tea.ClearScreen, textinput.Blink)
|
||||||
|
case msg.String() == "enter":
|
||||||
|
selectedItem := m.commandList.SelectedItem()
|
||||||
|
if selectedItem != nil {
|
||||||
|
item := selectedItem.(commandItem)
|
||||||
|
if item.name == "slug" {
|
||||||
|
m.showingCommands = false
|
||||||
|
m.editingSlug = true
|
||||||
|
m.slugInput.SetValue(m.interaction.slug.String())
|
||||||
|
m.slugInput.Focus()
|
||||||
|
return m, tea.Batch(tea.ClearScreen, textinput.Blink)
|
||||||
|
} else if item.name == "tunnel-type" {
|
||||||
|
m.showingCommands = false
|
||||||
|
m.showingComingSoon = true
|
||||||
|
return m, tea.Batch(tickCmd(5*time.Second), tea.ClearScreen, textinput.Blink)
|
||||||
|
}
|
||||||
|
m.showingCommands = false
|
||||||
|
return m, nil
|
||||||
|
}
|
||||||
|
case msg.String() == "esc":
|
||||||
|
m.showingCommands = false
|
||||||
|
return m, tea.Batch(tea.ClearScreen, textinput.Blink)
|
||||||
|
}
|
||||||
|
m.commandList, cmd = m.commandList.Update(msg)
|
||||||
|
return m, cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *model) commandsView() string {
|
||||||
|
isCompact := shouldUseCompactLayout(m.width, 60)
|
||||||
|
|
||||||
|
titleStyle := lipgloss.NewStyle().
|
||||||
|
Bold(true).
|
||||||
|
Foreground(lipgloss.Color("#7D56F4")).
|
||||||
|
PaddingTop(1).
|
||||||
|
PaddingBottom(1)
|
||||||
|
|
||||||
|
helpStyle := lipgloss.NewStyle().
|
||||||
|
Foreground(lipgloss.Color("#666666")).
|
||||||
|
Italic(true).
|
||||||
|
MarginTop(1)
|
||||||
|
|
||||||
|
var b strings.Builder
|
||||||
|
b.WriteString("\n")
|
||||||
|
|
||||||
|
var title string
|
||||||
|
if shouldUseCompactLayout(m.width, 40) {
|
||||||
|
title = "Commands"
|
||||||
|
} else {
|
||||||
|
title = "⚡ Commands"
|
||||||
|
}
|
||||||
|
b.WriteString(titleStyle.Render(title))
|
||||||
|
b.WriteString("\n\n")
|
||||||
|
b.WriteString(m.commandList.View())
|
||||||
|
b.WriteString("\n")
|
||||||
|
|
||||||
|
var helpText string
|
||||||
|
if isCompact {
|
||||||
|
helpText = "↑/↓ Nav • Enter Select • Esc Cancel"
|
||||||
|
} else {
|
||||||
|
helpText = "↑/↓ Navigate • Enter Select • Esc Cancel"
|
||||||
|
}
|
||||||
|
b.WriteString(helpStyle.Render(helpText))
|
||||||
|
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
@@ -0,0 +1,186 @@
|
|||||||
|
package interaction
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/charmbracelet/bubbles/key"
|
||||||
|
"github.com/charmbracelet/bubbles/textinput"
|
||||||
|
tea "github.com/charmbracelet/bubbletea"
|
||||||
|
"github.com/charmbracelet/lipgloss"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (m *model) dashboardUpdate(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
|
||||||
|
switch {
|
||||||
|
case key.Matches(msg, m.keymap.quit):
|
||||||
|
m.quitting = true
|
||||||
|
return m, tea.Batch(tea.ClearScreen, textinput.Blink, tea.Quit)
|
||||||
|
case key.Matches(msg, m.keymap.command):
|
||||||
|
m.showingCommands = true
|
||||||
|
return m, tea.Batch(tea.ClearScreen, textinput.Blink)
|
||||||
|
}
|
||||||
|
return m, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *model) dashboardView() string {
|
||||||
|
titleStyle := lipgloss.NewStyle().
|
||||||
|
Bold(true).
|
||||||
|
Foreground(lipgloss.Color("#7D56F4")).
|
||||||
|
PaddingTop(1)
|
||||||
|
|
||||||
|
subtitleStyle := lipgloss.NewStyle().
|
||||||
|
Foreground(lipgloss.Color("#888888")).
|
||||||
|
Italic(true)
|
||||||
|
|
||||||
|
urlStyle := lipgloss.NewStyle().
|
||||||
|
Foreground(lipgloss.Color("#7D56F4")).
|
||||||
|
Underline(true).
|
||||||
|
Italic(true)
|
||||||
|
|
||||||
|
urlBoxStyle := lipgloss.NewStyle().
|
||||||
|
Foreground(lipgloss.Color("#04B575")).
|
||||||
|
Bold(true).
|
||||||
|
Italic(true)
|
||||||
|
|
||||||
|
keyHintStyle := lipgloss.NewStyle().
|
||||||
|
Foreground(lipgloss.Color("#7D56F4")).
|
||||||
|
Bold(true)
|
||||||
|
|
||||||
|
var b strings.Builder
|
||||||
|
|
||||||
|
isCompact := shouldUseCompactLayout(m.width, 85)
|
||||||
|
|
||||||
|
var asciiArtMargin int
|
||||||
|
if isCompact {
|
||||||
|
asciiArtMargin = 0
|
||||||
|
} else {
|
||||||
|
asciiArtMargin = 1
|
||||||
|
}
|
||||||
|
|
||||||
|
asciiArtStyle := lipgloss.NewStyle().
|
||||||
|
Bold(true).
|
||||||
|
Foreground(lipgloss.Color("#7D56F4")).
|
||||||
|
MarginBottom(asciiArtMargin)
|
||||||
|
|
||||||
|
var asciiArt string
|
||||||
|
if shouldUseCompactLayout(m.width, 50) {
|
||||||
|
asciiArt = "TUNNEL PLS"
|
||||||
|
} else if isCompact {
|
||||||
|
asciiArt = `
|
||||||
|
▀█▀ █ █ █▄ █ █▄ █ ██▀ █ ▄▀▀ █ ▄▀▀
|
||||||
|
█ ▀▄█ █ ▀█ █ ▀█ █▄▄ █▄▄ ▄█▀ █▄▄ ▄█▀`
|
||||||
|
} else {
|
||||||
|
asciiArt = `
|
||||||
|
████████╗██╗ ██╗███╗ ██╗███╗ ██╗███████╗██╗ ██████╗ ██╗ ███████╗
|
||||||
|
╚══██╔══╝██║ ██║████╗ ██║████╗ ██║██╔════╝██║ ██╔══██╗██║ ██╔════╝
|
||||||
|
██║ ██║ ██║██╔██╗ ██║██╔██╗ ██║█████╗ ██║ ██████╔╝██║ ███████╗
|
||||||
|
██║ ██║ ██║██║╚██╗██║██║╚██╗██║██╔══╝ ██║ ██╔═══╝ ██║ ╚════██║
|
||||||
|
██║ ╚██████╔╝██║ ╚████║██║ ╚████║███████╗███████╗ ██║ ███████╗███████║
|
||||||
|
╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚═╝ ╚═══╝╚══════╝╚══════╝ ╚═╝ ╚══════╝╚══════╝`
|
||||||
|
}
|
||||||
|
|
||||||
|
b.WriteString(asciiArtStyle.Render(asciiArt))
|
||||||
|
b.WriteString("\n")
|
||||||
|
|
||||||
|
if !shouldUseCompactLayout(m.width, 60) {
|
||||||
|
b.WriteString(subtitleStyle.Render("Secure tunnel service by Bagas • "))
|
||||||
|
b.WriteString(urlStyle.Render("https://fossy.my.id"))
|
||||||
|
b.WriteString("\n\n")
|
||||||
|
} else {
|
||||||
|
b.WriteString("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
boxMaxWidth := getResponsiveWidth(m.width, 10, 40, 80)
|
||||||
|
var boxPadding int
|
||||||
|
var boxMargin int
|
||||||
|
if isCompact {
|
||||||
|
boxPadding = 1
|
||||||
|
boxMargin = 1
|
||||||
|
} else {
|
||||||
|
boxPadding = 2
|
||||||
|
boxMargin = 2
|
||||||
|
}
|
||||||
|
|
||||||
|
responsiveInfoBox := lipgloss.NewStyle().
|
||||||
|
Border(lipgloss.RoundedBorder()).
|
||||||
|
BorderForeground(lipgloss.Color("#7D56F4")).
|
||||||
|
Padding(1, boxPadding).
|
||||||
|
MarginTop(boxMargin).
|
||||||
|
MarginBottom(boxMargin).
|
||||||
|
Width(boxMaxWidth)
|
||||||
|
|
||||||
|
authenticatedUser := m.interaction.lifecycle.User()
|
||||||
|
|
||||||
|
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\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("👤 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")
|
||||||
|
|
||||||
|
var quickActionsTitle string
|
||||||
|
if shouldUseCompactLayout(m.width, 50) {
|
||||||
|
quickActionsTitle = "Actions"
|
||||||
|
} else if isCompact {
|
||||||
|
quickActionsTitle = "Quick Actions"
|
||||||
|
} else {
|
||||||
|
quickActionsTitle = "✨ Quick Actions"
|
||||||
|
}
|
||||||
|
b.WriteString(titleStyle.Render(quickActionsTitle))
|
||||||
|
b.WriteString("\n")
|
||||||
|
|
||||||
|
var featureMargin int
|
||||||
|
if isCompact {
|
||||||
|
featureMargin = 1
|
||||||
|
} else {
|
||||||
|
featureMargin = 2
|
||||||
|
}
|
||||||
|
|
||||||
|
compactFeatureStyle := lipgloss.NewStyle().
|
||||||
|
Foreground(lipgloss.Color("#FAFAFA")).
|
||||||
|
MarginLeft(featureMargin)
|
||||||
|
|
||||||
|
var commandsText string
|
||||||
|
var quitText string
|
||||||
|
if shouldUseCompactLayout(m.width, 60) {
|
||||||
|
commandsText = fmt.Sprintf(" %s Commands", keyHintStyle.Render("[C]"))
|
||||||
|
quitText = fmt.Sprintf(" %s Quit", keyHintStyle.Render("[Q]"))
|
||||||
|
} else {
|
||||||
|
commandsText = fmt.Sprintf(" %s Open commands menu", keyHintStyle.Render("[C]"))
|
||||||
|
quitText = fmt.Sprintf(" %s Quit application", keyHintStyle.Render("[Q]"))
|
||||||
|
}
|
||||||
|
|
||||||
|
b.WriteString(compactFeatureStyle.Render(commandsText))
|
||||||
|
b.WriteString("\n")
|
||||||
|
b.WriteString(compactFeatureStyle.Render(quitText))
|
||||||
|
|
||||||
|
if !shouldUseCompactLayout(m.width, 70) {
|
||||||
|
b.WriteString("\n\n")
|
||||||
|
footerStyle := lipgloss.NewStyle().
|
||||||
|
Foreground(lipgloss.Color("#666666")).
|
||||||
|
Italic(true)
|
||||||
|
b.WriteString(footerStyle.Render("Press 'C' to customize your tunnel settings"))
|
||||||
|
}
|
||||||
|
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
@@ -2,12 +2,8 @@ package interaction
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
|
||||||
"log"
|
"log"
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
"tunnel_pls/internal/config"
|
"tunnel_pls/internal/config"
|
||||||
"tunnel_pls/internal/random"
|
|
||||||
"tunnel_pls/session/slug"
|
"tunnel_pls/session/slug"
|
||||||
"tunnel_pls/types"
|
"tunnel_pls/types"
|
||||||
|
|
||||||
@@ -84,45 +80,6 @@ func (i *interaction) SetWH(w, h int) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type commandItem struct {
|
|
||||||
name string
|
|
||||||
desc string
|
|
||||||
}
|
|
||||||
|
|
||||||
type model struct {
|
|
||||||
domain string
|
|
||||||
protocol string
|
|
||||||
tunnelType types.TunnelType
|
|
||||||
port uint16
|
|
||||||
keymap keymap
|
|
||||||
help help.Model
|
|
||||||
quitting bool
|
|
||||||
showingCommands bool
|
|
||||||
editingSlug bool
|
|
||||||
showingComingSoon bool
|
|
||||||
commandList list.Model
|
|
||||||
slugInput textinput.Model
|
|
||||||
slugError string
|
|
||||||
interaction *interaction
|
|
||||||
width int
|
|
||||||
height int
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *model) getTunnelURL() string {
|
|
||||||
if m.tunnelType == types.HTTP {
|
|
||||||
return buildURL(m.protocol, m.interaction.slug.String(), m.domain)
|
|
||||||
}
|
|
||||||
return fmt.Sprintf("tcp://%s:%d", m.domain, m.port)
|
|
||||||
}
|
|
||||||
|
|
||||||
type keymap struct {
|
|
||||||
quit key.Binding
|
|
||||||
command key.Binding
|
|
||||||
random key.Binding
|
|
||||||
}
|
|
||||||
|
|
||||||
type tickMsg time.Time
|
|
||||||
|
|
||||||
func New(slug slug.Slug, forwarder Forwarder) Interaction {
|
func New(slug slug.Slug, forwarder Forwarder) Interaction {
|
||||||
ctx, cancel := context.WithCancel(context.Background())
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
return &interaction{
|
return &interaction{
|
||||||
@@ -159,47 +116,7 @@ func (i *interaction) Stop() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func getResponsiveWidth(screenWidth, padding, minWidth, maxWidth int) int {
|
|
||||||
width := screenWidth - padding
|
|
||||||
if width > maxWidth {
|
|
||||||
width = maxWidth
|
|
||||||
}
|
|
||||||
if width < minWidth {
|
|
||||||
width = minWidth
|
|
||||||
}
|
|
||||||
return width
|
|
||||||
}
|
|
||||||
|
|
||||||
func shouldUseCompactLayout(width int, threshold int) bool {
|
|
||||||
return width < threshold
|
|
||||||
}
|
|
||||||
|
|
||||||
func truncateString(s string, maxLength int) string {
|
|
||||||
if len(s) <= maxLength {
|
|
||||||
return s
|
|
||||||
}
|
|
||||||
if maxLength < 4 {
|
|
||||||
return s[:maxLength]
|
|
||||||
}
|
|
||||||
return s[:maxLength-3] + "..."
|
|
||||||
}
|
|
||||||
|
|
||||||
func (i commandItem) FilterValue() string { return i.name }
|
|
||||||
func (i commandItem) Title() string { return i.name }
|
|
||||||
func (i commandItem) Description() string { return i.desc }
|
|
||||||
|
|
||||||
func tickCmd(d time.Duration) tea.Cmd {
|
|
||||||
return tea.Tick(d, func(t time.Time) tea.Msg {
|
|
||||||
return tickMsg(t)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
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) {
|
switch msg := msg.(type) {
|
||||||
case tickMsg:
|
case tickMsg:
|
||||||
@@ -225,93 +142,18 @@ func (m *model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
|
|
||||||
case tea.KeyMsg:
|
case tea.KeyMsg:
|
||||||
if m.showingComingSoon {
|
if m.showingComingSoon {
|
||||||
m.showingComingSoon = false
|
return m.comingSoonUpdate(msg)
|
||||||
return m, tea.Batch(tea.ClearScreen, textinput.Blink)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if m.editingSlug {
|
if m.editingSlug {
|
||||||
if m.tunnelType != types.HTTP {
|
return m.slugUpdate(msg)
|
||||||
m.editingSlug = false
|
|
||||||
m.slugError = ""
|
|
||||||
return m, tea.Batch(tea.ClearScreen, textinput.Blink)
|
|
||||||
}
|
|
||||||
switch msg.String() {
|
|
||||||
case "esc":
|
|
||||||
m.editingSlug = false
|
|
||||||
m.slugError = ""
|
|
||||||
return m, tea.Batch(tea.ClearScreen, textinput.Blink)
|
|
||||||
case "enter":
|
|
||||||
inputValue := m.slugInput.Value()
|
|
||||||
if err := m.interaction.sessionRegistry.Update(m.interaction.lifecycle.User(), types.SessionKey{
|
|
||||||
Id: m.interaction.slug.String(),
|
|
||||||
Type: types.HTTP,
|
|
||||||
}, types.SessionKey{
|
|
||||||
Id: inputValue,
|
|
||||||
Type: types.HTTP,
|
|
||||||
}); err != nil {
|
|
||||||
m.slugError = err.Error()
|
|
||||||
return m, nil
|
|
||||||
}
|
|
||||||
m.editingSlug = false
|
|
||||||
m.slugError = ""
|
|
||||||
return m, tea.Batch(tea.ClearScreen, textinput.Blink)
|
|
||||||
case "ctrl+c":
|
|
||||||
m.editingSlug = false
|
|
||||||
m.slugError = ""
|
|
||||||
return m, tea.Batch(tea.ClearScreen, textinput.Blink)
|
|
||||||
default:
|
|
||||||
if key.Matches(msg, m.keymap.random) {
|
|
||||||
newSubdomain := generateRandomSubdomain()
|
|
||||||
m.slugInput.SetValue(newSubdomain)
|
|
||||||
m.slugError = ""
|
|
||||||
m.slugInput, cmd = m.slugInput.Update(msg)
|
|
||||||
return m, cmd
|
|
||||||
}
|
|
||||||
m.slugError = ""
|
|
||||||
m.slugInput, cmd = m.slugInput.Update(msg)
|
|
||||||
return m, cmd
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if m.showingCommands {
|
if m.showingCommands {
|
||||||
switch {
|
return m.commandsUpdate(msg)
|
||||||
case key.Matches(msg, m.keymap.quit):
|
|
||||||
m.showingCommands = false
|
|
||||||
return m, tea.Batch(tea.ClearScreen, textinput.Blink)
|
|
||||||
case msg.String() == "enter":
|
|
||||||
selectedItem := m.commandList.SelectedItem()
|
|
||||||
if selectedItem != nil {
|
|
||||||
item := selectedItem.(commandItem)
|
|
||||||
if item.name == "slug" {
|
|
||||||
m.showingCommands = false
|
|
||||||
m.editingSlug = true
|
|
||||||
m.slugInput.SetValue(m.interaction.slug.String())
|
|
||||||
m.slugInput.Focus()
|
|
||||||
return m, tea.Batch(tea.ClearScreen, textinput.Blink)
|
|
||||||
} else if item.name == "tunnel-type" {
|
|
||||||
m.showingCommands = false
|
|
||||||
m.showingComingSoon = true
|
|
||||||
return m, tea.Batch(tickCmd(5*time.Second), tea.ClearScreen, textinput.Blink)
|
|
||||||
}
|
|
||||||
m.showingCommands = false
|
|
||||||
return m, nil
|
|
||||||
}
|
|
||||||
case msg.String() == "esc":
|
|
||||||
m.showingCommands = false
|
|
||||||
return m, tea.Batch(tea.ClearScreen, textinput.Blink)
|
|
||||||
}
|
|
||||||
m.commandList, cmd = m.commandList.Update(msg)
|
|
||||||
return m, cmd
|
|
||||||
}
|
}
|
||||||
|
|
||||||
switch {
|
return m.dashboardUpdate(msg)
|
||||||
case key.Matches(msg, m.keymap.quit):
|
|
||||||
m.quitting = true
|
|
||||||
return m, tea.Batch(tea.ClearScreen, textinput.Blink, tea.Quit)
|
|
||||||
case key.Matches(msg, m.keymap.command):
|
|
||||||
m.showingCommands = true
|
|
||||||
return m, tea.Batch(tea.ClearScreen, textinput.Blink)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return m, nil
|
return m, nil
|
||||||
@@ -323,448 +165,24 @@ func (i *interaction) Redraw() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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 {
|
if m.quitting {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
if m.showingComingSoon {
|
if m.showingComingSoon {
|
||||||
isCompact := shouldUseCompactLayout(m.width, 60)
|
return m.comingSoonView()
|
||||||
|
|
||||||
var boxPadding int
|
|
||||||
var boxMargin int
|
|
||||||
if isCompact {
|
|
||||||
boxPadding = 1
|
|
||||||
boxMargin = 1
|
|
||||||
} else {
|
|
||||||
boxPadding = 3
|
|
||||||
boxMargin = 2
|
|
||||||
}
|
|
||||||
|
|
||||||
titleStyle := lipgloss.NewStyle().
|
|
||||||
Bold(true).
|
|
||||||
Foreground(lipgloss.Color("#7D56F4")).
|
|
||||||
PaddingTop(1).
|
|
||||||
PaddingBottom(1)
|
|
||||||
|
|
||||||
messageBoxWidth := getResponsiveWidth(m.width, 10, 30, 60)
|
|
||||||
messageBoxStyle := lipgloss.NewStyle().
|
|
||||||
Foreground(lipgloss.Color("#FAFAFA")).
|
|
||||||
Background(lipgloss.Color("#1A1A2E")).
|
|
||||||
Bold(true).
|
|
||||||
Border(lipgloss.RoundedBorder()).
|
|
||||||
BorderForeground(lipgloss.Color("#7D56F4")).
|
|
||||||
Padding(1, boxPadding).
|
|
||||||
MarginTop(boxMargin).
|
|
||||||
MarginBottom(boxMargin).
|
|
||||||
Width(messageBoxWidth).
|
|
||||||
Align(lipgloss.Center)
|
|
||||||
|
|
||||||
helpStyle := lipgloss.NewStyle().
|
|
||||||
Foreground(lipgloss.Color("#666666")).
|
|
||||||
Italic(true).
|
|
||||||
MarginTop(1)
|
|
||||||
|
|
||||||
var b strings.Builder
|
|
||||||
b.WriteString("\n\n")
|
|
||||||
|
|
||||||
var title string
|
|
||||||
if shouldUseCompactLayout(m.width, 40) {
|
|
||||||
title = "Coming Soon"
|
|
||||||
} else {
|
|
||||||
title = "⏳ Coming Soon"
|
|
||||||
}
|
|
||||||
b.WriteString(titleStyle.Render(title))
|
|
||||||
b.WriteString("\n\n")
|
|
||||||
|
|
||||||
var message string
|
|
||||||
if shouldUseCompactLayout(m.width, 50) {
|
|
||||||
message = "Coming soon!\nStay tuned."
|
|
||||||
} else {
|
|
||||||
message = "🚀 This feature is coming very soon!\n Stay tuned for updates."
|
|
||||||
}
|
|
||||||
b.WriteString(messageBoxStyle.Render(message))
|
|
||||||
b.WriteString("\n\n")
|
|
||||||
|
|
||||||
var helpText string
|
|
||||||
if shouldUseCompactLayout(m.width, 60) {
|
|
||||||
helpText = "Press any key..."
|
|
||||||
} else {
|
|
||||||
helpText = "This message will disappear in 5 seconds or press any key..."
|
|
||||||
}
|
|
||||||
b.WriteString(helpStyle.Render(helpText))
|
|
||||||
|
|
||||||
return b.String()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if m.editingSlug {
|
if m.editingSlug {
|
||||||
isCompact := shouldUseCompactLayout(m.width, 70)
|
return m.slugView()
|
||||||
isVeryCompact := shouldUseCompactLayout(m.width, 50)
|
|
||||||
|
|
||||||
var boxPadding int
|
|
||||||
var boxMargin int
|
|
||||||
if isVeryCompact {
|
|
||||||
boxPadding = 1
|
|
||||||
boxMargin = 1
|
|
||||||
} else if isCompact {
|
|
||||||
boxPadding = 1
|
|
||||||
boxMargin = 1
|
|
||||||
} else {
|
|
||||||
boxPadding = 2
|
|
||||||
boxMargin = 2
|
|
||||||
}
|
|
||||||
|
|
||||||
titleStyle := lipgloss.NewStyle().
|
|
||||||
Bold(true).
|
|
||||||
Foreground(lipgloss.Color("#7D56F4")).
|
|
||||||
PaddingTop(1).
|
|
||||||
PaddingBottom(1)
|
|
||||||
|
|
||||||
instructionStyle := lipgloss.NewStyle().
|
|
||||||
Foreground(lipgloss.Color("#FAFAFA")).
|
|
||||||
MarginTop(1)
|
|
||||||
|
|
||||||
inputBoxStyle := lipgloss.NewStyle().
|
|
||||||
Border(lipgloss.RoundedBorder()).
|
|
||||||
BorderForeground(lipgloss.Color("#7D56F4")).
|
|
||||||
Padding(1, boxPadding).
|
|
||||||
MarginTop(boxMargin).
|
|
||||||
MarginBottom(boxMargin)
|
|
||||||
|
|
||||||
helpStyle := lipgloss.NewStyle().
|
|
||||||
Foreground(lipgloss.Color("#666666")).
|
|
||||||
Italic(true).
|
|
||||||
MarginTop(1)
|
|
||||||
|
|
||||||
errorBoxStyle := lipgloss.NewStyle().
|
|
||||||
Foreground(lipgloss.Color("#FF0000")).
|
|
||||||
Background(lipgloss.Color("#3D0000")).
|
|
||||||
Bold(true).
|
|
||||||
Border(lipgloss.RoundedBorder()).
|
|
||||||
BorderForeground(lipgloss.Color("#FF0000")).
|
|
||||||
Padding(0, boxPadding).
|
|
||||||
MarginTop(1).
|
|
||||||
MarginBottom(1)
|
|
||||||
|
|
||||||
rulesBoxWidth := getResponsiveWidth(m.width, 10, 30, 60)
|
|
||||||
rulesBoxStyle := lipgloss.NewStyle().
|
|
||||||
Foreground(lipgloss.Color("#FAFAFA")).
|
|
||||||
Border(lipgloss.RoundedBorder()).
|
|
||||||
BorderForeground(lipgloss.Color("#7D56F4")).
|
|
||||||
Padding(0, boxPadding).
|
|
||||||
MarginTop(1).
|
|
||||||
MarginBottom(1).
|
|
||||||
Width(rulesBoxWidth)
|
|
||||||
|
|
||||||
var b strings.Builder
|
|
||||||
var title string
|
|
||||||
if isVeryCompact {
|
|
||||||
title = "Edit Subdomain"
|
|
||||||
} else {
|
|
||||||
title = "🔧 Edit Subdomain"
|
|
||||||
}
|
|
||||||
b.WriteString(titleStyle.Render(title))
|
|
||||||
b.WriteString("\n\n")
|
|
||||||
|
|
||||||
if m.tunnelType != types.HTTP {
|
|
||||||
warningBoxWidth := getResponsiveWidth(m.width, 10, 30, 60)
|
|
||||||
warningBoxStyle := lipgloss.NewStyle().
|
|
||||||
Foreground(lipgloss.Color("#FFA500")).
|
|
||||||
Background(lipgloss.Color("#3D2000")).
|
|
||||||
Bold(true).
|
|
||||||
Border(lipgloss.RoundedBorder()).
|
|
||||||
BorderForeground(lipgloss.Color("#FFA500")).
|
|
||||||
Padding(1, boxPadding).
|
|
||||||
MarginTop(boxMargin).
|
|
||||||
MarginBottom(boxMargin).
|
|
||||||
Width(warningBoxWidth)
|
|
||||||
|
|
||||||
var warningText string
|
|
||||||
if isVeryCompact {
|
|
||||||
warningText = "⚠️ TCP tunnels don't support custom subdomains."
|
|
||||||
} else {
|
|
||||||
warningText = "⚠️ TCP tunnels cannot have custom subdomains. Only HTTP/HTTPS tunnels support subdomain customization."
|
|
||||||
}
|
|
||||||
b.WriteString(warningBoxStyle.Render(warningText))
|
|
||||||
b.WriteString("\n\n")
|
|
||||||
|
|
||||||
var helpText string
|
|
||||||
if isVeryCompact {
|
|
||||||
helpText = "Press any key to go back"
|
|
||||||
} else {
|
|
||||||
helpText = "Press Enter or Esc to go back"
|
|
||||||
}
|
|
||||||
b.WriteString(helpStyle.Render(helpText))
|
|
||||||
return b.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
var rulesContent string
|
|
||||||
if isVeryCompact {
|
|
||||||
rulesContent = "Rules:\n3-20 chars\na-z, 0-9, -\nNo leading/trailing -"
|
|
||||||
} else if isCompact {
|
|
||||||
rulesContent = "📋 Rules:\n • 3-20 chars\n • a-z, 0-9, -\n • No leading/trailing -"
|
|
||||||
} else {
|
|
||||||
rulesContent = "📋 Rules: \n\t• 3-20 chars \n\t• a-z, 0-9, - \n\t• No leading/trailing -"
|
|
||||||
}
|
|
||||||
b.WriteString(rulesBoxStyle.Render(rulesContent))
|
|
||||||
b.WriteString("\n")
|
|
||||||
|
|
||||||
var instruction string
|
|
||||||
if isVeryCompact {
|
|
||||||
instruction = "Custom subdomain:"
|
|
||||||
} else {
|
|
||||||
instruction = "Enter your custom subdomain:"
|
|
||||||
}
|
|
||||||
b.WriteString(instructionStyle.Render(instruction))
|
|
||||||
b.WriteString("\n")
|
|
||||||
|
|
||||||
if m.slugError != "" {
|
|
||||||
errorInputBoxStyle := lipgloss.NewStyle().
|
|
||||||
Border(lipgloss.RoundedBorder()).
|
|
||||||
BorderForeground(lipgloss.Color("#FF0000")).
|
|
||||||
Padding(1, boxPadding).
|
|
||||||
MarginTop(boxMargin).
|
|
||||||
MarginBottom(1)
|
|
||||||
b.WriteString(errorInputBoxStyle.Render(m.slugInput.View()))
|
|
||||||
b.WriteString("\n")
|
|
||||||
b.WriteString(errorBoxStyle.Render("❌ " + m.slugError))
|
|
||||||
b.WriteString("\n")
|
|
||||||
} else {
|
|
||||||
b.WriteString(inputBoxStyle.Render(m.slugInput.View()))
|
|
||||||
b.WriteString("\n")
|
|
||||||
}
|
|
||||||
|
|
||||||
previewURL := buildURL(m.protocol, m.slugInput.Value(), m.domain)
|
|
||||||
previewWidth := getResponsiveWidth(m.width, 10, 30, 80)
|
|
||||||
|
|
||||||
if len(previewURL) > previewWidth-10 {
|
|
||||||
previewURL = truncateString(previewURL, previewWidth-10)
|
|
||||||
}
|
|
||||||
|
|
||||||
previewStyle := lipgloss.NewStyle().
|
|
||||||
Foreground(lipgloss.Color("#04B575")).
|
|
||||||
Italic(true).
|
|
||||||
Width(previewWidth)
|
|
||||||
b.WriteString(previewStyle.Render(fmt.Sprintf("Preview: %s", previewURL)))
|
|
||||||
b.WriteString("\n")
|
|
||||||
|
|
||||||
var helpText string
|
|
||||||
if isVeryCompact {
|
|
||||||
helpText = "Enter: save • CTRL+R: random • Esc: cancel"
|
|
||||||
} else {
|
|
||||||
helpText = "Press Enter to save • CTRL+R for random • Esc to cancel"
|
|
||||||
}
|
|
||||||
b.WriteString(helpStyle.Render(helpText))
|
|
||||||
|
|
||||||
return b.String()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if m.showingCommands {
|
if m.showingCommands {
|
||||||
isCompact := shouldUseCompactLayout(m.width, 60)
|
return m.commandsView()
|
||||||
|
|
||||||
titleStyle := lipgloss.NewStyle().
|
|
||||||
Bold(true).
|
|
||||||
Foreground(lipgloss.Color("#7D56F4")).
|
|
||||||
PaddingTop(1).
|
|
||||||
PaddingBottom(1)
|
|
||||||
|
|
||||||
helpStyle := lipgloss.NewStyle().
|
|
||||||
Foreground(lipgloss.Color("#666666")).
|
|
||||||
Italic(true).
|
|
||||||
MarginTop(1)
|
|
||||||
|
|
||||||
var b strings.Builder
|
|
||||||
b.WriteString("\n")
|
|
||||||
|
|
||||||
var title string
|
|
||||||
if shouldUseCompactLayout(m.width, 40) {
|
|
||||||
title = "Commands"
|
|
||||||
} else {
|
|
||||||
title = "⚡ Commands"
|
|
||||||
}
|
|
||||||
b.WriteString(titleStyle.Render(title))
|
|
||||||
b.WriteString("\n\n")
|
|
||||||
b.WriteString(m.commandList.View())
|
|
||||||
b.WriteString("\n")
|
|
||||||
|
|
||||||
var helpText string
|
|
||||||
if isCompact {
|
|
||||||
helpText = "↑/↓ Nav • Enter Select • Esc Cancel"
|
|
||||||
} else {
|
|
||||||
helpText = "↑/↓ Navigate • Enter Select • Esc Cancel"
|
|
||||||
}
|
|
||||||
b.WriteString(helpStyle.Render(helpText))
|
|
||||||
|
|
||||||
return b.String()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
titleStyle := lipgloss.NewStyle().
|
return m.dashboardView()
|
||||||
Bold(true).
|
|
||||||
Foreground(lipgloss.Color("#7D56F4")).
|
|
||||||
PaddingTop(1)
|
|
||||||
|
|
||||||
subtitleStyle := lipgloss.NewStyle().
|
|
||||||
Foreground(lipgloss.Color("#888888")).
|
|
||||||
Italic(true)
|
|
||||||
|
|
||||||
urlStyle := lipgloss.NewStyle().
|
|
||||||
Foreground(lipgloss.Color("#7D56F4")).
|
|
||||||
Underline(true).
|
|
||||||
Italic(true)
|
|
||||||
|
|
||||||
urlBoxStyle := lipgloss.NewStyle().
|
|
||||||
Foreground(lipgloss.Color("#04B575")).
|
|
||||||
Bold(true).
|
|
||||||
Italic(true)
|
|
||||||
|
|
||||||
keyHintStyle := lipgloss.NewStyle().
|
|
||||||
Foreground(lipgloss.Color("#7D56F4")).
|
|
||||||
Bold(true)
|
|
||||||
|
|
||||||
var b strings.Builder
|
|
||||||
|
|
||||||
isCompact := shouldUseCompactLayout(m.width, 85)
|
|
||||||
|
|
||||||
var asciiArtMargin int
|
|
||||||
if isCompact {
|
|
||||||
asciiArtMargin = 0
|
|
||||||
} else {
|
|
||||||
asciiArtMargin = 1
|
|
||||||
}
|
|
||||||
|
|
||||||
asciiArtStyle := lipgloss.NewStyle().
|
|
||||||
Bold(true).
|
|
||||||
Foreground(lipgloss.Color("#7D56F4")).
|
|
||||||
MarginBottom(asciiArtMargin)
|
|
||||||
|
|
||||||
var asciiArt string
|
|
||||||
if shouldUseCompactLayout(m.width, 50) {
|
|
||||||
asciiArt = "TUNNEL PLS"
|
|
||||||
} else if isCompact {
|
|
||||||
asciiArt = `
|
|
||||||
▀█▀ █ █ █▄ █ █▄ █ ██▀ █ ▄▀▀ █ ▄▀▀
|
|
||||||
█ ▀▄█ █ ▀█ █ ▀█ █▄▄ █▄▄ ▄█▀ █▄▄ ▄█▀`
|
|
||||||
} else {
|
|
||||||
asciiArt = `
|
|
||||||
████████╗██╗ ██╗███╗ ██╗███╗ ██╗███████╗██╗ ██████╗ ██╗ ███████╗
|
|
||||||
╚══██╔══╝██║ ██║████╗ ██║████╗ ██║██╔════╝██║ ██╔══██╗██║ ██╔════╝
|
|
||||||
██║ ██║ ██║██╔██╗ ██║██╔██╗ ██║█████╗ ██║ ██████╔╝██║ ███████╗
|
|
||||||
██║ ██║ ██║██║╚██╗██║██║╚██╗██║██╔══╝ ██║ ██╔═══╝ ██║ ╚════██║
|
|
||||||
██║ ╚██████╔╝██║ ╚████║██║ ╚████║███████╗███████╗ ██║ ███████╗███████║
|
|
||||||
╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚═╝ ╚═══╝╚══════╝╚══════╝ ╚═╝ ╚══════╝╚══════╝`
|
|
||||||
}
|
|
||||||
|
|
||||||
b.WriteString(asciiArtStyle.Render(asciiArt))
|
|
||||||
b.WriteString("\n")
|
|
||||||
|
|
||||||
if !shouldUseCompactLayout(m.width, 60) {
|
|
||||||
b.WriteString(subtitleStyle.Render("Secure tunnel service by Bagas • "))
|
|
||||||
b.WriteString(urlStyle.Render("https://fossy.my.id"))
|
|
||||||
b.WriteString("\n\n")
|
|
||||||
} else {
|
|
||||||
b.WriteString("\n")
|
|
||||||
}
|
|
||||||
|
|
||||||
boxMaxWidth := getResponsiveWidth(m.width, 10, 40, 80)
|
|
||||||
var boxPadding int
|
|
||||||
var boxMargin int
|
|
||||||
if isCompact {
|
|
||||||
boxPadding = 1
|
|
||||||
boxMargin = 1
|
|
||||||
} else {
|
|
||||||
boxPadding = 2
|
|
||||||
boxMargin = 2
|
|
||||||
}
|
|
||||||
|
|
||||||
responsiveInfoBox := lipgloss.NewStyle().
|
|
||||||
Border(lipgloss.RoundedBorder()).
|
|
||||||
BorderForeground(lipgloss.Color("#7D56F4")).
|
|
||||||
Padding(1, boxPadding).
|
|
||||||
MarginTop(boxMargin).
|
|
||||||
MarginBottom(boxMargin).
|
|
||||||
Width(boxMaxWidth)
|
|
||||||
|
|
||||||
authenticatedUser := m.interaction.lifecycle.User()
|
|
||||||
|
|
||||||
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\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("👤 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")
|
|
||||||
|
|
||||||
var quickActionsTitle string
|
|
||||||
if shouldUseCompactLayout(m.width, 50) {
|
|
||||||
quickActionsTitle = "Actions"
|
|
||||||
} else if isCompact {
|
|
||||||
quickActionsTitle = "Quick Actions"
|
|
||||||
} else {
|
|
||||||
quickActionsTitle = "✨ Quick Actions"
|
|
||||||
}
|
|
||||||
b.WriteString(titleStyle.Render(quickActionsTitle))
|
|
||||||
b.WriteString("\n")
|
|
||||||
|
|
||||||
var featureMargin int
|
|
||||||
if isCompact {
|
|
||||||
featureMargin = 1
|
|
||||||
} else {
|
|
||||||
featureMargin = 2
|
|
||||||
}
|
|
||||||
|
|
||||||
compactFeatureStyle := lipgloss.NewStyle().
|
|
||||||
Foreground(lipgloss.Color("#FAFAFA")).
|
|
||||||
MarginLeft(featureMargin)
|
|
||||||
|
|
||||||
var commandsText string
|
|
||||||
var quitText string
|
|
||||||
if shouldUseCompactLayout(m.width, 60) {
|
|
||||||
commandsText = fmt.Sprintf(" %s Commands", keyHintStyle.Render("[C]"))
|
|
||||||
quitText = fmt.Sprintf(" %s Quit", keyHintStyle.Render("[Q]"))
|
|
||||||
} else {
|
|
||||||
commandsText = fmt.Sprintf(" %s Open commands menu", keyHintStyle.Render("[C]"))
|
|
||||||
quitText = fmt.Sprintf(" %s Quit application", keyHintStyle.Render("[Q]"))
|
|
||||||
}
|
|
||||||
|
|
||||||
b.WriteString(compactFeatureStyle.Render(commandsText))
|
|
||||||
b.WriteString("\n")
|
|
||||||
b.WriteString(compactFeatureStyle.Render(quitText))
|
|
||||||
|
|
||||||
if !shouldUseCompactLayout(m.width, 70) {
|
|
||||||
b.WriteString("\n\n")
|
|
||||||
footerStyle := lipgloss.NewStyle().
|
|
||||||
Foreground(lipgloss.Color("#666666")).
|
|
||||||
Italic(true)
|
|
||||||
b.WriteString(footerStyle.Render("Press 'C' to customize your tunnel settings"))
|
|
||||||
}
|
|
||||||
|
|
||||||
return b.String()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i *interaction) Start() {
|
func (i *interaction) Start() {
|
||||||
@@ -848,11 +266,3 @@ func (i *interaction) Start() {
|
|||||||
log.Printf("Cannot close session: %s \n", err)
|
log.Printf("Cannot close session: %s \n", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func buildURL(protocol, subdomain, domain string) string {
|
|
||||||
return fmt.Sprintf("%s://%s.%s", protocol, subdomain, domain)
|
|
||||||
}
|
|
||||||
|
|
||||||
func generateRandomSubdomain() string {
|
|
||||||
return random.GenerateRandomString(20)
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,95 @@
|
|||||||
|
package interaction
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
"tunnel_pls/types"
|
||||||
|
|
||||||
|
"github.com/charmbracelet/bubbles/help"
|
||||||
|
"github.com/charmbracelet/bubbles/key"
|
||||||
|
"github.com/charmbracelet/bubbles/list"
|
||||||
|
"github.com/charmbracelet/bubbles/textinput"
|
||||||
|
tea "github.com/charmbracelet/bubbletea"
|
||||||
|
)
|
||||||
|
|
||||||
|
type commandItem struct {
|
||||||
|
name string
|
||||||
|
desc string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i commandItem) FilterValue() string { return i.name }
|
||||||
|
func (i commandItem) Title() string { return i.name }
|
||||||
|
func (i commandItem) Description() string { return i.desc }
|
||||||
|
|
||||||
|
type model struct {
|
||||||
|
domain string
|
||||||
|
protocol string
|
||||||
|
tunnelType types.TunnelType
|
||||||
|
port uint16
|
||||||
|
keymap keymap
|
||||||
|
help help.Model
|
||||||
|
quitting bool
|
||||||
|
showingCommands bool
|
||||||
|
editingSlug bool
|
||||||
|
showingComingSoon bool
|
||||||
|
commandList list.Model
|
||||||
|
slugInput textinput.Model
|
||||||
|
slugError string
|
||||||
|
interaction *interaction
|
||||||
|
width int
|
||||||
|
height int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *model) getTunnelURL() string {
|
||||||
|
if m.tunnelType == types.HTTP {
|
||||||
|
return buildURL(m.protocol, m.interaction.slug.String(), m.domain)
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("tcp://%s:%d", m.domain, m.port)
|
||||||
|
}
|
||||||
|
|
||||||
|
type keymap struct {
|
||||||
|
quit key.Binding
|
||||||
|
command key.Binding
|
||||||
|
random key.Binding
|
||||||
|
}
|
||||||
|
|
||||||
|
type tickMsg time.Time
|
||||||
|
|
||||||
|
func (m *model) Init() tea.Cmd {
|
||||||
|
return tea.Batch(textinput.Blink, tea.WindowSize())
|
||||||
|
}
|
||||||
|
|
||||||
|
func getResponsiveWidth(screenWidth, padding, minWidth, maxWidth int) int {
|
||||||
|
width := screenWidth - padding
|
||||||
|
if width > maxWidth {
|
||||||
|
width = maxWidth
|
||||||
|
}
|
||||||
|
if width < minWidth {
|
||||||
|
width = minWidth
|
||||||
|
}
|
||||||
|
return width
|
||||||
|
}
|
||||||
|
|
||||||
|
func shouldUseCompactLayout(width int, threshold int) bool {
|
||||||
|
return width < threshold
|
||||||
|
}
|
||||||
|
|
||||||
|
func truncateString(s string, maxLength int) string {
|
||||||
|
if len(s) <= maxLength {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
if maxLength < 4 {
|
||||||
|
return s[:maxLength]
|
||||||
|
}
|
||||||
|
return s[:maxLength-3] + "..."
|
||||||
|
}
|
||||||
|
|
||||||
|
func tickCmd(d time.Duration) tea.Cmd {
|
||||||
|
return tea.Tick(d, func(t time.Time) tea.Msg {
|
||||||
|
return tickMsg(t)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildURL(protocol, subdomain, domain string) string {
|
||||||
|
return fmt.Sprintf("%s://%s.%s", protocol, subdomain, domain)
|
||||||
|
}
|
||||||
@@ -0,0 +1,224 @@
|
|||||||
|
package interaction
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"tunnel_pls/internal/random"
|
||||||
|
"tunnel_pls/types"
|
||||||
|
|
||||||
|
"github.com/charmbracelet/bubbles/key"
|
||||||
|
"github.com/charmbracelet/bubbles/textinput"
|
||||||
|
tea "github.com/charmbracelet/bubbletea"
|
||||||
|
"github.com/charmbracelet/lipgloss"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (m *model) slugUpdate(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
|
||||||
|
var cmd tea.Cmd
|
||||||
|
|
||||||
|
if m.tunnelType != types.HTTP {
|
||||||
|
m.editingSlug = false
|
||||||
|
m.slugError = ""
|
||||||
|
return m, tea.Batch(tea.ClearScreen, textinput.Blink)
|
||||||
|
}
|
||||||
|
|
||||||
|
switch msg.String() {
|
||||||
|
case "esc":
|
||||||
|
m.editingSlug = false
|
||||||
|
m.slugError = ""
|
||||||
|
return m, tea.Batch(tea.ClearScreen, textinput.Blink)
|
||||||
|
case "enter":
|
||||||
|
inputValue := m.slugInput.Value()
|
||||||
|
if err := m.interaction.sessionRegistry.Update(m.interaction.lifecycle.User(), types.SessionKey{
|
||||||
|
Id: m.interaction.slug.String(),
|
||||||
|
Type: types.HTTP,
|
||||||
|
}, types.SessionKey{
|
||||||
|
Id: inputValue,
|
||||||
|
Type: types.HTTP,
|
||||||
|
}); err != nil {
|
||||||
|
m.slugError = err.Error()
|
||||||
|
return m, nil
|
||||||
|
}
|
||||||
|
m.editingSlug = false
|
||||||
|
m.slugError = ""
|
||||||
|
return m, tea.Batch(tea.ClearScreen, textinput.Blink)
|
||||||
|
case "ctrl+c":
|
||||||
|
m.editingSlug = false
|
||||||
|
m.slugError = ""
|
||||||
|
return m, tea.Batch(tea.ClearScreen, textinput.Blink)
|
||||||
|
default:
|
||||||
|
if key.Matches(msg, m.keymap.random) {
|
||||||
|
newSubdomain, err := random.GenerateRandomString(20)
|
||||||
|
if err != nil {
|
||||||
|
return m, cmd
|
||||||
|
}
|
||||||
|
m.slugInput.SetValue(newSubdomain)
|
||||||
|
m.slugError = ""
|
||||||
|
m.slugInput, cmd = m.slugInput.Update(msg)
|
||||||
|
}
|
||||||
|
m.slugError = ""
|
||||||
|
m.slugInput, cmd = m.slugInput.Update(msg)
|
||||||
|
return m, cmd
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *model) slugView() string {
|
||||||
|
isCompact := shouldUseCompactLayout(m.width, 70)
|
||||||
|
isVeryCompact := shouldUseCompactLayout(m.width, 50)
|
||||||
|
|
||||||
|
var boxPadding int
|
||||||
|
var boxMargin int
|
||||||
|
if isVeryCompact {
|
||||||
|
boxPadding = 1
|
||||||
|
boxMargin = 1
|
||||||
|
} else if isCompact {
|
||||||
|
boxPadding = 1
|
||||||
|
boxMargin = 1
|
||||||
|
} else {
|
||||||
|
boxPadding = 2
|
||||||
|
boxMargin = 2
|
||||||
|
}
|
||||||
|
|
||||||
|
titleStyle := lipgloss.NewStyle().
|
||||||
|
Bold(true).
|
||||||
|
Foreground(lipgloss.Color("#7D56F4")).
|
||||||
|
PaddingTop(1).
|
||||||
|
PaddingBottom(1)
|
||||||
|
|
||||||
|
instructionStyle := lipgloss.NewStyle().
|
||||||
|
Foreground(lipgloss.Color("#FAFAFA")).
|
||||||
|
MarginTop(1)
|
||||||
|
|
||||||
|
inputBoxStyle := lipgloss.NewStyle().
|
||||||
|
Border(lipgloss.RoundedBorder()).
|
||||||
|
BorderForeground(lipgloss.Color("#7D56F4")).
|
||||||
|
Padding(1, boxPadding).
|
||||||
|
MarginTop(boxMargin).
|
||||||
|
MarginBottom(boxMargin)
|
||||||
|
|
||||||
|
helpStyle := lipgloss.NewStyle().
|
||||||
|
Foreground(lipgloss.Color("#666666")).
|
||||||
|
Italic(true).
|
||||||
|
MarginTop(1)
|
||||||
|
|
||||||
|
errorBoxStyle := lipgloss.NewStyle().
|
||||||
|
Foreground(lipgloss.Color("#FF0000")).
|
||||||
|
Background(lipgloss.Color("#3D0000")).
|
||||||
|
Bold(true).
|
||||||
|
Border(lipgloss.RoundedBorder()).
|
||||||
|
BorderForeground(lipgloss.Color("#FF0000")).
|
||||||
|
Padding(0, boxPadding).
|
||||||
|
MarginTop(1).
|
||||||
|
MarginBottom(1)
|
||||||
|
|
||||||
|
rulesBoxWidth := getResponsiveWidth(m.width, 10, 30, 60)
|
||||||
|
rulesBoxStyle := lipgloss.NewStyle().
|
||||||
|
Foreground(lipgloss.Color("#FAFAFA")).
|
||||||
|
Border(lipgloss.RoundedBorder()).
|
||||||
|
BorderForeground(lipgloss.Color("#7D56F4")).
|
||||||
|
Padding(0, boxPadding).
|
||||||
|
MarginTop(1).
|
||||||
|
MarginBottom(1).
|
||||||
|
Width(rulesBoxWidth)
|
||||||
|
|
||||||
|
var b strings.Builder
|
||||||
|
var title string
|
||||||
|
if isVeryCompact {
|
||||||
|
title = "Edit Subdomain"
|
||||||
|
} else {
|
||||||
|
title = "🔧 Edit Subdomain"
|
||||||
|
}
|
||||||
|
b.WriteString(titleStyle.Render(title))
|
||||||
|
b.WriteString("\n\n")
|
||||||
|
|
||||||
|
if m.tunnelType != types.HTTP {
|
||||||
|
warningBoxWidth := getResponsiveWidth(m.width, 10, 30, 60)
|
||||||
|
warningBoxStyle := lipgloss.NewStyle().
|
||||||
|
Foreground(lipgloss.Color("#FFA500")).
|
||||||
|
Background(lipgloss.Color("#3D2000")).
|
||||||
|
Bold(true).
|
||||||
|
Border(lipgloss.RoundedBorder()).
|
||||||
|
BorderForeground(lipgloss.Color("#FFA500")).
|
||||||
|
Padding(1, boxPadding).
|
||||||
|
MarginTop(boxMargin).
|
||||||
|
MarginBottom(boxMargin).
|
||||||
|
Width(warningBoxWidth)
|
||||||
|
|
||||||
|
var warningText string
|
||||||
|
if isVeryCompact {
|
||||||
|
warningText = "⚠️ TCP tunnels don't support custom subdomains."
|
||||||
|
} else {
|
||||||
|
warningText = "⚠️ TCP tunnels cannot have custom subdomains. Only HTTP/HTTPS tunnels support subdomain customization."
|
||||||
|
}
|
||||||
|
b.WriteString(warningBoxStyle.Render(warningText))
|
||||||
|
b.WriteString("\n\n")
|
||||||
|
|
||||||
|
var helpText string
|
||||||
|
if isVeryCompact {
|
||||||
|
helpText = "Press any key to go back"
|
||||||
|
} else {
|
||||||
|
helpText = "Press Enter or Esc to go back"
|
||||||
|
}
|
||||||
|
b.WriteString(helpStyle.Render(helpText))
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
var rulesContent string
|
||||||
|
if isVeryCompact {
|
||||||
|
rulesContent = "Rules:\n3-20 chars\na-z, 0-9, -\nNo leading/trailing -"
|
||||||
|
} else if isCompact {
|
||||||
|
rulesContent = "📋 Rules:\n • 3-20 chars\n • a-z, 0-9, -\n • No leading/trailing -"
|
||||||
|
} else {
|
||||||
|
rulesContent = "📋 Rules: \n\t• 3-20 chars \n\t• a-z, 0-9, - \n\t• No leading/trailing -"
|
||||||
|
}
|
||||||
|
b.WriteString(rulesBoxStyle.Render(rulesContent))
|
||||||
|
b.WriteString("\n")
|
||||||
|
|
||||||
|
var instruction string
|
||||||
|
if isVeryCompact {
|
||||||
|
instruction = "Custom subdomain:"
|
||||||
|
} else {
|
||||||
|
instruction = "Enter your custom subdomain:"
|
||||||
|
}
|
||||||
|
b.WriteString(instructionStyle.Render(instruction))
|
||||||
|
b.WriteString("\n")
|
||||||
|
|
||||||
|
if m.slugError != "" {
|
||||||
|
errorInputBoxStyle := lipgloss.NewStyle().
|
||||||
|
Border(lipgloss.RoundedBorder()).
|
||||||
|
BorderForeground(lipgloss.Color("#FF0000")).
|
||||||
|
Padding(1, boxPadding).
|
||||||
|
MarginTop(boxMargin).
|
||||||
|
MarginBottom(1)
|
||||||
|
b.WriteString(errorInputBoxStyle.Render(m.slugInput.View()))
|
||||||
|
b.WriteString("\n")
|
||||||
|
b.WriteString(errorBoxStyle.Render("❌ " + m.slugError))
|
||||||
|
b.WriteString("\n")
|
||||||
|
} else {
|
||||||
|
b.WriteString(inputBoxStyle.Render(m.slugInput.View()))
|
||||||
|
b.WriteString("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
previewURL := buildURL(m.protocol, m.slugInput.Value(), m.domain)
|
||||||
|
previewWidth := getResponsiveWidth(m.width, 10, 30, 80)
|
||||||
|
|
||||||
|
if len(previewURL) > previewWidth-10 {
|
||||||
|
previewURL = truncateString(previewURL, previewWidth-10)
|
||||||
|
}
|
||||||
|
|
||||||
|
previewStyle := lipgloss.NewStyle().
|
||||||
|
Foreground(lipgloss.Color("#04B575")).
|
||||||
|
Italic(true).
|
||||||
|
Width(previewWidth)
|
||||||
|
b.WriteString(previewStyle.Render(fmt.Sprintf("Preview: %s", previewURL)))
|
||||||
|
b.WriteString("\n")
|
||||||
|
|
||||||
|
var helpText string
|
||||||
|
if isVeryCompact {
|
||||||
|
helpText = "Enter: save • CTRL+R: random • Esc: cancel"
|
||||||
|
} else {
|
||||||
|
helpText = "Press Enter to save • CTRL+R for random • Esc to cancel"
|
||||||
|
}
|
||||||
|
b.WriteString(helpStyle.Render(helpText))
|
||||||
|
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
+253
-1
@@ -1,10 +1,17 @@
|
|||||||
package session
|
package session
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/binary"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
"log"
|
"log"
|
||||||
|
"net"
|
||||||
"time"
|
"time"
|
||||||
"tunnel_pls/internal/config"
|
"tunnel_pls/internal/config"
|
||||||
|
portUtil "tunnel_pls/internal/port"
|
||||||
|
"tunnel_pls/internal/random"
|
||||||
"tunnel_pls/session/forwarder"
|
"tunnel_pls/session/forwarder"
|
||||||
"tunnel_pls/session/interaction"
|
"tunnel_pls/session/interaction"
|
||||||
"tunnel_pls/session/lifecycle"
|
"tunnel_pls/session/lifecycle"
|
||||||
@@ -45,6 +52,8 @@ type session struct {
|
|||||||
registry Registry
|
registry Registry
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var blockedReservedPorts = []uint16{1080, 1433, 1521, 1900, 2049, 3306, 3389, 5432, 5900, 6379, 8080, 8443, 9000, 9200, 27017}
|
||||||
|
|
||||||
func New(conn *ssh.ServerConn, initialReq <-chan *ssh.Request, sshChan <-chan ssh.NewChannel, sessionRegistry Registry, user string) Session {
|
func New(conn *ssh.ServerConn, initialReq <-chan *ssh.Request, sshChan <-chan ssh.NewChannel, sessionRegistry Registry, user string) Session {
|
||||||
slugManager := slug.New()
|
slugManager := slug.New()
|
||||||
forwarderManager := forwarder.New(slugManager)
|
forwarderManager := forwarder.New(slugManager)
|
||||||
@@ -151,7 +160,10 @@ func (s *session) Start() error {
|
|||||||
s.HandleTCPIPForward(tcpipReq)
|
s.HandleTCPIPForward(tcpipReq)
|
||||||
s.interaction.Start()
|
s.interaction.Start()
|
||||||
|
|
||||||
s.lifecycle.Connection().Wait()
|
if err := s.lifecycle.Connection().Wait(); err != nil && !errors.Is(err, io.EOF) && !errors.Is(err, net.ErrClosed) {
|
||||||
|
log.Printf("ssh connection closed with error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
if err := s.lifecycle.Close(); err != nil {
|
if err := s.lifecycle.Close(); err != nil {
|
||||||
log.Printf("failed to close session: %v", err)
|
log.Printf("failed to close session: %v", err)
|
||||||
return err
|
return err
|
||||||
@@ -179,3 +191,243 @@ func (s *session) waitForTCPIPForward() *ssh.Request {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *session) HandleGlobalRequest(GlobalRequest <-chan *ssh.Request) {
|
||||||
|
for req := range GlobalRequest {
|
||||||
|
switch req.Type {
|
||||||
|
case "shell", "pty-req":
|
||||||
|
err := req.Reply(true, nil)
|
||||||
|
if err != nil {
|
||||||
|
log.Println("Failed to reply to request:", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
case "window-change":
|
||||||
|
p := req.Payload
|
||||||
|
if len(p) < 16 {
|
||||||
|
log.Println("invalid window-change payload")
|
||||||
|
err := req.Reply(false, nil)
|
||||||
|
if err != nil {
|
||||||
|
log.Println("Failed to reply to request:", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
cols := binary.BigEndian.Uint32(p[0:4])
|
||||||
|
rows := binary.BigEndian.Uint32(p[4:8])
|
||||||
|
|
||||||
|
s.interaction.SetWH(int(cols), int(rows))
|
||||||
|
|
||||||
|
err := req.Reply(true, nil)
|
||||||
|
if err != nil {
|
||||||
|
log.Println("Failed to reply to request:", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
log.Println("Unknown request type:", req.Type)
|
||||||
|
err := req.Reply(false, nil)
|
||||||
|
if err != nil {
|
||||||
|
log.Println("Failed to reply to request:", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *session) HandleTCPIPForward(req *ssh.Request) {
|
||||||
|
log.Println("Port forwarding request detected")
|
||||||
|
|
||||||
|
fail := func(msg string) {
|
||||||
|
log.Println(msg)
|
||||||
|
if err := req.Reply(false, nil); err != nil {
|
||||||
|
log.Println("Failed to reply to request:", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := s.lifecycle.Close(); err != nil {
|
||||||
|
log.Printf("failed to close session: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
reader := bytes.NewReader(req.Payload)
|
||||||
|
|
||||||
|
addr, err := readSSHString(reader)
|
||||||
|
if err != nil {
|
||||||
|
fail(fmt.Sprintf("Failed to read address from payload: %v", err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var rawPortToBind uint32
|
||||||
|
if err = binary.Read(reader, binary.BigEndian, &rawPortToBind); err != nil {
|
||||||
|
fail(fmt.Sprintf("Failed to read port from payload: %v", err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if rawPortToBind > 65535 {
|
||||||
|
fail(fmt.Sprintf("Port %d is larger than allowed port of 65535", rawPortToBind))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
portToBind := uint16(rawPortToBind)
|
||||||
|
if isBlockedPort(portToBind) {
|
||||||
|
fail(fmt.Sprintf("Port %d is blocked or restricted", portToBind))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
switch portToBind {
|
||||||
|
case 80, 443:
|
||||||
|
s.HandleHTTPForward(req, portToBind)
|
||||||
|
default:
|
||||||
|
s.HandleTCPForward(req, addr, portToBind)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *session) HandleHTTPForward(req *ssh.Request, portToBind uint16) {
|
||||||
|
fail := func(msg string, key *types.SessionKey) {
|
||||||
|
log.Println(msg)
|
||||||
|
if key != nil {
|
||||||
|
s.registry.Remove(*key)
|
||||||
|
}
|
||||||
|
if err := req.Reply(false, nil); err != nil {
|
||||||
|
log.Println("Failed to reply to request:", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
randomString, err := random.GenerateRandomString(20)
|
||||||
|
if err != nil {
|
||||||
|
fail(fmt.Sprintf("Failed to create slug: %s", err), nil)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
key := types.SessionKey{Id: randomString, Type: types.HTTP}
|
||||||
|
if !s.registry.Register(key, s) {
|
||||||
|
fail(fmt.Sprintf("Failed to register client with slug: %s", randomString), nil)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
buf := new(bytes.Buffer)
|
||||||
|
err = binary.Write(buf, binary.BigEndian, uint32(portToBind))
|
||||||
|
if err != nil {
|
||||||
|
fail(fmt.Sprintf("Failed to write port to buffer: %v", err), &key)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
log.Printf("HTTP forwarding approved on port: %d", portToBind)
|
||||||
|
|
||||||
|
err = req.Reply(true, buf.Bytes())
|
||||||
|
if err != nil {
|
||||||
|
fail(fmt.Sprintf("Failed to reply to request: %v", err), &key)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
s.forwarder.SetType(types.HTTP)
|
||||||
|
s.forwarder.SetForwardedPort(portToBind)
|
||||||
|
s.slug.Set(randomString)
|
||||||
|
s.lifecycle.SetStatus(types.RUNNING)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *session) HandleTCPForward(req *ssh.Request, addr string, portToBind uint16) {
|
||||||
|
fail := func(msg string) {
|
||||||
|
log.Println(msg)
|
||||||
|
if err := req.Reply(false, nil); err != nil {
|
||||||
|
log.Println("Failed to reply to request:", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := s.lifecycle.Close(); err != nil {
|
||||||
|
log.Printf("failed to close session: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
cleanup := func(msg string, port uint16, listener net.Listener, key *types.SessionKey) {
|
||||||
|
log.Println(msg)
|
||||||
|
if key != nil {
|
||||||
|
s.registry.Remove(*key)
|
||||||
|
}
|
||||||
|
if port != 0 {
|
||||||
|
if setErr := portUtil.Default.SetPortStatus(port, false); setErr != nil {
|
||||||
|
log.Printf("Failed to reset port status: %v", setErr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if listener != nil {
|
||||||
|
if closeErr := listener.Close(); closeErr != nil {
|
||||||
|
log.Printf("Failed to close listener: %v", closeErr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := req.Reply(false, nil); err != nil {
|
||||||
|
log.Println("Failed to reply to request:", err)
|
||||||
|
}
|
||||||
|
_ = s.lifecycle.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
if portToBind == 0 {
|
||||||
|
unassigned, ok := portUtil.Default.GetUnassignedPort()
|
||||||
|
if !ok {
|
||||||
|
fail("No available port")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
portToBind = unassigned
|
||||||
|
}
|
||||||
|
|
||||||
|
if claimed := portUtil.Default.ClaimPort(portToBind); !claimed {
|
||||||
|
fail(fmt.Sprintf("Port %d is already in use or restricted", portToBind))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("Requested forwarding on %s:%d", addr, portToBind)
|
||||||
|
listener, err := net.Listen("tcp", fmt.Sprintf("0.0.0.0:%d", portToBind))
|
||||||
|
if err != nil {
|
||||||
|
cleanup(fmt.Sprintf("Port %d is already in use or restricted", portToBind), portToBind, nil, nil)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
key := types.SessionKey{Id: fmt.Sprintf("%d", portToBind), Type: types.TCP}
|
||||||
|
|
||||||
|
if !s.registry.Register(key, s) {
|
||||||
|
cleanup(fmt.Sprintf("Failed to register TCP client with id: %s", key.Id), portToBind, listener, nil)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
buf := new(bytes.Buffer)
|
||||||
|
err = binary.Write(buf, binary.BigEndian, uint32(portToBind))
|
||||||
|
if err != nil {
|
||||||
|
cleanup(fmt.Sprintf("Failed to write port to buffer: %v", err), portToBind, listener, &key)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("TCP forwarding approved on port: %d", portToBind)
|
||||||
|
err = req.Reply(true, buf.Bytes())
|
||||||
|
if err != nil {
|
||||||
|
cleanup(fmt.Sprintf("Failed to reply to request: %v", err), portToBind, listener, &key)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
s.forwarder.SetType(types.TCP)
|
||||||
|
s.forwarder.SetListener(listener)
|
||||||
|
s.forwarder.SetForwardedPort(portToBind)
|
||||||
|
s.slug.Set(key.Id)
|
||||||
|
s.lifecycle.SetStatus(types.RUNNING)
|
||||||
|
go s.forwarder.AcceptTCPConnections()
|
||||||
|
}
|
||||||
|
|
||||||
|
func readSSHString(reader *bytes.Reader) (string, error) {
|
||||||
|
var length uint32
|
||||||
|
if err := binary.Read(reader, binary.BigEndian, &length); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
strBytes := make([]byte, length)
|
||||||
|
if _, err := reader.Read(strBytes); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return string(strBytes), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func isBlockedPort(port uint16) bool {
|
||||||
|
if port == 80 || port == 443 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if port < 1024 && port != 0 {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
for _, p := range blockedReservedPorts {
|
||||||
|
if p == port {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user