1 Commits

Author SHA1 Message Date
4d0a7deaf2 Merge pull request 'staging' (#53) from staging into main
All checks were successful
Docker Build and Push / build-and-push (push) Successful in 3m33s
renovate / renovate (push) Successful in 22s
Reviewed-on: #53
2025-12-29 17:18:25 +00:00
17 changed files with 85 additions and 397 deletions

View File

@@ -5,8 +5,6 @@ on:
branches: branches:
- main - main
- staging - staging
tags:
- 'v*'
paths: paths:
- '**.go' - '**.go'
- 'go.mod' - 'go.mod'
@@ -17,9 +15,8 @@ on:
- '.gitea/workflows/build.yml' - '.gitea/workflows/build.yml'
jobs: jobs:
build-and-push-branches: build-and-push:
runs-on: ubuntu-latest runs-on: ubuntu-latest
if: github.ref_type == 'branch'
steps: steps:
- name: Checkout repository - name: Checkout repository
@@ -35,17 +32,6 @@ jobs:
username: ${{ secrets.DOCKER_USERNAME }} username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }} password: ${{ secrets.DOCKER_PASSWORD }}
- name: Set version variables
id: vars
run: |
if [ "${{ github.ref }}" == "refs/heads/main" ]; then
echo "VERSION=dev-main" >> $GITHUB_OUTPUT
else
echo "VERSION=dev-staging" >> $GITHUB_OUTPUT
fi
echo "BUILD_DATE=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" >> $GITHUB_OUTPUT
echo "COMMIT=${{ github.sha }}" >> $GITHUB_OUTPUT
- name: Build and push Docker image for main - name: Build and push Docker image for main
uses: docker/build-push-action@v6 uses: docker/build-push-action@v6
with: with:
@@ -54,10 +40,6 @@ jobs:
tags: | tags: |
git.fossy.my.id/${{ secrets.DOCKER_USERNAME }}/tunnel-please:latest git.fossy.my.id/${{ secrets.DOCKER_USERNAME }}/tunnel-please:latest
platforms: linux/amd64,linux/arm64 platforms: linux/amd64,linux/arm64
build-args: |
VERSION=${{ steps.vars.outputs.VERSION }}
BUILD_DATE=${{ steps.vars.outputs.BUILD_DATE }}
COMMIT=${{ steps.vars.outputs.COMMIT }}
if: github.ref == 'refs/heads/main' if: github.ref == 'refs/heads/main'
- name: Build and push Docker image for staging - name: Build and push Docker image for staging
@@ -68,85 +50,4 @@ jobs:
tags: | tags: |
git.fossy.my.id/${{ secrets.DOCKER_USERNAME }}/tunnel-please:staging git.fossy.my.id/${{ secrets.DOCKER_USERNAME }}/tunnel-please:staging
platforms: linux/amd64,linux/arm64 platforms: linux/amd64,linux/arm64
build-args: |
VERSION=${{ steps.vars.outputs.VERSION }}
BUILD_DATE=${{ steps.vars.outputs.BUILD_DATE }}
COMMIT=${{ steps.vars.outputs.COMMIT }}
if: github.ref == 'refs/heads/staging' if: github.ref == 'refs/heads/staging'
build-and-push-tags:
runs-on: ubuntu-latest
if: github.ref_type == 'tag' && startsWith(github.ref, 'refs/tags/v')
steps:
- name: Checkout repository
uses: actions/checkout@v6
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to Docker Hub
uses: docker/login-action@v3
with:
registry: git.fossy.my.id
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Extract version and determine release type
id: version
run: |
VERSION=${GITHUB_REF#refs/tags/v}
echo "VERSION=$VERSION" >> $GITHUB_OUTPUT
echo "BUILD_DATE=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" >> $GITHUB_OUTPUT
echo "COMMIT=${{ github.sha }}" >> $GITHUB_OUTPUT
if echo "$VERSION" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9.]+)?$'; then
MAJOR=$(echo "$VERSION" | cut -d. -f1)
MINOR=$(echo "$VERSION" | cut -d. -f2)
echo "MAJOR=$MAJOR" >> $GITHUB_OUTPUT
echo "MINOR=$MINOR" >> $GITHUB_OUTPUT
if echo "$VERSION" | grep -q '-'; then
echo "IS_PRERELEASE=true" >> $GITHUB_OUTPUT
echo "ADDITIONAL_TAG=staging" >> $GITHUB_OUTPUT
else
echo "IS_PRERELEASE=false" >> $GITHUB_OUTPUT
echo "ADDITIONAL_TAG=latest" >> $GITHUB_OUTPUT
fi
else
echo "Invalid version format: $VERSION"
exit 1
fi
- name: Build and push Docker image for release
uses: docker/build-push-action@v6
with:
context: .
push: true
tags: |
git.fossy.my.id/${{ secrets.DOCKER_USERNAME }}/tunnel-please:v${{ steps.version.outputs.VERSION }}
git.fossy.my.id/${{ secrets.DOCKER_USERNAME }}/tunnel-please:v${{ steps.version.outputs.MAJOR }}.${{ steps.version.outputs.MINOR }}
git.fossy.my.id/${{ secrets.DOCKER_USERNAME }}/tunnel-please:v${{ steps.version.outputs.MAJOR }}
git.fossy.my.id/${{ secrets.DOCKER_USERNAME }}/tunnel-please:${{ steps.version.outputs.ADDITIONAL_TAG }}
platforms: linux/amd64,linux/arm64
build-args: |
VERSION=${{ steps.version.outputs.VERSION }}
BUILD_DATE=${{ steps.version.outputs.BUILD_DATE }}
COMMIT=${{ steps.version.outputs.COMMIT }}
if: steps.version.outputs.IS_PRERELEASE == 'false'
- name: Build and push Docker image for pre-release
uses: docker/build-push-action@v6
with:
context: .
push: true
tags: |
git.fossy.my.id/${{ secrets.DOCKER_USERNAME }}/tunnel-please:v${{ steps.version.outputs.VERSION }}
git.fossy.my.id/${{ secrets.DOCKER_USERNAME }}/tunnel-please:${{ steps.version.outputs.ADDITIONAL_TAG }}
platforms: linux/amd64,linux/arm64
build-args: |
VERSION=${{ steps.version.outputs.VERSION }}
BUILD_DATE=${{ steps.version.outputs.BUILD_DATE }}
COMMIT=${{ steps.version.outputs.COMMIT }}
if: steps.version.outputs.IS_PRERELEASE == 'true'

View File

@@ -1,9 +1,5 @@
FROM golang:1.25.5-alpine AS go_builder FROM golang:1.25.5-alpine AS go_builder
ARG VERSION=dev
ARG BUILD_DATE=unknown
ARG COMMIT=unknown
RUN apk update && apk upgrade && \ RUN apk update && apk upgrade && \
apk add --no-cache ca-certificates tzdata git && \ apk add --no-cache ca-certificates tzdata git && \
update-ca-certificates update-ca-certificates
@@ -22,7 +18,7 @@ RUN --mount=type=cache,target=/go/pkg/mod \
--mount=type=cache,target=/root/.cache/go-build \ --mount=type=cache,target=/root/.cache/go-build \
CGO_ENABLED=0 GOOS=linux \ CGO_ENABLED=0 GOOS=linux \
go build -trimpath \ go build -trimpath \
-ldflags="-w -s -X tunnel_pls/version.Version=${VERSION} -X tunnel_pls/version.BuildDate=${BUILD_DATE} -X tunnel_pls/version.Commit=${COMMIT}" \ -ldflags="-w -s" \
-o /app/tunnel_pls \ -o /app/tunnel_pls \
. .
@@ -32,10 +28,6 @@ RUN adduser -D -u 10001 -g '' appuser && \
FROM scratch FROM scratch
ARG VERSION=dev
ARG BUILD_DATE=unknown
ARG COMMIT=unknown
COPY --from=go_builder /usr/share/zoneinfo /usr/share/zoneinfo COPY --from=go_builder /usr/share/zoneinfo /usr/share/zoneinfo
COPY --from=go_builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ COPY --from=go_builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
COPY --from=go_builder /etc/passwd /etc/passwd COPY --from=go_builder /etc/passwd /etc/passwd
@@ -51,9 +43,6 @@ ENV TZ=Asia/Jakarta
EXPOSE 2200 8080 8443 EXPOSE 2200 8080 8443
LABEL org.opencontainers.image.title="Tunnel Please" \ LABEL org.opencontainers.image.title="Tunnel Please" \
org.opencontainers.image.description="SSH-based tunnel server" \ org.opencontainers.image.description="SSH-based tunnel server"
org.opencontainers.image.version="${VERSION}" \
org.opencontainers.image.revision="${COMMIT}" \
org.opencontainers.image.created="${BUILD_DATE}"
ENTRYPOINT ["/app/tunnel_pls"] ENTRYPOINT ["/app/tunnel_pls"]

View File

@@ -1,35 +0,0 @@
package config
import (
"log"
"os"
"strconv"
"github.com/joho/godotenv"
)
func init() {
if _, err := os.Stat(".env"); err == nil {
if err := godotenv.Load(".env"); err != nil {
log.Printf("Warning: Failed to load .env file: %s", err)
}
}
}
func Getenv(key, defaultValue string) string {
val := os.Getenv(key)
if val == "" {
val = defaultValue
}
return val
}
func GetBufferSize() int {
sizeStr := Getenv("BUFFER_SIZE", "32768")
size, err := strconv.Atoi(sizeStr)
if err != nil || size < 4096 || size > 1048576 {
return 32768
}
return size
}

View File

@@ -6,7 +6,7 @@ import (
"strconv" "strconv"
"strings" "strings"
"sync" "sync"
"tunnel_pls/internal/config" "tunnel_pls/utils"
) )
type Manager interface { type Manager interface {
@@ -28,7 +28,7 @@ var Default Manager = &manager{
} }
func init() { func init() {
rawRange := config.Getenv("ALLOWED_PORTS", "") rawRange := utils.Getenv("ALLOWED_PORTS", "")
if rawRange == "" { if rawRange == "" {
return return
} }

View File

@@ -1,18 +0,0 @@
package random
import (
mathrand "math/rand"
"strings"
"time"
)
func GenerateRandomString(length int) string {
const charset = "abcdefghijklmnopqrstuvwxyz"
seededRand := mathrand.New(mathrand.NewSource(time.Now().UnixNano() + int64(mathrand.Intn(9999))))
var result strings.Builder
for i := 0; i < length; i++ {
randomIndex := seededRand.Intn(len(charset))
result.WriteString(string(charset[randomIndex]))
}
return result.String()
}

19
main.go
View File

@@ -6,28 +6,19 @@ import (
"net/http" "net/http"
_ "net/http/pprof" _ "net/http/pprof"
"os" "os"
"tunnel_pls/internal/config"
"tunnel_pls/internal/key"
"tunnel_pls/server" "tunnel_pls/server"
"tunnel_pls/version" "tunnel_pls/utils"
"golang.org/x/crypto/ssh" "golang.org/x/crypto/ssh"
) )
func main() { func main() {
if len(os.Args) > 1 && (os.Args[1] == "--version" || os.Args[1] == "-v") {
fmt.Println(version.GetVersion())
os.Exit(0)
}
log.SetOutput(os.Stdout) log.SetOutput(os.Stdout)
log.SetFlags(log.LstdFlags | log.Lshortfile) log.SetFlags(log.LstdFlags | log.Lshortfile)
log.Printf("Starting %s", version.GetVersion()) pprofEnabled := utils.Getenv("PPROF_ENABLED", "false")
pprofEnabled := config.Getenv("PPROF_ENABLED", "false")
if pprofEnabled == "true" { if pprofEnabled == "true" {
pprofPort := config.Getenv("PPROF_PORT", "6060") pprofPort := utils.Getenv("PPROF_PORT", "6060")
go func() { go func() {
pprofAddr := fmt.Sprintf("localhost:%s", pprofPort) pprofAddr := fmt.Sprintf("localhost:%s", pprofPort)
log.Printf("Starting pprof server on http://%s/debug/pprof/", pprofAddr) log.Printf("Starting pprof server on http://%s/debug/pprof/", pprofAddr)
@@ -39,11 +30,11 @@ func main() {
sshConfig := &ssh.ServerConfig{ sshConfig := &ssh.ServerConfig{
NoClientAuth: true, NoClientAuth: true,
ServerVersion: fmt.Sprintf("SSH-2.0-TunnlPls-%s", version.GetShortVersion()), ServerVersion: "SSH-2.0-TunnlPls-1.0",
} }
sshKeyPath := "certs/ssh/id_rsa" sshKeyPath := "certs/ssh/id_rsa"
if err := key.GenerateSSHKeyIfNotExist(sshKeyPath); err != nil { if err := utils.GenerateSSHKeyIfNotExist(sshKeyPath); err != nil {
log.Fatalf("Failed to generate SSH key: %s", err) log.Fatalf("Failed to generate SSH key: %s", err)
} }

View File

@@ -11,8 +11,8 @@ import (
"regexp" "regexp"
"strings" "strings"
"time" "time"
"tunnel_pls/internal/config"
"tunnel_pls/session" "tunnel_pls/session"
"tunnel_pls/utils"
"golang.org/x/crypto/ssh" "golang.org/x/crypto/ssh"
) )
@@ -231,12 +231,12 @@ func (cw *customWriter) AddInteraction(interaction Interaction) {
var redirectTLS = false var redirectTLS = false
func NewHTTPServer() error { func NewHTTPServer() error {
httpPort := config.Getenv("HTTP_PORT", "8080") httpPort := utils.Getenv("HTTP_PORT", "8080")
listener, err := net.Listen("tcp", ":"+httpPort) listener, err := net.Listen("tcp", ":"+httpPort)
if err != nil { if err != nil {
return errors.New("Error listening: " + err.Error()) return errors.New("Error listening: " + err.Error())
} }
if config.Getenv("TLS_ENABLED", "false") == "true" && config.Getenv("TLS_REDIRECT", "false") == "true" { if utils.Getenv("TLS_ENABLED", "false") == "true" && utils.Getenv("TLS_REDIRECT", "false") == "true" {
redirectTLS = true redirectTLS = true
} }
go func() { go func() {
@@ -288,7 +288,7 @@ func Handler(conn net.Conn) {
if redirectTLS { if redirectTLS {
_, err = conn.Write([]byte("HTTP/1.1 301 Moved Permanently\r\n" + _, err = conn.Write([]byte("HTTP/1.1 301 Moved Permanently\r\n" +
fmt.Sprintf("Location: https://%s.%s/\r\n", slug, config.Getenv("DOMAIN", "localhost")) + fmt.Sprintf("Location: https://%s.%s/\r\n", slug, utils.Getenv("DOMAIN", "localhost")) +
"Content-Length: 0\r\n" + "Content-Length: 0\r\n" +
"Connection: close\r\n" + "Connection: close\r\n" +
"\r\n")) "\r\n"))

View File

@@ -8,13 +8,13 @@ import (
"log" "log"
"net" "net"
"strings" "strings"
"tunnel_pls/internal/config"
"tunnel_pls/session" "tunnel_pls/session"
"tunnel_pls/utils"
) )
func NewHTTPSServer() error { func NewHTTPSServer() error {
domain := config.Getenv("DOMAIN", "localhost") domain := utils.Getenv("DOMAIN", "localhost")
httpsPort := config.Getenv("HTTPS_PORT", "8443") httpsPort := utils.Getenv("HTTPS_PORT", "8443")
tlsConfig, err := NewTLSConfig(domain) tlsConfig, err := NewTLSConfig(domain)
if err != nil { if err != nil {

View File

@@ -5,7 +5,7 @@ import (
"log" "log"
"net" "net"
"net/http" "net/http"
"tunnel_pls/internal/config" "tunnel_pls/utils"
"golang.org/x/crypto/ssh" "golang.org/x/crypto/ssh"
) )
@@ -28,13 +28,13 @@ func (s *Server) GetHttpServer() *http.Server {
return s.httpServer return s.httpServer
} }
func NewServer(sshConfig *ssh.ServerConfig) *Server { func NewServer(config *ssh.ServerConfig) *Server {
listener, err := net.Listen("tcp", fmt.Sprintf(":%s", config.Getenv("PORT", "2200"))) listener, err := net.Listen("tcp", fmt.Sprintf(":%s", utils.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)
return nil return nil
} }
if config.Getenv("TLS_ENABLED", "false") == "true" { if utils.Getenv("TLS_ENABLED", "false") == "true" {
err = NewHTTPSServer() err = NewHTTPSServer()
if err != nil { if err != nil {
log.Fatalf("failed to start https server: %v", err) log.Fatalf("failed to start https server: %v", err)
@@ -46,7 +46,7 @@ func NewServer(sshConfig *ssh.ServerConfig) *Server {
} }
return &Server{ return &Server{
conn: &listener, conn: &listener,
config: sshConfig, config: config,
} }
} }

View File

@@ -10,7 +10,7 @@ import (
"os" "os"
"sync" "sync"
"time" "time"
"tunnel_pls/internal/config" "tunnel_pls/utils"
"github.com/caddyserver/certmagic" "github.com/caddyserver/certmagic"
"github.com/libdns/cloudflare" "github.com/libdns/cloudflare"
@@ -92,7 +92,7 @@ func NewTLSConfig(domain string) (*tls.Config, error) {
} }
func isACMEConfigComplete() bool { func isACMEConfigComplete() bool {
cfAPIToken := config.Getenv("CF_API_TOKEN", "") cfAPIToken := utils.Getenv("CF_API_TOKEN", "")
return cfAPIToken != "" return cfAPIToken != ""
} }
@@ -241,9 +241,9 @@ func (tm *tlsManager) initCertMagic() error {
return fmt.Errorf("failed to create cert storage directory: %w", err) return fmt.Errorf("failed to create cert storage directory: %w", err)
} }
acmeEmail := config.Getenv("ACME_EMAIL", "admin@"+tm.domain) acmeEmail := utils.Getenv("ACME_EMAIL", "admin@"+tm.domain)
cfAPIToken := config.Getenv("CF_API_TOKEN", "") cfAPIToken := utils.Getenv("CF_API_TOKEN", "")
acmeStaging := config.Getenv("ACME_STAGING", "false") == "true" acmeStaging := utils.Getenv("ACME_STAGING", "false") == "true"
if cfAPIToken == "" { if cfAPIToken == "" {
return fmt.Errorf("CF_API_TOKEN environment variable is required for automatic certificate generation") return fmt.Errorf("CF_API_TOKEN environment variable is required for automatic certificate generation")

View File

@@ -10,16 +10,16 @@ import (
"strconv" "strconv"
"sync" "sync"
"time" "time"
"tunnel_pls/internal/config"
"tunnel_pls/session/slug" "tunnel_pls/session/slug"
"tunnel_pls/types" "tunnel_pls/types"
"tunnel_pls/utils"
"golang.org/x/crypto/ssh" "golang.org/x/crypto/ssh"
) )
var bufferPool = sync.Pool{ var bufferPool = sync.Pool{
New: func() interface{} { New: func() interface{} {
bufSize := config.GetBufferSize() bufSize := utils.GetBufferSize()
return make([]byte, bufSize) return make([]byte, bufSize)
}, },
} }

View File

@@ -7,9 +7,10 @@ import (
"log" "log"
"net" "net"
portUtil "tunnel_pls/internal/port" portUtil "tunnel_pls/internal/port"
"tunnel_pls/internal/random"
"tunnel_pls/types" "tunnel_pls/types"
"tunnel_pls/utils"
"golang.org/x/crypto/ssh" "golang.org/x/crypto/ssh"
) )
@@ -275,7 +276,7 @@ func generateUniqueSlug() string {
maxAttempts := 5 maxAttempts := 5
for i := 0; i < maxAttempts; i++ { for i := 0; i < maxAttempts; i++ {
slug := random.GenerateRandomString(20) slug := utils.GenerateRandomString(20)
clientsMutex.RLock() clientsMutex.RLock()
_, exists := Clients[slug] _, exists := Clients[slug]

View File

@@ -22,131 +22,6 @@ const (
paddingRight = 4 paddingRight = 4
) )
var forbiddenSlugs = map[string]struct{}{ var forbiddenSlugs = []string{
"ping": {}, "ping",
"staging": {},
"admin": {},
"root": {},
"api": {},
"www": {},
"support": {},
"help": {},
"status": {},
"health": {},
"login": {},
"logout": {},
"signup": {},
"register": {},
"settings": {},
"config": {},
"null": {},
"undefined": {},
"example": {},
"test": {},
"dev": {},
"system": {},
"administrator": {},
"dashboard": {},
"account": {},
"profile": {},
"user": {},
"users": {},
"auth": {},
"oauth": {},
"callback": {},
"webhook": {},
"webhooks": {},
"static": {},
"assets": {},
"cdn": {},
"mail": {},
"email": {},
"ftp": {},
"ssh": {},
"git": {},
"svn": {},
"blog": {},
"news": {},
"about": {},
"contact": {},
"terms": {},
"privacy": {},
"legal": {},
"billing": {},
"payment": {},
"checkout": {},
"cart": {},
"shop": {},
"store": {},
"download": {},
"uploads": {},
"images": {},
"img": {},
"css": {},
"js": {},
"fonts": {},
"public": {},
"private": {},
"internal": {},
"external": {},
"proxy": {},
"cache": {},
"debug": {},
"metrics": {},
"monitoring": {},
"graphql": {},
"rest": {},
"rpc": {},
"socket": {},
"ws": {},
"wss": {},
"app": {},
"apps": {},
"mobile": {},
"desktop": {},
"embed": {},
"widget": {},
"docs": {},
"documentation": {},
"wiki": {},
"forum": {},
"community": {},
"feedback": {},
"report": {},
"abuse": {},
"spam": {},
"security": {},
"verify": {},
"confirm": {},
"reset": {},
"password": {},
"recovery": {},
"unsubscribe": {},
"subscribe": {},
"notifications": {},
"alerts": {},
"messages": {},
"inbox": {},
"outbox": {},
"sent": {},
"draft": {},
"trash": {},
"archive": {},
"search": {},
"explore": {},
"discover": {},
"trending": {},
"popular": {},
"featured": {},
"new": {},
"latest": {},
"top": {},
"best": {},
"hot": {},
"random": {},
"all": {},
"any": {},
"none": {},
"true": {},
"false": {},
} }

View File

@@ -6,10 +6,9 @@ import (
"log" "log"
"strings" "strings"
"time" "time"
"tunnel_pls/internal/config"
"tunnel_pls/internal/random"
"tunnel_pls/session/slug" "tunnel_pls/session/slug"
"tunnel_pls/types" "tunnel_pls/types"
"tunnel_pls/utils"
"github.com/charmbracelet/bubbles/help" "github.com/charmbracelet/bubbles/help"
"github.com/charmbracelet/bubbles/key" "github.com/charmbracelet/bubbles/key"
@@ -206,20 +205,7 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
return m, tea.Batch(tea.ClearScreen, textinput.Blink) return m, tea.Batch(tea.ClearScreen, textinput.Blink)
case "enter": case "enter":
inputValue := m.slugInput.Value() inputValue := m.slugInput.Value()
m.interaction.updateClientSlug(m.interaction.slugManager.Get(), inputValue)
if isForbiddenSlug(inputValue) {
m.slugError = "This subdomain is reserved. Please choose a different one."
return m, nil
} else if !isValidSlug(inputValue) {
m.slugError = "Invalid subdomain. Follow the rules."
return m, nil
}
if !m.interaction.updateClientSlug(m.interaction.slugManager.Get(), inputValue) {
m.slugError = "Someone already uses this subdomain."
return m, nil
}
m.tunnelURL = buildURL(m.protocol, inputValue, m.domain) m.tunnelURL = buildURL(m.protocol, inputValue, m.domain)
m.editingSlug = false m.editingSlug = false
m.slugError = "" m.slugError = ""
@@ -723,9 +709,9 @@ func (m model) View() string {
func (i *Interaction) Start() { func (i *Interaction) Start() {
lipgloss.SetColorProfile(termenv.TrueColor) lipgloss.SetColorProfile(termenv.TrueColor)
domain := config.Getenv("DOMAIN", "localhost") domain := utils.Getenv("DOMAIN", "localhost")
protocol := "http" protocol := "http"
if config.Getenv("TLS_ENABLED", "false") == "true" { if utils.Getenv("TLS_ENABLED", "false") == "true" {
protocol = "https" protocol = "https"
} }
@@ -812,32 +798,5 @@ func buildURL(protocol, subdomain, domain string) string {
} }
func generateRandomSubdomain() string { func generateRandomSubdomain() string {
return random.GenerateRandomString(20) return utils.GenerateRandomString(20)
}
func isValidSlug(slug string) bool {
if len(slug) < minSlugLength || len(slug) > maxSlugLength {
return false
}
if slug[0] == '-' || slug[len(slug)-1] == '-' {
return false
}
for _, c := range slug {
if !isValidSlugChar(byte(c)) {
return false
}
}
return true
}
func isValidSlugChar(c byte) bool {
return (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-'
}
func isForbiddenSlug(slug string) bool {
_, ok := forbiddenSlugs[slug]
return ok
} }

View File

@@ -4,11 +4,11 @@ import (
"log" "log"
"sync" "sync"
"time" "time"
"tunnel_pls/internal/config"
"tunnel_pls/session/forwarder" "tunnel_pls/session/forwarder"
"tunnel_pls/session/interaction" "tunnel_pls/session/interaction"
"tunnel_pls/session/lifecycle" "tunnel_pls/session/lifecycle"
"tunnel_pls/session/slug" "tunnel_pls/session/slug"
"tunnel_pls/utils"
"golang.org/x/crypto/ssh" "golang.org/x/crypto/ssh"
) )
@@ -79,7 +79,7 @@ func New(conn *ssh.ServerConn, forwardingReq <-chan *ssh.Request, sshChan <-chan
tcpipReq := session.waitForTCPIPForward(forwardingReq) tcpipReq := session.waitForTCPIPForward(forwardingReq)
if tcpipReq == nil { if tcpipReq == nil {
log.Printf("Port forwarding request not received. Ensure you ran the correct command with -R flag. Example: ssh %s -p %s -R 80:localhost:3000", config.Getenv("DOMAIN", "localhost"), config.Getenv("PORT", "2200")) log.Printf("Port forwarding request not received. Ensure you ran the correct command with -R flag. Example: ssh %s -p %s -R 80:localhost:3000", utils.Getenv("DOMAIN", "localhost"), utils.Getenv("PORT", "2200"))
if err := session.lifecycle.Close(); err != nil { if err := session.lifecycle.Close(); err != nil {
log.Printf("failed to close session: %v", err) log.Printf("failed to close session: %v", err)
} }

View File

@@ -1,4 +1,4 @@
package key package utils
import ( import (
"crypto/rand" "crypto/rand"
@@ -6,12 +6,54 @@ import (
"crypto/x509" "crypto/x509"
"encoding/pem" "encoding/pem"
"log" "log"
mathrand "math/rand"
"os" "os"
"path/filepath" "path/filepath"
"strconv"
"strings"
"time"
"github.com/joho/godotenv"
"golang.org/x/crypto/ssh" "golang.org/x/crypto/ssh"
) )
func init() {
if _, err := os.Stat(".env"); err == nil {
if err := godotenv.Load(".env"); err != nil {
log.Printf("Warning: Failed to load .env file: %s", err)
}
}
}
func GenerateRandomString(length int) string {
const charset = "abcdefghijklmnopqrstuvwxyz"
seededRand := mathrand.New(mathrand.NewSource(time.Now().UnixNano() + int64(mathrand.Intn(9999))))
var result strings.Builder
for i := 0; i < length; i++ {
randomIndex := seededRand.Intn(len(charset))
result.WriteString(string(charset[randomIndex]))
}
return result.String()
}
func Getenv(key, defaultValue string) string {
val := os.Getenv(key)
if val == "" {
val = defaultValue
}
return val
}
func GetBufferSize() int {
sizeStr := Getenv("BUFFER_SIZE", "32768")
size, err := strconv.Atoi(sizeStr)
if err != nil || size < 4096 || size > 1048576 {
return 32768
}
return size
}
func GenerateSSHKeyIfNotExist(keyPath string) error { func GenerateSSHKeyIfNotExist(keyPath string) error {
if _, err := os.Stat(keyPath); err == nil { if _, err := os.Stat(keyPath); err == nil {
log.Printf("SSH key already exists at %s", keyPath) log.Printf("SSH key already exists at %s", keyPath)

View File

@@ -1,17 +0,0 @@
package version
import "fmt"
var (
Version = "dev"
BuildDate = "unknown"
Commit = "unknown"
)
func GetVersion() string {
return fmt.Sprintf("tunnel_pls %s (commit: %s, built: %s)", Version, Commit, BuildDate)
}
func GetShortVersion() string {
return Version
}