-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
322 lines (286 loc) · 9.22 KB
/
main.go
File metadata and controls
322 lines (286 loc) · 9.22 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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
package main
import (
"context"
"crypto/ed25519"
"encoding/hex"
"flag"
"fmt"
"log"
"os"
"os/signal"
"path/filepath"
"syscall"
"time"
tea "github.com/charmbracelet/bubbletea"
"github.com/boxsie/ensemble/internal/daemon"
"github.com/boxsie/ensemble/internal/identity"
"github.com/boxsie/ensemble/internal/ui"
)
func main() {
if len(os.Args) > 1 {
switch os.Args[1] {
case "attach":
runAttach(os.Args[2:])
return
case "debug":
runDebug(os.Args[2:])
return
case "keygen":
runKeygen(os.Args[2:])
return
case "add-node":
runAddNode(os.Args[2:])
return
}
}
runDaemon(os.Args[1:])
}
// runDaemon starts the daemon and optionally the TUI.
func runDaemon(args []string) {
fs := flag.NewFlagSet("ensemble", flag.ExitOnError)
headless := fs.Bool("headless", false, "run daemon without TUI")
dataDir := fs.String("data-dir", "", "override data directory")
apiAddr := fs.String("api-addr", "", "TCP listen address for gRPC (headless mode)")
apiSocket := fs.String("api-socket", "", "Unix socket path for gRPC (combine with --api-addr to listen on both)")
adminKey := fs.String("admin-key", os.Getenv("ENSEMBLE_ADMIN_KEY"), "hex-encoded Ed25519 admin public key (or ENSEMBLE_ADMIN_KEY env)")
torPath := fs.String("tor-path", "", "path to tor binary (skip auto-download)")
fs.Parse(args)
cfg := daemon.DefaultConfig()
if *dataDir != "" {
cfg.DataDir = *dataDir
cfg.SocketPath = filepath.Join(*dataDir, "ensemble.sock")
}
if *apiAddr != "" {
cfg.TCPAddr = *apiAddr
// Preserve historical behavior: --api-addr alone means TCP only.
// Operators wanting both TCP and a socket pass --api-socket explicitly.
cfg.SocketPath = ""
}
if *apiSocket != "" {
cfg.SocketPath = *apiSocket
}
if *adminKey != "" {
cfg.AdminKey = *adminKey
}
if *torPath != "" {
cfg.TorPath = *torPath
}
d := daemon.New(cfg)
if err := d.Start(); err != nil {
log.Fatalf("failed to start daemon: %v", err)
}
defer d.Stop()
if *headless {
log.Printf("running in headless mode")
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
<-sig
log.Printf("shutting down")
return
}
// In-process TUI.
backend := ui.NewDirectBackend(d.Node())
app := ui.NewApp(backend)
p := tea.NewProgram(app, tea.WithAltScreen())
if _, err := p.Run(); err != nil {
log.Fatalf("TUI error: %v", err)
}
}
// runAttach connects a TUI to an already-running daemon.
func runAttach(args []string) {
fs := flag.NewFlagSet("attach", flag.ExitOnError)
socketPath := fs.String("socket", "", "daemon socket path")
addr := fs.String("addr", "", "daemon TCP address (e.g. localhost:9090)")
authKey := fs.String("auth-key", "", "path to Ed25519 seed file for authentication")
useTLS := fs.Bool("tls", false, "wrap the connection in TLS (use for HTTPS ingress)")
tlsInsecure := fs.Bool("tls-insecure", false, "use TLS but skip certificate verification")
fs.Parse(args)
var target string
switch {
case *addr != "":
target = *addr
case *socketPath != "":
target = "unix://" + *socketPath
default:
home, _ := os.UserHomeDir()
target = "unix://" + filepath.Join(home, ".ensemble", "ensemble.sock")
}
var privKey ed25519.PrivateKey
if *authKey != "" {
var err error
privKey, err = loadAuthKey(*authKey)
if err != nil {
fmt.Fprintf(os.Stderr, "loading auth key: %v\n", err)
os.Exit(1)
}
}
backend, err := ui.NewGRPCBackend(target, privKey, grpcTLSOptions(*useTLS, *tlsInsecure)...)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to connect to daemon: %v\n", err)
os.Exit(1)
}
defer backend.Close()
app := ui.NewApp(backend)
p := tea.NewProgram(app, tea.WithAltScreen())
if _, err := p.Run(); err != nil {
fmt.Fprintf(os.Stderr, "TUI error: %v\n", err)
os.Exit(1)
}
}
// runDebug connects via gRPC and prints diagnostic info to stdout.
func runDebug(args []string) {
fs := flag.NewFlagSet("debug", flag.ExitOnError)
socketPath := fs.String("socket", "", "daemon socket path")
addr := fs.String("addr", "", "daemon TCP address (e.g. localhost:9090)")
authKey := fs.String("auth-key", "", "path to Ed25519 seed file for authentication")
useTLS := fs.Bool("tls", false, "wrap the connection in TLS (use for HTTPS ingress)")
tlsInsecure := fs.Bool("tls-insecure", false, "use TLS but skip certificate verification")
fs.Parse(args)
var target string
switch {
case *addr != "":
target = *addr
case *socketPath != "":
target = "unix://" + *socketPath
default:
home, _ := os.UserHomeDir()
target = "unix://" + filepath.Join(home, ".ensemble", "ensemble.sock")
}
var privKey ed25519.PrivateKey
if *authKey != "" {
var err error
privKey, err = loadAuthKey(*authKey)
if err != nil {
fmt.Fprintf(os.Stderr, "loading auth key: %v\n", err)
os.Exit(1)
}
}
backend, err := ui.NewGRPCBackend(target, privKey, grpcTLSOptions(*useTLS, *tlsInsecure)...)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to connect to daemon: %v\n", err)
os.Exit(1)
}
defer backend.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
info, err := backend.GetDebugInfo(ctx)
if err != nil {
fmt.Fprintf(os.Stderr, "GetDebugInfo failed: %v\n", err)
os.Exit(1)
}
fmt.Printf("Onion: %s\n", info.OnionAddr)
fmt.Printf("\nRouting Table (%d peers):\n", info.RTSize)
if len(info.RTPeers) == 0 {
fmt.Println(" (empty)")
} else {
for _, p := range info.RTPeers {
ago := time.Since(time.UnixMilli(p.LastSeen)).Truncate(time.Second)
fmt.Printf(" %-36s %-62s %s ago\n", p.Address, p.OnionAddr, ago)
}
}
fmt.Printf("\nConnections (%d):\n", len(info.Connections))
if len(info.Connections) == 0 {
fmt.Println(" (none)")
} else {
for _, c := range info.Connections {
line := fmt.Sprintf(" %-36s %s", c.Address, c.State)
if c.Error != "" {
line += fmt.Sprintf(" err: %s", c.Error)
}
fmt.Println(line)
}
}
}
// runKeygen generates an Ed25519 admin keypair for gRPC authentication.
func runKeygen(args []string) {
fs := flag.NewFlagSet("keygen", flag.ExitOnError)
output := fs.String("output", "admin.key", "path to save the private seed file")
fs.Parse(args)
kp, err := identity.Generate()
if err != nil {
fmt.Fprintf(os.Stderr, "generating keypair: %v\n", err)
os.Exit(1)
}
// Save the 32-byte seed (enough to reconstruct the full keypair).
if err := os.WriteFile(*output, kp.Seed(), 0600); err != nil {
fmt.Fprintf(os.Stderr, "writing key file: %v\n", err)
os.Exit(1)
}
pubHex := hex.EncodeToString(kp.PublicKey())
fmt.Printf("Admin key generated.\n\n")
fmt.Printf(" Private seed: %s (keep secret!)\n", *output)
fmt.Printf(" Public key: %s\n\n", pubHex)
fmt.Printf("Server: ensemble --headless --admin-key %s\n", pubHex)
fmt.Printf("Client: ensemble debug --auth-key %s --addr host:9090\n", *output)
}
// runAddNode bootstraps from a seed node's onion address.
func runAddNode(args []string) {
fs := flag.NewFlagSet("add-node", flag.ExitOnError)
socketPath := fs.String("socket", "", "daemon socket path")
addr := fs.String("addr", "", "daemon TCP address")
authKey := fs.String("auth-key", "", "path to Ed25519 seed file for authentication")
useTLS := fs.Bool("tls", false, "wrap the connection in TLS (use for HTTPS ingress)")
tlsInsecure := fs.Bool("tls-insecure", false, "use TLS but skip certificate verification")
timeout := fs.Duration("timeout", 180*time.Second, "RPC deadline for the bootstrap call (cold-start Tor circuits often need 60-120s: bootstrap + circuit + HSDir lookup + introduce + dial; bump if your daemon was just started)")
fs.Parse(args)
if fs.NArg() < 1 {
fmt.Fprintf(os.Stderr, "usage: ensemble add-node [flags] <onion-address>\n")
os.Exit(1)
}
onionAddr := fs.Arg(0)
var target string
switch {
case *addr != "":
target = *addr
case *socketPath != "":
target = "unix://" + *socketPath
default:
home, _ := os.UserHomeDir()
target = "unix://" + filepath.Join(home, ".ensemble", "ensemble.sock")
}
var privKey ed25519.PrivateKey
if *authKey != "" {
var err error
privKey, err = loadAuthKey(*authKey)
if err != nil {
fmt.Fprintf(os.Stderr, "loading auth key: %v\n", err)
os.Exit(1)
}
}
backend, err := ui.NewGRPCBackend(target, privKey, grpcTLSOptions(*useTLS, *tlsInsecure)...)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to connect: %v\n", err)
os.Exit(1)
}
defer backend.Close()
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
defer cancel()
n, err := backend.AddNode(ctx, onionAddr)
if err != nil {
fmt.Fprintf(os.Stderr, "AddNode failed: %v\n", err)
os.Exit(1)
}
fmt.Printf("Bootstrap complete: %d peers discovered\n", n)
}
// grpcTLSOptions converts the --tls / --tls-insecure flags into GRPCBackend options.
func grpcTLSOptions(useTLS, tlsInsecure bool) []ui.GRPCOption {
switch {
case tlsInsecure:
return []ui.GRPCOption{ui.WithTLSInsecureSkipVerify()}
case useTLS:
return []ui.GRPCOption{ui.WithTLS()}
default:
return nil
}
}
// loadAuthKey reads a 32-byte Ed25519 seed file and returns the private key.
func loadAuthKey(path string) (ed25519.PrivateKey, error) {
seed, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("reading %s: %w", path, err)
}
if len(seed) != ed25519.SeedSize {
return nil, fmt.Errorf("invalid seed file: got %d bytes, want %d", len(seed), ed25519.SeedSize)
}
return ed25519.NewKeyFromSeed(seed), nil
}