This commit is contained in:
@@ -0,0 +1,191 @@
|
||||
package forwarder
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"strconv"
|
||||
"sync"
|
||||
"tunnel_pls/internal/config"
|
||||
"tunnel_pls/internal/session/slug"
|
||||
"tunnel_pls/types"
|
||||
|
||||
"golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
type Forwarder interface {
|
||||
SetType(tunnelType types.TunnelType)
|
||||
SetForwardedPort(port uint16)
|
||||
SetListener(listener net.Listener)
|
||||
Listener() net.Listener
|
||||
TunnelType() types.TunnelType
|
||||
ForwardedPort() uint16
|
||||
HandleConnection(dst io.ReadWriter, src ssh.Channel)
|
||||
OpenForwardedChannel(ctx context.Context, origin net.Addr) (ssh.Channel, <-chan *ssh.Request, error)
|
||||
Close() error
|
||||
}
|
||||
type forwarder struct {
|
||||
listener net.Listener
|
||||
tunnelType types.TunnelType
|
||||
forwardedPort uint16
|
||||
slug slug.Slug
|
||||
conn ssh.Conn
|
||||
bufferPool sync.Pool
|
||||
}
|
||||
|
||||
func New(config config.Config, slug slug.Slug, conn ssh.Conn) Forwarder {
|
||||
return &forwarder{
|
||||
listener: nil,
|
||||
tunnelType: types.TunnelTypeUNKNOWN,
|
||||
forwardedPort: 0,
|
||||
slug: slug,
|
||||
conn: conn,
|
||||
bufferPool: sync.Pool{
|
||||
New: func() interface{} {
|
||||
bufSize := config.BufferSize()
|
||||
buf := make([]byte, bufSize)
|
||||
return &buf
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (f *forwarder) copyWithBuffer(dst io.Writer, src io.Reader) (written int64, err error) {
|
||||
buf := f.bufferPool.Get().(*[]byte)
|
||||
defer f.bufferPool.Put(buf)
|
||||
return io.CopyBuffer(dst, src, *buf)
|
||||
}
|
||||
|
||||
func (f *forwarder) OpenForwardedChannel(ctx context.Context, origin net.Addr) (ssh.Channel, <-chan *ssh.Request, error) {
|
||||
payload := createForwardedTCPIPPayload(origin, f.forwardedPort)
|
||||
type channelResult struct {
|
||||
channel ssh.Channel
|
||||
reqs <-chan *ssh.Request
|
||||
err error
|
||||
}
|
||||
resultChan := make(chan channelResult, 1)
|
||||
|
||||
go func() {
|
||||
channel, reqs, err := f.conn.OpenChannel("forwarded-tcpip", payload)
|
||||
select {
|
||||
case resultChan <- channelResult{channel, reqs, err}:
|
||||
case <-ctx.Done():
|
||||
if channel != nil {
|
||||
_ = channel.Close()
|
||||
go ssh.DiscardRequests(reqs)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
select {
|
||||
case result := <-resultChan:
|
||||
return result.channel, result.reqs, result.err
|
||||
case <-ctx.Done():
|
||||
return nil, nil, fmt.Errorf("context cancelled: %w", ctx.Err())
|
||||
}
|
||||
}
|
||||
|
||||
func closeWriter(w io.Writer) error {
|
||||
if cw, ok := w.(interface{ CloseWrite() error }); ok {
|
||||
return cw.CloseWrite()
|
||||
}
|
||||
if closer, ok := w.(io.Closer); ok {
|
||||
return closer.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *forwarder) copyAndClose(dst io.Writer, src io.Reader, direction string) error {
|
||||
var errs []error
|
||||
_, err := f.copyWithBuffer(dst, src)
|
||||
if err != nil && !errors.Is(err, io.EOF) && !errors.Is(err, net.ErrClosed) {
|
||||
errs = append(errs, fmt.Errorf("copy error (%s): %w", direction, err))
|
||||
}
|
||||
|
||||
if err = closeWriter(dst); err != nil && !errors.Is(err, io.EOF) {
|
||||
errs = append(errs, fmt.Errorf("close stream error (%s): %w", direction, err))
|
||||
}
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
func (f *forwarder) HandleConnection(dst io.ReadWriter, src ssh.Channel) {
|
||||
defer func() {
|
||||
_, _ = io.Copy(io.Discard, src)
|
||||
}()
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(2)
|
||||
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
err := f.copyAndClose(dst, src, "src to dst")
|
||||
if err != nil {
|
||||
log.Println("Error during copy: ", err)
|
||||
return
|
||||
}
|
||||
}()
|
||||
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
err := f.copyAndClose(src, dst, "dst to src")
|
||||
if err != nil {
|
||||
log.Println("Error during copy: ", err)
|
||||
return
|
||||
}
|
||||
}()
|
||||
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func (f *forwarder) SetType(tunnelType types.TunnelType) {
|
||||
f.tunnelType = tunnelType
|
||||
}
|
||||
|
||||
func (f *forwarder) TunnelType() types.TunnelType {
|
||||
return f.tunnelType
|
||||
}
|
||||
|
||||
func (f *forwarder) ForwardedPort() uint16 {
|
||||
return f.forwardedPort
|
||||
}
|
||||
|
||||
func (f *forwarder) SetForwardedPort(port uint16) {
|
||||
f.forwardedPort = port
|
||||
}
|
||||
|
||||
func (f *forwarder) SetListener(listener net.Listener) {
|
||||
f.listener = listener
|
||||
}
|
||||
|
||||
func (f *forwarder) Listener() net.Listener {
|
||||
return f.listener
|
||||
}
|
||||
|
||||
func (f *forwarder) Close() error {
|
||||
if f.Listener() != nil {
|
||||
return f.listener.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func createForwardedTCPIPPayload(origin net.Addr, destPort uint16) []byte {
|
||||
host, portStr, _ := net.SplitHostPort(origin.String())
|
||||
port, _ := strconv.Atoi(portStr)
|
||||
|
||||
forwardPayload := struct {
|
||||
DestAddr string
|
||||
DestPort uint32
|
||||
OriginAddr string
|
||||
OriginPort uint32
|
||||
}{
|
||||
DestAddr: "localhost",
|
||||
DestPort: uint32(destPort),
|
||||
OriginAddr: host,
|
||||
OriginPort: uint32(port),
|
||||
}
|
||||
|
||||
return ssh.Marshal(forwardPayload)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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,86 @@
|
||||
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) handleCommandSelection(item commandItem) (tea.Model, tea.Cmd) {
|
||||
switch item.name {
|
||||
case "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)
|
||||
case "tunnel-type":
|
||||
m.showingCommands = false
|
||||
m.showingComingSoon = true
|
||||
return m, tea.Batch(tickCmd(5*time.Second), tea.ClearScreen, textinput.Blink)
|
||||
default:
|
||||
m.showingCommands = false
|
||||
return m, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (m *model) commandsUpdate(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
|
||||
var cmd tea.Cmd
|
||||
|
||||
switch {
|
||||
case key.Matches(msg, m.keymap.quit), msg.String() == "esc":
|
||||
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)
|
||||
return m.handleCommandSelection(item)
|
||||
}
|
||||
}
|
||||
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,216 @@
|
||||
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 {
|
||||
isCompact := shouldUseCompactLayout(m.width, BreakpointLarge)
|
||||
|
||||
var b strings.Builder
|
||||
b.WriteString(m.renderHeader(isCompact))
|
||||
b.WriteString(m.renderUserInfo(isCompact))
|
||||
b.WriteString(m.renderQuickActions(isCompact))
|
||||
b.WriteString(m.renderFooter(isCompact))
|
||||
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func (m *model) renderHeader(isCompact bool) string {
|
||||
var b strings.Builder
|
||||
|
||||
asciiArtMargin := getMarginValue(isCompact, 0, 1)
|
||||
asciiArtStyle := lipgloss.NewStyle().
|
||||
Bold(true).
|
||||
Foreground(lipgloss.Color(ColorPrimary)).
|
||||
MarginBottom(asciiArtMargin)
|
||||
|
||||
b.WriteString(asciiArtStyle.Render(m.getASCIIArt()))
|
||||
b.WriteString("\n")
|
||||
|
||||
if !shouldUseCompactLayout(m.width, BreakpointSmall) {
|
||||
b.WriteString(m.renderSubtitle())
|
||||
} else {
|
||||
b.WriteString("\n")
|
||||
}
|
||||
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func (m *model) getASCIIArt() string {
|
||||
if shouldUseCompactLayout(m.width, BreakpointTiny) {
|
||||
return "TUNNEL PLS"
|
||||
}
|
||||
|
||||
if shouldUseCompactLayout(m.width, BreakpointLarge) {
|
||||
return `
|
||||
▀█▀ █ █ █▄ █ █▄ █ ██▀ █ ▄▀▀ █ ▄▀▀
|
||||
█ ▀▄█ █ ▀█ █ ▀█ █▄▄ █▄▄ ▄█▀ █▄▄ ▄█▀`
|
||||
}
|
||||
|
||||
return `
|
||||
████████╗██╗ ██╗███╗ ██╗███╗ ██╗███████╗██╗ ██████╗ ██╗ ███████╗
|
||||
╚══██╔══╝██║ ██║████╗ ██║████╗ ██║██╔════╝██║ ██╔══██╗██║ ██╔════╝
|
||||
██║ ██║ ██║██╔██╗ ██║██╔██╗ ██║█████╗ ██║ ██████╔╝██║ ███████╗
|
||||
██║ ██║ ██║██║╚██╗██║██║╚██╗██║██╔══╝ ██║ ██╔═══╝ ██║ ╚════██║
|
||||
██║ ╚██████╔╝██║ ╚████║██║ ╚████║███████╗███████╗ ██║ ███████╗███████║
|
||||
╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚═╝ ╚═══╝╚══════╝╚══════╝ ╚═╝ ╚══════╝╚══════╝`
|
||||
}
|
||||
|
||||
func (m *model) renderSubtitle() string {
|
||||
subtitleStyle := lipgloss.NewStyle().
|
||||
Foreground(lipgloss.Color(ColorGray)).
|
||||
Italic(true)
|
||||
|
||||
urlStyle := lipgloss.NewStyle().
|
||||
Foreground(lipgloss.Color(ColorPrimary)).
|
||||
Underline(true).
|
||||
Italic(true)
|
||||
|
||||
return subtitleStyle.Render("Secure tunnel service by Bagas • ") +
|
||||
urlStyle.Render("https://fossy.my.id") + "\n\n"
|
||||
}
|
||||
|
||||
func (m *model) renderUserInfo(isCompact bool) string {
|
||||
boxMaxWidth := getResponsiveWidth(m.width, 10, 40, 80)
|
||||
boxPadding := getMarginValue(isCompact, 1, 2)
|
||||
boxMargin := getMarginValue(isCompact, 1, 2)
|
||||
|
||||
responsiveInfoBox := lipgloss.NewStyle().
|
||||
Border(lipgloss.RoundedBorder()).
|
||||
BorderForeground(lipgloss.Color(ColorPrimary)).
|
||||
Padding(1, boxPadding).
|
||||
MarginTop(boxMargin).
|
||||
MarginBottom(boxMargin).
|
||||
Width(boxMaxWidth)
|
||||
|
||||
infoContent := m.getUserInfoContent(isCompact)
|
||||
return responsiveInfoBox.Render(infoContent) + "\n"
|
||||
}
|
||||
|
||||
func (m *model) getUserInfoContent(isCompact bool) string {
|
||||
userInfoStyle := lipgloss.NewStyle().
|
||||
Foreground(lipgloss.Color(ColorWhite)).
|
||||
Bold(true)
|
||||
|
||||
sectionHeaderStyle := lipgloss.NewStyle().
|
||||
Foreground(lipgloss.Color(ColorGray)).
|
||||
Bold(true)
|
||||
|
||||
addressStyle := lipgloss.NewStyle().
|
||||
Foreground(lipgloss.Color(ColorWhite))
|
||||
|
||||
urlBoxStyle := lipgloss.NewStyle().
|
||||
Foreground(lipgloss.Color(ColorSecondary)).
|
||||
Bold(true).
|
||||
Italic(true)
|
||||
|
||||
authenticatedUser := m.interaction.user
|
||||
tunnelURL := urlBoxStyle.Render(m.getTunnelURL())
|
||||
|
||||
if isCompact {
|
||||
return fmt.Sprintf("👤 %s\n\n%s\n%s",
|
||||
userInfoStyle.Render(authenticatedUser),
|
||||
sectionHeaderStyle.Render("🌐 FORWARDING ADDRESS:"),
|
||||
addressStyle.Render(fmt.Sprintf(" %s", tunnelURL)))
|
||||
}
|
||||
|
||||
return fmt.Sprintf("👤 Authenticated as: %s\n\n%s\n %s",
|
||||
userInfoStyle.Render(authenticatedUser),
|
||||
sectionHeaderStyle.Render("🌐 FORWARDING ADDRESS:"),
|
||||
addressStyle.Render(tunnelURL))
|
||||
}
|
||||
|
||||
func (m *model) renderQuickActions(isCompact bool) string {
|
||||
var b strings.Builder
|
||||
|
||||
titleStyle := lipgloss.NewStyle().
|
||||
Bold(true).
|
||||
Foreground(lipgloss.Color(ColorPrimary)).
|
||||
PaddingTop(1)
|
||||
|
||||
b.WriteString(titleStyle.Render(m.getQuickActionsTitle()))
|
||||
b.WriteString("\n")
|
||||
|
||||
featureMargin := getMarginValue(isCompact, 1, 2)
|
||||
featureStyle := lipgloss.NewStyle().
|
||||
Foreground(lipgloss.Color(ColorWhite)).
|
||||
MarginLeft(featureMargin)
|
||||
|
||||
keyHintStyle := lipgloss.NewStyle().
|
||||
Foreground(lipgloss.Color(ColorPrimary)).
|
||||
Bold(true)
|
||||
|
||||
commands := m.getActionCommands(keyHintStyle)
|
||||
b.WriteString(featureStyle.Render(commands.commandsText))
|
||||
b.WriteString("\n")
|
||||
b.WriteString(featureStyle.Render(commands.quitText))
|
||||
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func (m *model) getQuickActionsTitle() string {
|
||||
if shouldUseCompactLayout(m.width, BreakpointTiny) {
|
||||
return "Actions"
|
||||
}
|
||||
if shouldUseCompactLayout(m.width, BreakpointLarge) {
|
||||
return "Quick Actions"
|
||||
}
|
||||
return "✨ Quick Actions"
|
||||
}
|
||||
|
||||
type actionCommands struct {
|
||||
commandsText string
|
||||
quitText string
|
||||
}
|
||||
|
||||
func (m *model) getActionCommands(keyHintStyle lipgloss.Style) actionCommands {
|
||||
if shouldUseCompactLayout(m.width, BreakpointSmall) {
|
||||
return actionCommands{
|
||||
commandsText: fmt.Sprintf(" %s Commands", keyHintStyle.Render("[C]")),
|
||||
quitText: fmt.Sprintf(" %s Quit", keyHintStyle.Render("[Q]")),
|
||||
}
|
||||
}
|
||||
|
||||
return actionCommands{
|
||||
commandsText: fmt.Sprintf(" %s Open commands menu", keyHintStyle.Render("[C]")),
|
||||
quitText: fmt.Sprintf(" %s Quit application", keyHintStyle.Render("[Q]")),
|
||||
}
|
||||
}
|
||||
|
||||
func (m *model) renderFooter(isCompact bool) string {
|
||||
if isCompact {
|
||||
return ""
|
||||
}
|
||||
|
||||
footerStyle := lipgloss.NewStyle().
|
||||
Foreground(lipgloss.Color(ColorDarkGray)).
|
||||
Italic(true)
|
||||
|
||||
return "\n\n" + footerStyle.Render("Press 'C' to customize your tunnel settings")
|
||||
}
|
||||
|
||||
func getMarginValue(isCompact bool, compactValue, normalValue int) int {
|
||||
if isCompact {
|
||||
return compactValue
|
||||
}
|
||||
return normalValue
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
package interaction
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"sync"
|
||||
"tunnel_pls/internal/config"
|
||||
"tunnel_pls/internal/random"
|
||||
"tunnel_pls/internal/session/slug"
|
||||
"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"
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
"github.com/muesli/termenv"
|
||||
"golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
type Interaction interface {
|
||||
Mode() types.InteractiveMode
|
||||
SetChannel(channel ssh.Channel)
|
||||
SetMode(m types.InteractiveMode)
|
||||
SetWH(w, h int)
|
||||
Start()
|
||||
Redraw()
|
||||
Send(message string) error
|
||||
}
|
||||
|
||||
type SessionRegistry interface {
|
||||
Update(user string, oldKey, newKey types.SessionKey) error
|
||||
}
|
||||
|
||||
type Forwarder interface {
|
||||
Close() error
|
||||
TunnelType() types.TunnelType
|
||||
ForwardedPort() uint16
|
||||
}
|
||||
|
||||
type CloseFunc func() error
|
||||
type interaction struct {
|
||||
randomizer random.Random
|
||||
config config.Config
|
||||
channel ssh.Channel
|
||||
slug slug.Slug
|
||||
forwarder Forwarder
|
||||
closeFunc CloseFunc
|
||||
user string
|
||||
sessionRegistry SessionRegistry
|
||||
program *tea.Program
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
mode types.InteractiveMode
|
||||
programMu sync.Mutex
|
||||
}
|
||||
|
||||
func (i *interaction) SetMode(m types.InteractiveMode) {
|
||||
i.mode = m
|
||||
}
|
||||
|
||||
func (i *interaction) Mode() types.InteractiveMode {
|
||||
return i.mode
|
||||
}
|
||||
|
||||
func (i *interaction) Send(message string) error {
|
||||
if i.channel != nil {
|
||||
_, err := i.channel.Write([]byte(message))
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (i *interaction) SetWH(w, h int) {
|
||||
if i.program != nil {
|
||||
i.program.Send(tea.WindowSizeMsg{
|
||||
Width: w,
|
||||
Height: h,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func New(randomizer random.Random, config config.Config, slug slug.Slug, forwarder Forwarder, sessionRegistry SessionRegistry, user string, closeFunc CloseFunc) Interaction {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
return &interaction{
|
||||
randomizer: randomizer,
|
||||
config: config,
|
||||
channel: nil,
|
||||
slug: slug,
|
||||
forwarder: forwarder,
|
||||
closeFunc: closeFunc,
|
||||
user: user,
|
||||
sessionRegistry: sessionRegistry,
|
||||
program: nil,
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
}
|
||||
}
|
||||
|
||||
func (i *interaction) SetChannel(channel ssh.Channel) {
|
||||
i.channel = channel
|
||||
}
|
||||
|
||||
func (i *interaction) Stop() {
|
||||
if i.cancel != nil {
|
||||
i.cancel()
|
||||
}
|
||||
|
||||
i.programMu.Lock()
|
||||
defer i.programMu.Unlock()
|
||||
|
||||
if i.program != nil {
|
||||
i.program.Kill()
|
||||
i.program = nil
|
||||
}
|
||||
}
|
||||
|
||||
func (m *model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
|
||||
switch msg := msg.(type) {
|
||||
case tickMsg:
|
||||
m.showingComingSoon = false
|
||||
return m, tea.Batch(tea.ClearScreen, textinput.Blink)
|
||||
|
||||
case tea.WindowSizeMsg:
|
||||
m.width = msg.Width
|
||||
m.height = msg.Height
|
||||
m.commandList.SetWidth(msg.Width)
|
||||
m.commandList.SetHeight(msg.Height - 4)
|
||||
|
||||
if msg.Width < 80 {
|
||||
m.slugInput.Width = msg.Width - 10
|
||||
} else {
|
||||
m.slugInput.Width = 50
|
||||
}
|
||||
return m, nil
|
||||
|
||||
case tea.QuitMsg:
|
||||
m.quitting = true
|
||||
return m, tea.Batch(tea.ClearScreen, textinput.Blink, tea.Quit)
|
||||
|
||||
case tea.KeyMsg:
|
||||
if m.showingComingSoon {
|
||||
return m.comingSoonUpdate(msg)
|
||||
}
|
||||
|
||||
if m.editingSlug {
|
||||
return m.slugUpdate(msg)
|
||||
}
|
||||
|
||||
if m.showingCommands {
|
||||
return m.commandsUpdate(msg)
|
||||
}
|
||||
|
||||
return m.dashboardUpdate(msg)
|
||||
}
|
||||
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func (i *interaction) Redraw() {
|
||||
if i.program != nil {
|
||||
i.program.Send(tea.ClearScreen())
|
||||
}
|
||||
}
|
||||
|
||||
func (m *model) View() string {
|
||||
if m.quitting {
|
||||
return ""
|
||||
}
|
||||
|
||||
if m.showingComingSoon {
|
||||
return m.comingSoonView()
|
||||
}
|
||||
|
||||
if m.editingSlug {
|
||||
return m.slugView()
|
||||
}
|
||||
|
||||
if m.showingCommands {
|
||||
return m.commandsView()
|
||||
}
|
||||
|
||||
return m.dashboardView()
|
||||
}
|
||||
|
||||
func (i *interaction) Start() {
|
||||
if i.mode == types.InteractiveModeHEADLESS {
|
||||
return
|
||||
}
|
||||
lipgloss.SetColorProfile(termenv.TrueColor)
|
||||
|
||||
protocol := "http"
|
||||
if i.config.TLSEnabled() {
|
||||
protocol = "https"
|
||||
}
|
||||
|
||||
tunnelType := i.forwarder.TunnelType()
|
||||
port := i.forwarder.ForwardedPort()
|
||||
|
||||
items := []list.Item{
|
||||
commandItem{name: "slug", desc: "Set custom subdomain"},
|
||||
commandItem{name: "tunnel-type", desc: "Change tunnel type (Coming Soon)"},
|
||||
}
|
||||
|
||||
delegate := list.NewDefaultDelegate()
|
||||
delegate.ShowDescription = true
|
||||
delegate.SetHeight(2)
|
||||
|
||||
commandList := list.New(items, delegate, 80, 20)
|
||||
commandList.Title = "Select a command"
|
||||
commandList.SetShowStatusBar(false)
|
||||
commandList.SetFilteringEnabled(false)
|
||||
commandList.SetShowHelp(false)
|
||||
|
||||
ti := textinput.New()
|
||||
ti.Placeholder = "my-custom-slug"
|
||||
ti.CharLimit = 20
|
||||
ti.Width = 50
|
||||
|
||||
m := &model{
|
||||
randomizer: i.randomizer,
|
||||
domain: i.config.Domain(),
|
||||
protocol: protocol,
|
||||
tunnelType: tunnelType,
|
||||
port: port,
|
||||
commandList: commandList,
|
||||
slugInput: ti,
|
||||
interaction: i,
|
||||
keymap: keymap{
|
||||
quit: key.NewBinding(
|
||||
key.WithKeys("q", "ctrl+c"),
|
||||
key.WithHelp("q", "quit"),
|
||||
),
|
||||
command: key.NewBinding(
|
||||
key.WithKeys("c"),
|
||||
key.WithHelp("c", "commands"),
|
||||
),
|
||||
random: key.NewBinding(
|
||||
key.WithKeys("ctrl+r"),
|
||||
key.WithHelp("ctrl+r", "random"),
|
||||
),
|
||||
},
|
||||
help: help.New(),
|
||||
}
|
||||
|
||||
i.programMu.Lock()
|
||||
i.program = tea.NewProgram(
|
||||
m,
|
||||
tea.WithInput(i.channel),
|
||||
tea.WithOutput(i.channel),
|
||||
tea.WithAltScreen(),
|
||||
tea.WithMouseCellMotion(),
|
||||
tea.WithoutSignals(),
|
||||
tea.WithoutSignalHandler(),
|
||||
tea.WithFPS(30),
|
||||
)
|
||||
i.programMu.Unlock()
|
||||
|
||||
_, err := i.program.Run()
|
||||
if err != nil {
|
||||
log.Printf("Cannot close tea: %s \n", err)
|
||||
}
|
||||
|
||||
i.programMu.Lock()
|
||||
if i.program != nil {
|
||||
i.program.Kill()
|
||||
i.program = nil
|
||||
}
|
||||
i.programMu.Unlock()
|
||||
|
||||
if i.closeFunc != nil {
|
||||
_ = i.closeFunc()
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,116 @@
|
||||
package interaction
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
"tunnel_pls/internal/random"
|
||||
"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 {
|
||||
randomizer random.Random
|
||||
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
|
||||
}
|
||||
|
||||
const (
|
||||
ColorPrimary = "#7D56F4"
|
||||
ColorSecondary = "#04B575"
|
||||
ColorGray = "#888888"
|
||||
ColorDarkGray = "#666666"
|
||||
ColorWhite = "#FAFAFA"
|
||||
ColorError = "#FF0000"
|
||||
ColorErrorBg = "#3D0000"
|
||||
ColorWarning = "#FFA500"
|
||||
ColorWarningBg = "#3D2000"
|
||||
)
|
||||
|
||||
const (
|
||||
BreakpointTiny = 50
|
||||
BreakpointSmall = 60
|
||||
BreakpointMedium = 70
|
||||
BreakpointLarge = 85
|
||||
)
|
||||
|
||||
func (m *model) getTunnelURL() string {
|
||||
if m.tunnelType == types.TunnelTypeHTTP {
|
||||
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,265 @@
|
||||
package interaction
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"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.TunnelTypeHTTP {
|
||||
m.editingSlug = false
|
||||
m.slugError = ""
|
||||
return m, tea.Batch(tea.ClearScreen, textinput.Blink)
|
||||
}
|
||||
|
||||
switch msg.String() {
|
||||
case "esc", "ctrl+c":
|
||||
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.user, types.SessionKey{
|
||||
Id: m.interaction.slug.String(),
|
||||
Type: types.TunnelTypeHTTP,
|
||||
}, types.SessionKey{
|
||||
Id: inputValue,
|
||||
Type: types.TunnelTypeHTTP,
|
||||
}); err != nil {
|
||||
m.slugError = err.Error()
|
||||
return m, nil
|
||||
}
|
||||
m.editingSlug = false
|
||||
m.slugError = ""
|
||||
return m, tea.Batch(tea.ClearScreen, textinput.Blink)
|
||||
default:
|
||||
if key.Matches(msg, m.keymap.random) {
|
||||
newSubdomain, err := m.randomizer.String(20)
|
||||
if err != nil {
|
||||
return m, cmd
|
||||
}
|
||||
m.slugInput.SetValue(newSubdomain)
|
||||
}
|
||||
m.slugError = ""
|
||||
m.slugInput, cmd = m.slugInput.Update(msg)
|
||||
return m, cmd
|
||||
}
|
||||
}
|
||||
|
||||
func (m *model) slugView() string {
|
||||
isCompact := shouldUseCompactLayout(m.width, BreakpointMedium)
|
||||
isVeryCompact := shouldUseCompactLayout(m.width, BreakpointTiny)
|
||||
|
||||
var b strings.Builder
|
||||
b.WriteString(m.renderSlugTitle(isVeryCompact))
|
||||
|
||||
if m.tunnelType != types.TunnelTypeHTTP {
|
||||
b.WriteString(m.renderTCPWarning(isVeryCompact, isCompact))
|
||||
return b.String()
|
||||
}
|
||||
|
||||
b.WriteString(m.renderSlugRules(isVeryCompact, isCompact))
|
||||
b.WriteString(m.renderSlugInstruction(isVeryCompact))
|
||||
b.WriteString(m.renderSlugInput(isVeryCompact, isCompact))
|
||||
b.WriteString(m.renderSlugPreview(isVeryCompact))
|
||||
b.WriteString(m.renderSlugHelp(isVeryCompact))
|
||||
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func (m *model) renderSlugTitle(isVeryCompact bool) string {
|
||||
titleStyle := lipgloss.NewStyle().
|
||||
Bold(true).
|
||||
Foreground(lipgloss.Color(ColorPrimary)).
|
||||
PaddingTop(1).
|
||||
PaddingBottom(1)
|
||||
|
||||
title := "🔧 Edit Subdomain"
|
||||
if isVeryCompact {
|
||||
title = "Edit Subdomain"
|
||||
}
|
||||
|
||||
return titleStyle.Render(title) + "\n\n"
|
||||
}
|
||||
|
||||
func (m *model) renderTCPWarning(isVeryCompact, isCompact bool) string {
|
||||
boxPadding := getPaddingValue(isVeryCompact, isCompact)
|
||||
boxMargin := getMarginValue(isCompact, 1, 2)
|
||||
warningBoxWidth := getResponsiveWidth(m.width, 10, 30, 60)
|
||||
|
||||
warningBoxStyle := lipgloss.NewStyle().
|
||||
Foreground(lipgloss.Color(ColorWarning)).
|
||||
Background(lipgloss.Color(ColorWarningBg)).
|
||||
Bold(true).
|
||||
Border(lipgloss.RoundedBorder()).
|
||||
BorderForeground(lipgloss.Color(ColorWarning)).
|
||||
Padding(1, boxPadding).
|
||||
MarginTop(boxMargin).
|
||||
MarginBottom(boxMargin).
|
||||
Width(warningBoxWidth)
|
||||
|
||||
helpStyle := lipgloss.NewStyle().
|
||||
Foreground(lipgloss.Color(ColorDarkGray)).
|
||||
Italic(true).
|
||||
MarginTop(1)
|
||||
|
||||
warningText := m.getTCPWarningText(isVeryCompact)
|
||||
helpText := m.getTCPHelpText(isVeryCompact)
|
||||
|
||||
var b strings.Builder
|
||||
b.WriteString(warningBoxStyle.Render(warningText))
|
||||
b.WriteString("\n\n")
|
||||
b.WriteString(helpStyle.Render(helpText))
|
||||
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func (m *model) getTCPWarningText(isVeryCompact bool) string {
|
||||
if isVeryCompact {
|
||||
return "⚠️ TCP tunnels don't support custom subdomains."
|
||||
}
|
||||
return "⚠️ TCP tunnels cannot have custom subdomains. Only HTTP/HTTPS tunnels support subdomain customization."
|
||||
}
|
||||
|
||||
func (m *model) getTCPHelpText(isVeryCompact bool) string {
|
||||
if isVeryCompact {
|
||||
return "Press any key to go back"
|
||||
}
|
||||
return "Press Enter or Esc to go back"
|
||||
}
|
||||
|
||||
func (m *model) renderSlugRules(isVeryCompact, isCompact bool) string {
|
||||
boxPadding := getPaddingValue(isVeryCompact, isCompact)
|
||||
rulesBoxWidth := getResponsiveWidth(m.width, 10, 30, 60)
|
||||
|
||||
rulesBoxStyle := lipgloss.NewStyle().
|
||||
Foreground(lipgloss.Color(ColorWhite)).
|
||||
Border(lipgloss.RoundedBorder()).
|
||||
BorderForeground(lipgloss.Color(ColorPrimary)).
|
||||
Padding(0, boxPadding).
|
||||
MarginTop(1).
|
||||
MarginBottom(1).
|
||||
Width(rulesBoxWidth)
|
||||
|
||||
rulesContent := m.getRulesContent(isVeryCompact, isCompact)
|
||||
return rulesBoxStyle.Render(rulesContent) + "\n"
|
||||
}
|
||||
|
||||
func (m *model) getRulesContent(isVeryCompact, isCompact bool) string {
|
||||
if isVeryCompact {
|
||||
return "Rules:\n3-20 chars\na-z, 0-9, -\nNo leading/trailing -"
|
||||
}
|
||||
|
||||
if isCompact {
|
||||
return "📋 Rules:\n • 3-20 chars\n • a-z, 0-9, -\n • No leading/trailing -"
|
||||
}
|
||||
|
||||
return "📋 Rules: \n\t• 3-20 chars \n\t• a-z, 0-9, - \n\t• No leading/trailing -"
|
||||
}
|
||||
|
||||
func (m *model) renderSlugInstruction(isVeryCompact bool) string {
|
||||
instructionStyle := lipgloss.NewStyle().
|
||||
Foreground(lipgloss.Color(ColorWhite)).
|
||||
MarginTop(1)
|
||||
|
||||
instruction := "Enter your custom subdomain:"
|
||||
if isVeryCompact {
|
||||
instruction = "Custom subdomain:"
|
||||
}
|
||||
|
||||
return instructionStyle.Render(instruction) + "\n"
|
||||
}
|
||||
|
||||
func (m *model) renderSlugInput(isVeryCompact, isCompact bool) string {
|
||||
boxPadding := getPaddingValue(isVeryCompact, isCompact)
|
||||
boxMargin := getMarginValue(isCompact, 1, 2)
|
||||
|
||||
if m.slugError != "" {
|
||||
return m.renderErrorInput(boxPadding, boxMargin)
|
||||
}
|
||||
|
||||
return m.renderNormalInput(boxPadding, boxMargin)
|
||||
}
|
||||
|
||||
func (m *model) renderErrorInput(boxPadding, boxMargin int) string {
|
||||
errorInputBoxStyle := lipgloss.NewStyle().
|
||||
Border(lipgloss.RoundedBorder()).
|
||||
BorderForeground(lipgloss.Color(ColorError)).
|
||||
Padding(1, boxPadding).
|
||||
MarginTop(boxMargin).
|
||||
MarginBottom(1)
|
||||
|
||||
errorBoxStyle := lipgloss.NewStyle().
|
||||
Foreground(lipgloss.Color(ColorError)).
|
||||
Background(lipgloss.Color(ColorErrorBg)).
|
||||
Bold(true).
|
||||
Border(lipgloss.RoundedBorder()).
|
||||
BorderForeground(lipgloss.Color(ColorError)).
|
||||
Padding(0, boxPadding).
|
||||
MarginTop(1).
|
||||
MarginBottom(1)
|
||||
|
||||
var b strings.Builder
|
||||
b.WriteString(errorInputBoxStyle.Render(m.slugInput.View()))
|
||||
b.WriteString("\n")
|
||||
b.WriteString(errorBoxStyle.Render("❌ " + m.slugError))
|
||||
b.WriteString("\n")
|
||||
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func (m *model) renderNormalInput(boxPadding, boxMargin int) string {
|
||||
inputBoxStyle := lipgloss.NewStyle().
|
||||
Border(lipgloss.RoundedBorder()).
|
||||
BorderForeground(lipgloss.Color(ColorPrimary)).
|
||||
Padding(1, boxPadding).
|
||||
MarginTop(boxMargin).
|
||||
MarginBottom(boxMargin)
|
||||
|
||||
return inputBoxStyle.Render(m.slugInput.View()) + "\n"
|
||||
}
|
||||
|
||||
func (m *model) renderSlugPreview(isVeryCompact bool) string {
|
||||
previewURL := buildURL(m.protocol, m.slugInput.Value(), m.domain)
|
||||
previewWidth := getResponsiveWidth(m.width, 10, 30, 80)
|
||||
|
||||
if isVeryCompact {
|
||||
previewURL = truncateString(previewURL, previewWidth-10)
|
||||
}
|
||||
|
||||
previewStyle := lipgloss.NewStyle().
|
||||
Foreground(lipgloss.Color(ColorSecondary)).
|
||||
Italic(true).
|
||||
Width(previewWidth)
|
||||
|
||||
return previewStyle.Render(fmt.Sprintf("Preview: %s", previewURL)) + "\n"
|
||||
}
|
||||
|
||||
func (m *model) renderSlugHelp(isVeryCompact bool) string {
|
||||
helpStyle := lipgloss.NewStyle().
|
||||
Foreground(lipgloss.Color(ColorDarkGray)).
|
||||
Italic(true).
|
||||
MarginTop(1)
|
||||
|
||||
helpText := "Press Enter to save • CTRL+R for random • Esc to cancel"
|
||||
if isVeryCompact {
|
||||
helpText = "Enter: save • CTRL+R: random • Esc: cancel"
|
||||
}
|
||||
|
||||
return helpStyle.Render(helpText)
|
||||
}
|
||||
|
||||
func getPaddingValue(isVeryCompact, isCompact bool) int {
|
||||
if isVeryCompact || isCompact {
|
||||
return 1
|
||||
}
|
||||
return 2
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
"tunnel_pls/internal/session/slug"
|
||||
|
||||
portUtil "tunnel_pls/internal/port"
|
||||
"tunnel_pls/types"
|
||||
|
||||
"golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
type Forwarder interface {
|
||||
Close() error
|
||||
TunnelType() types.TunnelType
|
||||
ForwardedPort() uint16
|
||||
}
|
||||
|
||||
type SessionRegistry interface {
|
||||
Remove(key types.SessionKey)
|
||||
}
|
||||
|
||||
type lifecycle struct {
|
||||
mu sync.Mutex
|
||||
status types.SessionStatus
|
||||
closeErr error
|
||||
conn ssh.Conn
|
||||
channel ssh.Channel
|
||||
forwarder Forwarder
|
||||
slug slug.Slug
|
||||
startedAt time.Time
|
||||
sessionRegistry SessionRegistry
|
||||
portRegistry portUtil.Port
|
||||
user string
|
||||
}
|
||||
|
||||
func New(conn ssh.Conn, forwarder Forwarder, slugManager slug.Slug, port portUtil.Port, sessionRegistry SessionRegistry, user string) Lifecycle {
|
||||
return &lifecycle{
|
||||
status: types.SessionStatusINITIALIZING,
|
||||
conn: conn,
|
||||
channel: nil,
|
||||
forwarder: forwarder,
|
||||
slug: slugManager,
|
||||
startedAt: time.Now(),
|
||||
sessionRegistry: sessionRegistry,
|
||||
portRegistry: port,
|
||||
user: user,
|
||||
}
|
||||
}
|
||||
|
||||
type Lifecycle interface {
|
||||
Connection() ssh.Conn
|
||||
Channel() ssh.Channel
|
||||
PortRegistry() portUtil.Port
|
||||
User() string
|
||||
SetChannel(channel ssh.Channel)
|
||||
SetStatus(status types.SessionStatus)
|
||||
IsActive() bool
|
||||
StartedAt() time.Time
|
||||
Close() error
|
||||
}
|
||||
|
||||
func (l *lifecycle) PortRegistry() portUtil.Port {
|
||||
return l.portRegistry
|
||||
}
|
||||
|
||||
func (l *lifecycle) User() string {
|
||||
return l.user
|
||||
}
|
||||
|
||||
func (l *lifecycle) SetChannel(channel ssh.Channel) {
|
||||
l.channel = channel
|
||||
}
|
||||
|
||||
func (l *lifecycle) Channel() ssh.Channel {
|
||||
return l.channel
|
||||
}
|
||||
|
||||
func (l *lifecycle) Connection() ssh.Conn {
|
||||
return l.conn
|
||||
}
|
||||
|
||||
func (l *lifecycle) SetStatus(status types.SessionStatus) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
l.status = status
|
||||
}
|
||||
|
||||
func (l *lifecycle) IsActive() bool {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
return l.status == types.SessionStatusRUNNING
|
||||
}
|
||||
|
||||
func (l *lifecycle) Close() error {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
if l.status == types.SessionStatusCLOSED {
|
||||
return l.closeErr
|
||||
}
|
||||
l.status = types.SessionStatusCLOSED
|
||||
|
||||
var errs []error
|
||||
tunnelType := l.forwarder.TunnelType()
|
||||
|
||||
if l.channel != nil {
|
||||
if err := l.channel.Close(); err != nil && !isClosedError(err) {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
}
|
||||
|
||||
if l.conn != nil {
|
||||
if err := l.conn.Close(); err != nil && !isClosedError(err) {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
}
|
||||
|
||||
clientSlug := l.slug.String()
|
||||
key := types.SessionKey{
|
||||
Id: clientSlug,
|
||||
Type: tunnelType,
|
||||
}
|
||||
l.sessionRegistry.Remove(key)
|
||||
|
||||
if tunnelType == types.TunnelTypeTCP {
|
||||
errs = append(errs, l.PortRegistry().SetStatus(l.forwarder.ForwardedPort(), false))
|
||||
errs = append(errs, l.forwarder.Close())
|
||||
}
|
||||
|
||||
l.closeErr = errors.Join(errs...)
|
||||
return l.closeErr
|
||||
}
|
||||
|
||||
func isClosedError(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
return errors.Is(err, io.EOF) || errors.Is(err, net.ErrClosed) || err.Error() == "EOF"
|
||||
}
|
||||
|
||||
func (l *lifecycle) StartedAt() time.Time {
|
||||
return l.startedAt
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"testing"
|
||||
"tunnel_pls/types"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
type MockSessionRegistry struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
func (m *MockSessionRegistry) Remove(key types.SessionKey) {
|
||||
m.Called(key)
|
||||
}
|
||||
|
||||
type MockForwarder struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
func (m *MockForwarder) CreateForwardedTCPIPPayload(origin net.Addr) []byte {
|
||||
args := m.Called(origin)
|
||||
return args.Get(0).([]byte)
|
||||
}
|
||||
|
||||
func (m *MockForwarder) HandleConnection(dst io.ReadWriter, src ssh.Channel) {
|
||||
m.Called(dst, src)
|
||||
}
|
||||
|
||||
func (m *MockForwarder) Close() error {
|
||||
args := m.Called()
|
||||
return args.Error(0)
|
||||
}
|
||||
|
||||
func (m *MockForwarder) TunnelType() types.TunnelType {
|
||||
args := m.Called()
|
||||
return args.Get(0).(types.TunnelType)
|
||||
}
|
||||
|
||||
func (m *MockForwarder) ForwardedPort() uint16 {
|
||||
args := m.Called()
|
||||
return args.Get(0).(uint16)
|
||||
}
|
||||
|
||||
func (m *MockForwarder) SetType(tunnelType types.TunnelType) {
|
||||
m.Called(tunnelType)
|
||||
}
|
||||
|
||||
func (m *MockForwarder) SetForwardedPort(port uint16) {
|
||||
m.Called(port)
|
||||
}
|
||||
|
||||
func (m *MockForwarder) SetListener(listener net.Listener) {
|
||||
m.Called(listener)
|
||||
}
|
||||
|
||||
func (m *MockForwarder) Listener() net.Listener {
|
||||
args := m.Called()
|
||||
return args.Get(0).(net.Listener)
|
||||
}
|
||||
|
||||
func (m *MockForwarder) OpenForwardedChannel(ctx context.Context, origin net.Addr) (ssh.Channel, <-chan *ssh.Request, error) {
|
||||
args := m.Called(ctx, origin)
|
||||
if args.Get(0) == nil {
|
||||
return nil, nil, args.Error(2)
|
||||
}
|
||||
return args.Get(0).(ssh.Channel), args.Get(1).(<-chan *ssh.Request), args.Error(2)
|
||||
}
|
||||
|
||||
type MockPort struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
func (m *MockPort) AddRange(startPort, endPort uint16) error {
|
||||
return m.Called(startPort, endPort).Error(0)
|
||||
}
|
||||
func (m *MockPort) Unassigned() (uint16, bool) {
|
||||
args := m.Called()
|
||||
var port uint16
|
||||
if args.Get(0) != nil {
|
||||
switch v := args.Get(0).(type) {
|
||||
case int:
|
||||
port = uint16(v)
|
||||
case uint16:
|
||||
port = v
|
||||
case uint32:
|
||||
port = uint16(v)
|
||||
case int32:
|
||||
port = uint16(v)
|
||||
case float64:
|
||||
port = uint16(v)
|
||||
default:
|
||||
port = uint16(args.Int(0))
|
||||
}
|
||||
}
|
||||
return port, args.Bool(1)
|
||||
}
|
||||
func (m *MockPort) SetStatus(port uint16, assigned bool) error {
|
||||
return m.Called(port, assigned).Error(0)
|
||||
}
|
||||
func (m *MockPort) Claim(port uint16) bool {
|
||||
return m.Called(port).Bool(0)
|
||||
}
|
||||
|
||||
type MockSlug struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
func (ms *MockSlug) Set(slug string) {
|
||||
ms.Called(slug)
|
||||
}
|
||||
func (ms *MockSlug) String() string {
|
||||
return ms.Called().String(0)
|
||||
}
|
||||
|
||||
type MockSSHConn struct {
|
||||
ssh.Conn
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
func (m *MockSSHConn) Close() error {
|
||||
args := m.Called()
|
||||
return args.Error(0)
|
||||
}
|
||||
|
||||
type MockSSHChannel struct {
|
||||
ssh.Channel
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
func (m *MockSSHChannel) Close() error {
|
||||
return m.Called().Error(0)
|
||||
}
|
||||
|
||||
func TestNew(t *testing.T) {
|
||||
mockSSHConn := new(MockSSHConn)
|
||||
mockForwarder := &MockForwarder{}
|
||||
mockSlug := &MockSlug{}
|
||||
mockPort := &MockPort{}
|
||||
mockSessionRegistry := &MockSessionRegistry{}
|
||||
|
||||
mockLifecycle := New(mockSSHConn, mockForwarder, mockSlug, mockPort, mockSessionRegistry, "mas-fuad")
|
||||
|
||||
assert.NotNil(t, mockLifecycle.Connection())
|
||||
assert.NotNil(t, mockLifecycle.User())
|
||||
assert.NotNil(t, mockLifecycle.PortRegistry())
|
||||
assert.NotNil(t, mockLifecycle.StartedAt())
|
||||
}
|
||||
|
||||
func TestLifecycle_User(t *testing.T) {
|
||||
mockSSHConn := new(MockSSHConn)
|
||||
mockForwarder := &MockForwarder{}
|
||||
mockSlug := &MockSlug{}
|
||||
mockPort := &MockPort{}
|
||||
mockSessionRegistry := &MockSessionRegistry{}
|
||||
|
||||
user := "mas-fuad"
|
||||
mockLifecycle := New(mockSSHConn, mockForwarder, mockSlug, mockPort, mockSessionRegistry, user)
|
||||
assert.Equal(t, user, mockLifecycle.User())
|
||||
}
|
||||
|
||||
func TestLifecycle_SetChannel(t *testing.T) {
|
||||
mockSSHConn := new(MockSSHConn)
|
||||
mockForwarder := &MockForwarder{}
|
||||
mockSlug := &MockSlug{}
|
||||
mockPort := &MockPort{}
|
||||
mockSessionRegistry := &MockSessionRegistry{}
|
||||
|
||||
mockLifecycle := New(mockSSHConn, mockForwarder, mockSlug, mockPort, mockSessionRegistry, "mas-fuad")
|
||||
|
||||
mockSSHChannel := &MockSSHChannel{}
|
||||
|
||||
mockLifecycle.SetChannel(mockSSHChannel)
|
||||
|
||||
assert.Equal(t, mockSSHChannel, mockLifecycle.Channel())
|
||||
}
|
||||
|
||||
func TestLifecycle_SetStatus(t *testing.T) {
|
||||
mockSSHConn := new(MockSSHConn)
|
||||
mockForwarder := &MockForwarder{}
|
||||
mockSlug := &MockSlug{}
|
||||
mockPort := &MockPort{}
|
||||
mockSessionRegistry := &MockSessionRegistry{}
|
||||
|
||||
mockLifecycle := New(mockSSHConn, mockForwarder, mockSlug, mockPort, mockSessionRegistry, "mas-fuad")
|
||||
|
||||
mockLifecycle.SetStatus(types.SessionStatusRUNNING)
|
||||
assert.True(t, mockLifecycle.IsActive())
|
||||
}
|
||||
|
||||
func TestLifecycle_IsActive(t *testing.T) {
|
||||
mockSSHConn := new(MockSSHConn)
|
||||
mockForwarder := &MockForwarder{}
|
||||
mockSlug := &MockSlug{}
|
||||
mockPort := &MockPort{}
|
||||
mockSessionRegistry := &MockSessionRegistry{}
|
||||
|
||||
mockLifecycle := New(mockSSHConn, mockForwarder, mockSlug, mockPort, mockSessionRegistry, "mas-fuad")
|
||||
|
||||
mockLifecycle.SetStatus(types.SessionStatusRUNNING)
|
||||
assert.True(t, mockLifecycle.IsActive())
|
||||
}
|
||||
|
||||
func TestLifecycle_Close(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
tunnelType types.TunnelType
|
||||
connCloseErr error
|
||||
channelCloseErr error
|
||||
expectErr bool
|
||||
alreadyClosed bool
|
||||
}{
|
||||
{
|
||||
name: "Close HTTP forwarding success",
|
||||
tunnelType: types.TunnelTypeHTTP,
|
||||
expectErr: false,
|
||||
},
|
||||
{
|
||||
name: "Close TCP forwarding success",
|
||||
tunnelType: types.TunnelTypeTCP,
|
||||
expectErr: false,
|
||||
},
|
||||
{
|
||||
name: "Close with conn close error",
|
||||
tunnelType: types.TunnelTypeHTTP,
|
||||
connCloseErr: errors.New("conn close error"),
|
||||
expectErr: true,
|
||||
},
|
||||
{
|
||||
name: "Close with channel close error",
|
||||
tunnelType: types.TunnelTypeHTTP,
|
||||
channelCloseErr: errors.New("channel close error"),
|
||||
expectErr: true,
|
||||
},
|
||||
{
|
||||
name: "Close when already closed",
|
||||
tunnelType: types.TunnelTypeHTTP,
|
||||
alreadyClosed: true,
|
||||
expectErr: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
mockSSHConn := &MockSSHConn{}
|
||||
mockSSHConn.On("Close").Return(tt.connCloseErr)
|
||||
|
||||
mockForwarder := &MockForwarder{}
|
||||
mockForwarder.On("TunnelType").Return(tt.tunnelType)
|
||||
if tt.tunnelType == types.TunnelTypeTCP {
|
||||
mockForwarder.On("ForwardedPort").Return(uint16(8080))
|
||||
mockForwarder.On("Close").Return(nil)
|
||||
}
|
||||
|
||||
mockSlug := &MockSlug{}
|
||||
mockSlug.On("String").Return("test-slug")
|
||||
|
||||
mockPort := &MockPort{}
|
||||
if tt.tunnelType == types.TunnelTypeTCP {
|
||||
mockPort.On("SetStatus", uint16(8080), false).Return(nil)
|
||||
}
|
||||
|
||||
mockSessionRegistry := &MockSessionRegistry{}
|
||||
mockSessionRegistry.On("Remove", mock.Anything).Return()
|
||||
|
||||
mockSSHChannel := &MockSSHChannel{}
|
||||
mockSSHChannel.On("Close").Return(tt.channelCloseErr)
|
||||
|
||||
mockLifecycle := New(mockSSHConn, mockForwarder, mockSlug, mockPort, mockSessionRegistry, "mas-fuad")
|
||||
|
||||
mockLifecycle.SetStatus(types.SessionStatusRUNNING)
|
||||
mockLifecycle.SetChannel(mockSSHChannel)
|
||||
|
||||
if tt.alreadyClosed {
|
||||
err := mockLifecycle.Close()
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
err := mockLifecycle.Close()
|
||||
|
||||
if tt.expectErr {
|
||||
assert.Error(t, err)
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
assert.False(t, mockLifecycle.IsActive())
|
||||
|
||||
mockSSHConn.AssertExpectations(t)
|
||||
mockForwarder.AssertExpectations(t)
|
||||
mockSlug.AssertExpectations(t)
|
||||
mockPort.AssertExpectations(t)
|
||||
mockSessionRegistry.AssertExpectations(t)
|
||||
mockSSHChannel.AssertExpectations(t)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,402 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"time"
|
||||
"tunnel_pls/internal/config"
|
||||
portUtil "tunnel_pls/internal/port"
|
||||
"tunnel_pls/internal/random"
|
||||
"tunnel_pls/internal/registry"
|
||||
"tunnel_pls/internal/session/forwarder"
|
||||
"tunnel_pls/internal/session/interaction"
|
||||
"tunnel_pls/internal/session/lifecycle"
|
||||
"tunnel_pls/internal/session/slug"
|
||||
"tunnel_pls/internal/transport"
|
||||
"tunnel_pls/types"
|
||||
|
||||
"golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
type Session interface {
|
||||
HandleGlobalRequest(ch <-chan *ssh.Request) error
|
||||
HandleTCPIPForward(req *ssh.Request) error
|
||||
HandleHTTPForward(req *ssh.Request, port uint16) error
|
||||
HandleTCPForward(req *ssh.Request, addr string, port uint16) error
|
||||
Lifecycle() lifecycle.Lifecycle
|
||||
Interaction() interaction.Interaction
|
||||
Forwarder() forwarder.Forwarder
|
||||
Slug() slug.Slug
|
||||
Detail() *types.Detail
|
||||
Start() error
|
||||
}
|
||||
|
||||
type session struct {
|
||||
randomizer random.Random
|
||||
config config.Config
|
||||
initialReq <-chan *ssh.Request
|
||||
sshChan <-chan ssh.NewChannel
|
||||
lifecycle lifecycle.Lifecycle
|
||||
interaction interaction.Interaction
|
||||
forwarder forwarder.Forwarder
|
||||
slug slug.Slug
|
||||
registry registry.Registry
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
Randomizer random.Random
|
||||
Config config.Config
|
||||
Conn *ssh.ServerConn
|
||||
InitialReq <-chan *ssh.Request
|
||||
SshChan <-chan ssh.NewChannel
|
||||
SessionRegistry registry.Registry
|
||||
PortRegistry portUtil.Port
|
||||
User string
|
||||
}
|
||||
|
||||
var blockedReservedPorts = []uint16{1080, 1433, 1521, 1900, 2049, 3306, 3389, 5432, 5900, 6379, 8080, 8443, 9000, 9200, 27017}
|
||||
|
||||
func New(conf *Config) Session {
|
||||
slugManager := slug.New()
|
||||
forwarderManager := forwarder.New(conf.Config, slugManager, conf.Conn)
|
||||
lifecycleManager := lifecycle.New(conf.Conn, forwarderManager, slugManager, conf.PortRegistry, conf.SessionRegistry, conf.User)
|
||||
interactionManager := interaction.New(conf.Randomizer, conf.Config, slugManager, forwarderManager, conf.SessionRegistry, conf.User, lifecycleManager.Close)
|
||||
|
||||
return &session{
|
||||
randomizer: conf.Randomizer,
|
||||
config: conf.Config,
|
||||
initialReq: conf.InitialReq,
|
||||
sshChan: conf.SshChan,
|
||||
lifecycle: lifecycleManager,
|
||||
interaction: interactionManager,
|
||||
forwarder: forwarderManager,
|
||||
slug: slugManager,
|
||||
registry: conf.SessionRegistry,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *session) Lifecycle() lifecycle.Lifecycle {
|
||||
return s.lifecycle
|
||||
}
|
||||
|
||||
func (s *session) Interaction() interaction.Interaction {
|
||||
return s.interaction
|
||||
}
|
||||
|
||||
func (s *session) Forwarder() forwarder.Forwarder {
|
||||
return s.forwarder
|
||||
}
|
||||
|
||||
func (s *session) Slug() slug.Slug {
|
||||
return s.slug
|
||||
}
|
||||
|
||||
func (s *session) Detail() *types.Detail {
|
||||
tunnelTypeMap := map[types.TunnelType]string{
|
||||
types.TunnelTypeHTTP: "HTTP",
|
||||
types.TunnelTypeTCP: "TCP",
|
||||
}
|
||||
tunnelType, ok := tunnelTypeMap[s.forwarder.TunnelType()]
|
||||
if !ok {
|
||||
tunnelType = "UNKNOWN"
|
||||
}
|
||||
|
||||
return &types.Detail{
|
||||
ForwardingType: tunnelType,
|
||||
Slug: s.slug.String(),
|
||||
UserID: s.lifecycle.User(),
|
||||
Active: s.lifecycle.IsActive(),
|
||||
StartedAt: s.lifecycle.StartedAt(),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *session) Start() error {
|
||||
if err := s.setupSessionMode(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
tcpipReq := s.waitForTCPIPForward()
|
||||
if tcpipReq == nil {
|
||||
return s.handleMissingForwardRequest()
|
||||
}
|
||||
|
||||
if s.shouldRejectUnauthorized() {
|
||||
return s.denyForwardingRequest(tcpipReq, nil, nil, "headless forwarding only allowed on node mode")
|
||||
}
|
||||
|
||||
if err := s.HandleTCPIPForward(tcpipReq); err != nil {
|
||||
return err
|
||||
}
|
||||
s.interaction.Start()
|
||||
|
||||
return s.waitForSessionEnd()
|
||||
}
|
||||
|
||||
func (s *session) setupSessionMode() error {
|
||||
select {
|
||||
case channel, ok := <-s.sshChan:
|
||||
if !ok {
|
||||
log.Println("Forwarding request channel closed")
|
||||
return nil
|
||||
}
|
||||
return s.setupInteractiveMode(channel)
|
||||
case <-time.After(500 * time.Millisecond):
|
||||
s.interaction.SetMode(types.InteractiveModeHEADLESS)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (s *session) setupInteractiveMode(channel ssh.NewChannel) error {
|
||||
ch, reqs, err := channel.Accept()
|
||||
if err != nil {
|
||||
log.Printf("failed to accept channel: %v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
go func() {
|
||||
err = s.HandleGlobalRequest(reqs)
|
||||
if err != nil {
|
||||
log.Printf("global request handler error: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
s.lifecycle.SetChannel(ch)
|
||||
s.interaction.SetChannel(ch)
|
||||
s.interaction.SetMode(types.InteractiveModeINTERACTIVE)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *session) handleMissingForwardRequest() error {
|
||||
err := s.interaction.Send(fmt.Sprintf("Port forwarding request not received. Ensure you ran the correct command with -R flag. Example: ssh %s -p %s -R 80:localhost:3000", s.config.Domain(), s.config.SSHPort()))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return fmt.Errorf("no forwarding Request")
|
||||
}
|
||||
|
||||
func (s *session) shouldRejectUnauthorized() bool {
|
||||
return s.interaction.Mode() == types.InteractiveModeHEADLESS &&
|
||||
s.config.Mode() == types.ServerModeSTANDALONE &&
|
||||
s.lifecycle.User() == "UNAUTHORIZED"
|
||||
}
|
||||
|
||||
func (s *session) waitForSessionEnd() error {
|
||||
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 {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *session) waitForTCPIPForward() *ssh.Request {
|
||||
select {
|
||||
case req, ok := <-s.initialReq:
|
||||
if !ok {
|
||||
log.Println("Forwarding request channel closed")
|
||||
return nil
|
||||
}
|
||||
if req.Type == "tcpip-forward" {
|
||||
return req
|
||||
}
|
||||
if err := req.Reply(false, nil); err != nil {
|
||||
log.Printf("Failed to reply to request: %v", err)
|
||||
}
|
||||
log.Printf("Expected tcpip-forward request, got: %s", req.Type)
|
||||
return nil
|
||||
case <-time.After(500 * time.Millisecond):
|
||||
log.Println("No forwarding request received")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (s *session) handleWindowChange(req *ssh.Request) error {
|
||||
p := req.Payload
|
||||
if len(p) < 16 {
|
||||
log.Println("invalid window-change payload")
|
||||
return req.Reply(false, nil)
|
||||
}
|
||||
|
||||
cols := binary.BigEndian.Uint32(p[0:4])
|
||||
rows := binary.BigEndian.Uint32(p[4:8])
|
||||
|
||||
s.interaction.SetWH(int(cols), int(rows))
|
||||
return req.Reply(true, nil)
|
||||
}
|
||||
|
||||
func (s *session) HandleGlobalRequest(GlobalRequest <-chan *ssh.Request) error {
|
||||
for req := range GlobalRequest {
|
||||
switch req.Type {
|
||||
case "shell", "pty-req":
|
||||
if err := req.Reply(true, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
case "window-change":
|
||||
if err := s.handleWindowChange(req); err != nil {
|
||||
return err
|
||||
}
|
||||
default:
|
||||
log.Println("Unknown request type:", req.Type)
|
||||
if err := req.Reply(false, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *session) parseForwardPayload(payload []byte) (address string, port uint16, err error) {
|
||||
var forwardPayload struct {
|
||||
BindAddr string
|
||||
BindPort uint32
|
||||
}
|
||||
|
||||
if err = ssh.Unmarshal(payload, &forwardPayload); err != nil {
|
||||
return "", 0, fmt.Errorf("failed to unmarshal forward payload: %w", err)
|
||||
}
|
||||
|
||||
if forwardPayload.BindPort > 65535 {
|
||||
return "", 0, fmt.Errorf("port is larger than allowed port of 65535")
|
||||
}
|
||||
|
||||
port = uint16(forwardPayload.BindPort)
|
||||
|
||||
if isBlockedPort(port) {
|
||||
return "", 0, fmt.Errorf("port is blocked")
|
||||
}
|
||||
|
||||
if port == 0 {
|
||||
unassigned, ok := s.lifecycle.PortRegistry().Unassigned()
|
||||
if !ok {
|
||||
return "", 0, fmt.Errorf("no available port")
|
||||
}
|
||||
return forwardPayload.BindAddr, unassigned, nil
|
||||
}
|
||||
|
||||
return forwardPayload.BindAddr, port, nil
|
||||
}
|
||||
|
||||
func (s *session) denyForwardingRequest(req *ssh.Request, key *types.SessionKey, listener io.Closer, msg string) error {
|
||||
var errs []error
|
||||
if key != nil {
|
||||
s.registry.Remove(*key)
|
||||
}
|
||||
|
||||
if listener != nil {
|
||||
errs = append(errs, listener.Close())
|
||||
}
|
||||
|
||||
errs = append(errs, req.Reply(false, nil))
|
||||
errs = append(errs, s.lifecycle.Close())
|
||||
errs = append(errs, fmt.Errorf("deny forwarding request: %s", msg))
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
func (s *session) finalizeForwarding(req *ssh.Request, portToBind uint16, listener net.Listener, tunnelType types.TunnelType, slug string) error {
|
||||
replyPayload := struct {
|
||||
BoundPort uint32
|
||||
}{
|
||||
BoundPort: uint32(portToBind),
|
||||
}
|
||||
err := req.Reply(true, ssh.Marshal(replyPayload))
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
s.forwarder.SetType(tunnelType)
|
||||
s.forwarder.SetForwardedPort(portToBind)
|
||||
s.slug.Set(slug)
|
||||
s.lifecycle.SetStatus(types.SessionStatusRUNNING)
|
||||
|
||||
if listener != nil {
|
||||
s.forwarder.SetListener(listener)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *session) HandleTCPIPForward(req *ssh.Request) error {
|
||||
address, port, err := s.parseForwardPayload(req.Payload)
|
||||
if err != nil {
|
||||
return s.denyForwardingRequest(req, nil, nil, fmt.Sprintf("cannot parse forwarded payload: %s", err.Error()))
|
||||
}
|
||||
|
||||
switch port {
|
||||
case 80, 443:
|
||||
return s.HandleHTTPForward(req, port)
|
||||
default:
|
||||
return s.HandleTCPForward(req, address, port)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *session) HandleHTTPForward(req *ssh.Request, portToBind uint16) error {
|
||||
randomString, err := s.randomizer.String(20)
|
||||
if err != nil {
|
||||
return s.denyForwardingRequest(req, nil, nil, fmt.Sprintf("Failed to create slug: %s", err))
|
||||
}
|
||||
key := types.SessionKey{Id: randomString, Type: types.TunnelTypeHTTP}
|
||||
if !s.registry.Register(key, s) {
|
||||
return s.denyForwardingRequest(req, nil, nil, fmt.Sprintf("Failed to register client with slug: %s", randomString))
|
||||
}
|
||||
|
||||
err = s.finalizeForwarding(req, portToBind, nil, types.TunnelTypeHTTP, key.Id)
|
||||
if err != nil {
|
||||
return s.denyForwardingRequest(req, &key, nil, fmt.Sprintf("Failed to finalize forwarding: %s", err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *session) HandleTCPForward(req *ssh.Request, addr string, portToBind uint16) error {
|
||||
if claimed := s.lifecycle.PortRegistry().Claim(portToBind); !claimed {
|
||||
return s.denyForwardingRequest(req, nil, nil, fmt.Sprintf("Port %d is already in use or restricted", portToBind))
|
||||
}
|
||||
|
||||
tcpServer := transport.NewTCPServer(portToBind, s.forwarder)
|
||||
listener, err := tcpServer.Listen()
|
||||
if err != nil {
|
||||
return s.denyForwardingRequest(req, nil, listener, fmt.Sprintf("Port %d is already in use or restricted", portToBind))
|
||||
}
|
||||
|
||||
key := types.SessionKey{Id: fmt.Sprintf("%d", portToBind), Type: types.TunnelTypeTCP}
|
||||
if !s.registry.Register(key, s) {
|
||||
return s.denyForwardingRequest(req, nil, listener, fmt.Sprintf("Failed to register TunnelTypeTCP client with id: %s", key.Id))
|
||||
}
|
||||
|
||||
err = s.finalizeForwarding(req, portToBind, listener, types.TunnelTypeTCP, key.Id)
|
||||
if err != nil {
|
||||
return s.denyForwardingRequest(req, &key, listener, fmt.Sprintf("Failed to finalize forwarding: %s", err))
|
||||
}
|
||||
|
||||
go func() {
|
||||
err = tcpServer.Serve(listener)
|
||||
if err != nil {
|
||||
log.Printf("Failed serving tcp server: %s\n", err)
|
||||
}
|
||||
}()
|
||||
|
||||
return 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
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,24 @@
|
||||
package slug
|
||||
|
||||
type Slug interface {
|
||||
String() string
|
||||
Set(slug string)
|
||||
}
|
||||
|
||||
type slug struct {
|
||||
slug string
|
||||
}
|
||||
|
||||
func New() Slug {
|
||||
return &slug{
|
||||
slug: "",
|
||||
}
|
||||
}
|
||||
|
||||
func (s *slug) String() string {
|
||||
return s.slug
|
||||
}
|
||||
|
||||
func (s *slug) Set(slug string) {
|
||||
s.slug = slug
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package slug
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/suite"
|
||||
)
|
||||
|
||||
type SlugTestSuite struct {
|
||||
suite.Suite
|
||||
slug Slug
|
||||
}
|
||||
|
||||
func (suite *SlugTestSuite) SetupTest() {
|
||||
suite.slug = New()
|
||||
}
|
||||
|
||||
func TestNew(t *testing.T) {
|
||||
s := New()
|
||||
|
||||
assert.NotNil(t, s, "New() should return a non-nil Slug")
|
||||
assert.Implements(t, (*Slug)(nil), s, "New() should return a type that implements Slug interface")
|
||||
assert.Equal(t, "", s.String(), "New() should initialize with empty string")
|
||||
}
|
||||
|
||||
func (suite *SlugTestSuite) TestString() {
|
||||
assert.Equal(suite.T(), "", suite.slug.String(), "String() should return empty string initially")
|
||||
|
||||
suite.slug.Set("test-slug")
|
||||
assert.Equal(suite.T(), "test-slug", suite.slug.String(), "String() should return the set value")
|
||||
}
|
||||
|
||||
func (suite *SlugTestSuite) TestSet() {
|
||||
testCases := []struct {
|
||||
name string
|
||||
input string
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
name: "simple slug",
|
||||
input: "hello-world",
|
||||
expected: "hello-world",
|
||||
},
|
||||
{
|
||||
name: "empty string",
|
||||
input: "",
|
||||
expected: "",
|
||||
},
|
||||
{
|
||||
name: "slug with numbers",
|
||||
input: "test-123",
|
||||
expected: "test-123",
|
||||
},
|
||||
{
|
||||
name: "slug with special characters",
|
||||
input: "hello_world-123",
|
||||
expected: "hello_world-123",
|
||||
},
|
||||
{
|
||||
name: "overwrite existing slug",
|
||||
input: "new-slug",
|
||||
expected: "new-slug",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
suite.Run(tc.name, func() {
|
||||
suite.slug.Set(tc.input)
|
||||
assert.Equal(suite.T(), tc.expected, suite.slug.String())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (suite *SlugTestSuite) TestMultipleSet() {
|
||||
suite.slug.Set("first-slug")
|
||||
assert.Equal(suite.T(), "first-slug", suite.slug.String())
|
||||
|
||||
suite.slug.Set("second-slug")
|
||||
assert.Equal(suite.T(), "second-slug", suite.slug.String())
|
||||
|
||||
suite.slug.Set("")
|
||||
assert.Equal(suite.T(), "", suite.slug.String())
|
||||
}
|
||||
|
||||
func TestSlugIsolation(t *testing.T) {
|
||||
slug1 := New()
|
||||
slug2 := New()
|
||||
|
||||
slug1.Set("slug-one")
|
||||
slug2.Set("slug-two")
|
||||
|
||||
assert.Equal(t, "slug-one", slug1.String(), "First slug should maintain its value")
|
||||
assert.Equal(t, "slug-two", slug2.String(), "Second slug should maintain its value")
|
||||
}
|
||||
|
||||
func TestSlugTestSuite(t *testing.T) {
|
||||
suite.Run(t, new(SlugTestSuite))
|
||||
}
|
||||
Reference in New Issue
Block a user