-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmain.go
More file actions
219 lines (191 loc) · 6.84 KB
/
Copy pathmain.go
File metadata and controls
219 lines (191 loc) · 6.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
package main
import (
"context"
"embed"
"errors"
"fmt"
"log/slog"
"net"
"os"
"os/signal"
"strings"
"syscall"
"time"
"windshift/internal/auth"
"windshift/internal/config"
"windshift/internal/database"
"windshift/internal/logger"
"windshift/internal/middleware"
"windshift/internal/server"
"windshift/internal/tui"
"windshift/internal/utils"
"charm.land/wish/v2"
"charm.land/wish/v2/activeterm"
wishbubbletea "charm.land/wish/v2/bubbletea"
"charm.land/wish/v2/logging"
"github.com/charmbracelet/ssh"
)
//go:embed all:frontend/dist
var frontendFiles embed.FS
//go:embed assets/banner.txt
var bannerArt string
// ANSI color for startup banner
const colorTeal = "\033[38;5;37m"
const colorReset = "\033[0m"
// printBanner prints the windshift logo at startup
func printBanner() {
fmt.Print(colorTeal)
fmt.Print(bannerArt)
fmt.Print(colorReset)
fmt.Println()
fmt.Println(colorTeal + " W I N D S H I F T" + colorReset)
fmt.Println(" Work Management Platform")
fmt.Println()
}
func main() {
// Setup signal handling for graceful shutdown
shutdownChan := make(chan os.Signal, 1)
signal.Notify(shutdownChan, os.Interrupt, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
// Resolve all flags + env vars into a single canonical Config. No other
// part of the app reads env vars or defines CLI flags directly.
cfg := config.Load(frontendFiles, shutdownChan)
// Initialize logger early
logger.Init(cfg.Logging.Level, cfg.Logging.Format)
// Apply the global SSRF-dialer override before any client is built. When on,
// server-side HTTP clients may reach loopback/private IPs (self-hosted SCM,
// Jira DC, local LLM gateways). Off by default; warn loudly when enabled.
utils.SetAllowLocalConnections(cfg.AllowLocalConnections)
if cfg.AllowLocalConnections {
slog.Warn("ALLOW_LOCAL_CONNECTIONS is enabled: server-side HTTP clients may dial loopback/private addresses (SSRF protections relaxed)")
}
// Print startup banner
printBanner()
// Resolve security configuration: auto-detect proxy, derive CORS hosts/ports, validate
resolved, err := server.ResolveSecurityConfig(cfg)
if err != nil {
slog.Error("security configuration error", "error", err)
os.Exit(1)
}
resolved.LogDiagnostics()
// Apply resolved values back to config
cfg.UseProxy = resolved.UseProxy
cfg.AllowedHosts = resolved.AllowedHosts
cfg.AllowedPort = resolved.AllowedPort
// Create and start the server
srv, err := server.New(cfg)
if err != nil {
slog.Error("failed to create server", "error", err)
os.Exit(1)
}
if err = srv.Start(); err != nil {
slog.Error("failed to start server", "error", err)
os.Exit(1)
}
// Setup SSH server if enabled
var sshServer *ssh.Server
var sshDB database.Database // Declared at function scope to allow explicit cleanup
if cfg.SSH.Enabled {
// 127.0.0.1 (not "localhost") so the loopback IP family the TUI's
// HTTP client dials matches what the SSH listener stored in the
// session row. "localhost" resolves to ::1 on modern systems while
// SSH typically binds to 127.0.0.1, and the legacy /api/* session
// middleware compares request IP against session IP by string
// equality — IPv4 vs IPv6 loopback would mismatch.
apiURL := fmt.Sprintf("http://127.0.0.1:%d", srv.Port())
var additionalProxyList []string
if cfg.AdditionalProxies != "" {
additionalProxyList = strings.Split(cfg.AdditionalProxies, ",")
}
enableHTTPS := cfg.TLSCertPath != "" && cfg.TLSKeyPath != ""
// Create a separate DB connection for SSH auth. This pool only services
// public-key auth + session/token lookups, so it gets a small fixed cap
// rather than cfg.DB.MaxReadConns — otherwise enabling SSH would double
// the process's draw against the server's max_connections.
if cfg.DB.PostgresConn != "" {
sshDB, err = database.NewDatabase("postgres", cfg.DB.PostgresConn, config.SSHDatabaseMaxConnections, cfg.DB.MaxWriteConns)
} else {
sshDB, err = database.NewDatabase("sqlite3", cfg.DB.SQLitePath, config.SSHDatabaseMaxConnections, cfg.DB.MaxWriteConns)
}
if err != nil {
slog.Error("failed to create SSH database connection", "error", err)
} else {
if registerErr := srv.RegisterDatabasePool("ssh", sshDB); registerErr != nil {
slog.Warn("failed to register SSH database pool for diagnostics", "error", registerErr)
}
sessionManager := auth.NewSessionManagerWithValidationCacheTTL(
sshDB,
enableHTTPS,
cfg.UseProxy,
additionalProxyList,
cfg.Auth.SessionSecret,
cfg.Auth.SessionValidationCacheTTL,
)
// nil tokenTracker: the SSH-minted temp tokens are short-lived
// (24h) and we don't need last-used-at tracking for them.
tokenManager := auth.NewTokenManager(sshDB, nil)
serverOptions := make([]ssh.Option, 0, 4)
serverOptions = append(serverOptions,
wish.WithAddress(net.JoinHostPort(cfg.SSH.Host, cfg.SSH.Port)),
wish.WithHostKeyPath(cfg.SSH.KeyPath),
)
slog.Info("SSH server starting with public key authentication enabled")
sshAuthMiddleware := middleware.NewSSHAuthMiddleware(sshDB)
serverOptions = append(serverOptions,
wish.WithPublicKeyAuth(sshAuthMiddleware.PublicKeyHandler()),
wish.WithIdleTimeout(30*time.Minute),
wish.WithMaxTimeout(24*time.Hour),
wish.WithMiddleware(
wishbubbletea.Middleware(tui.NewTUIHandler(apiURL, sessionManager, tokenManager)),
activeterm.Middleware(),
logging.Middleware(),
),
)
s, err := wish.NewServer(serverOptions...)
if err != nil {
slog.Error("failed to create SSH server", "error", err)
} else {
sshServer = s
slog.Info("SSH TUI server starting", "host", cfg.SSH.Host, "port", cfg.SSH.Port)
go func() {
if err := sshServer.ListenAndServe(); err != nil && !errors.Is(err, ssh.ErrServerClosed) {
slog.Error("SSH server error", "error", err)
}
}()
}
}
}
// Log startup info
if cfg.SSH.Enabled {
slog.Info("SSH TUI available", "command", "ssh "+cfg.SSH.Host+" -p "+cfg.SSH.Port)
}
// Wait for shutdown signal
<-shutdownChan
slog.Info("shutdown signal received, starting graceful shutdown")
// Shutdown SSH server first
if sshServer != nil {
slog.Info("shutting down SSH server")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
if err := sshServer.Shutdown(ctx); err != nil && !errors.Is(err, ssh.ErrServerClosed) {
slog.Error("SSH server shutdown error", "error", err)
} else {
slog.Info("SSH server shutdown complete")
}
cancel()
}
// Shutdown the main server
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
if err := srv.Shutdown(ctx); err != nil {
slog.Error("server shutdown error", "error", err)
cancel()
if sshDB != nil {
_ = sshDB.Close()
}
os.Exit(1)
}
cancel()
// Clean up SSH database connection
if sshDB != nil {
_ = sshDB.Close()
}
slog.Info("all servers stopped successfully")
}