summaryrefslogtreecommitdiff
path: root/cmd/dashboard/main.go
blob: b38b9e19b31fca4f6e922f8dcba6596486559382 (plain)
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
package main

import (
	"context"
	"html/template"
	"log"
	"net/http"
	"os"
	"os/signal"
	"path/filepath"
	"syscall"
	"time"

	"github.com/alexedwards/scs/sqlite3store"
	"github.com/alexedwards/scs/v2"
	"github.com/go-chi/chi/v5"
	"github.com/go-chi/chi/v5/middleware"
	"github.com/joho/godotenv"

	"task-dashboard/internal/api"
	"task-dashboard/internal/auth"
	"task-dashboard/internal/config"
	"task-dashboard/internal/handlers"
	appmiddleware "task-dashboard/internal/middleware"
	"task-dashboard/internal/store"

	"github.com/go-webauthn/webauthn/webauthn"
)

// Set via -ldflags at build time
var (
	buildCommit = "dev"
	buildTime   = "unknown"
)

func main() {
	log.Printf("task-dashboard build=%s time=%s", buildCommit, buildTime)
	// Load .env file (ignore error if file doesn't exist - env vars might be set directly)
	_ = godotenv.Load()

	// Load configuration
	cfg, err := config.Load()
	if err != nil {
		log.Fatalf("Failed to load configuration: %v", err)
	}

	// Set display timezone (must be done early, before any time operations)
	config.SetDisplayTimezone(cfg.Timezone)
	log.Printf("Display timezone set to: %s", cfg.Timezone)

	// Initialize database
	db, err := store.New(cfg.DatabasePath, cfg.MigrationDir)
	if err != nil {
		log.Fatalf("Failed to initialize database: %v", err)
	}
	defer func() { _ = db.Close() }()

	// Initialize session manager
	sessionManager := scs.New()
	sessionManager.Store = sqlite3store.New(db.DB())
	sessionManager.Lifetime = config.SessionLifetime
	sessionManager.IdleTimeout = 24 * time.Hour // Extend session on activity
	sessionManager.Cookie.Persist = true
	sessionManager.Cookie.Secure = !cfg.Debug
	sessionManager.Cookie.SameSite = http.SameSiteLaxMode
	sessionManager.Cookie.Name = "session" // Standard name for better compatibility

	// Initialize auth service
	authService := auth.NewService(db.DB())

	// Ensure default admin user exists (use env vars for credentials)
	defaultUser := os.Getenv("DEFAULT_USER")
	defaultPass := os.Getenv("DEFAULT_PASS")
	if defaultUser == "" {
		defaultUser = "admin"
	}
	if defaultPass == "" {
		log.Fatal("CRITICAL: DEFAULT_PASS environment variable must be set. Cannot start without a password.")
	}
	if err := authService.EnsureDefaultUser(defaultUser, defaultPass); err != nil {
		log.Printf("Warning: failed to ensure default user: %v", err)
	}

	// Parse templates for auth handlers
	authTemplates, err := template.ParseGlob(filepath.Join(cfg.TemplateDir, "*.html"))
	if err != nil {
		log.Printf("Warning: failed to parse auth templates: %v", err)
	}

	// Initialize WebAuthn (optional - only if configured)
	var wa *webauthn.WebAuthn
	if cfg.WebAuthnRPID != "" && cfg.WebAuthnOrigin != "" {
		var err error
		wa, err = webauthn.New(&webauthn.Config{
			RPDisplayName: "Task Dashboard",
			RPID:          cfg.WebAuthnRPID,
			RPOrigins:     []string{cfg.WebAuthnOrigin},
		})
		if err != nil {
			log.Fatalf("Failed to initialize WebAuthn: %v", err)
		}
		log.Printf("WebAuthn initialized (RP ID: %s, Origin: %s)", cfg.WebAuthnRPID, cfg.WebAuthnOrigin)
	}

	// Initialize auth handlers
	authHandlers := auth.NewHandlers(authService, sessionManager, authTemplates, wa)

	// Initialize API clients
	trelloClient := api.NewTrelloClient(cfg.TrelloAPIKey, cfg.TrelloToken)

	var planToEatClient api.PlanToEatAPI
	if cfg.HasPlanToEat() {
		pteClient := api.NewPlanToEatClient(cfg.PlanToEatAPIKey)
		if cfg.PlanToEatSession != "" {
			pteClient.SetSessionCookie(cfg.PlanToEatSession)
		}
		planToEatClient = pteClient
	}

	var googleCalendarClient api.GoogleCalendarAPI
	if cfg.HasGoogleCalendar() {
		// Use timeout context to prevent startup hangs if credentials file is unreachable
		initCtx, cancel := context.WithTimeout(context.Background(), config.GoogleCalendarInitTimeout)
		var err error
		googleCalendarClient, err = api.NewGoogleCalendarClient(initCtx, cfg.GoogleCredentialsFile, cfg.GoogleCalendarID, cfg.Timezone)
		cancel()
		if err != nil {
			log.Printf("Warning: failed to initialize Google Calendar client: %v", err)
		} else {
			log.Printf("Google Calendar client initialized for calendars: %s (timezone: %s)", cfg.GoogleCalendarID, cfg.Timezone)
		}
	}

	var googleTasksClient api.GoogleTasksAPI
	if cfg.HasGoogleTasks() {
		initCtx, cancel := context.WithTimeout(context.Background(), config.GoogleCalendarInitTimeout)
		var err error
		googleTasksClient, err = api.NewGoogleTasksClient(initCtx, cfg.GoogleCredentialsFile, cfg.GoogleTasksListID, cfg.Timezone)
		cancel()
		if err != nil {
			log.Printf("Warning: failed to initialize Google Tasks client: %v", err)
		} else {
			log.Printf("Google Tasks client initialized for list: %s", cfg.GoogleTasksListID)
		}
	}

	var claudomatorClient api.ClaudomatorClient
	if cfg.ClaudomatorURL != "" {
		claudomatorClient = api.NewClaudomatorClient(cfg.ClaudomatorURL)
	}

	// Initialize handlers
	h := handlers.New(db, trelloClient, planToEatClient, googleCalendarClient, googleTasksClient, claudomatorClient, cfg, buildCommit, wa != nil)

	// Set up router
	r := chi.NewRouter()

	// Global middleware
	r.Use(middleware.Logger)
	r.Use(middleware.Recoverer)
	r.Use(middleware.Timeout(config.RequestTimeout))
	r.Use(appmiddleware.SecurityHeaders(cfg.Debug)) // Security headers
	r.Use(sessionManager.LoadAndSave) // Session middleware must be applied globally

	// Service gateway — upstream services proxied through doot's auth + SSL layer.
	// Each mount registers a path prefix, upstream URL, and any public webhook paths.
	type serviceMount struct {
		name         string
		upstream     string
		prefix       string
		webhookPaths []string // POST-only paths that bypass session auth (e.g. HMAC-signed webhooks)
		publicPaths  []string // all-method paths that bypass session auth (protected by service-level bearer token)
	}
	mounts := []serviceMount{
		{
			name:         "claudomator",
			upstream:     cfg.ClaudomatorURL,
			prefix:       "/claudomator",
			webhookPaths: []string{"/claudomator/api/webhooks/github"},
			publicPaths:  []string{"/claudomator/chatbot/mcp"},
		},
	}
	if cfg.PlaygroundURL != "" {
		mounts = append(mounts, serviceMount{
			name:     "playground",
			upstream: cfg.PlaygroundURL,
			prefix:   "/playground",
		})
	}
	if cfg.ScoutURL != "" {
		mounts = append(mounts, serviceMount{
			name:     "scout",
			upstream: cfg.ScoutURL,
			prefix:   "/scout",
		})
	}
	if cfg.HawaiiURL != "" {
		mounts = append(mounts, serviceMount{
			name:     "hawaii",
			upstream: cfg.HawaiiURL,
			prefix:   "/hawaii",
		})
	}

	// Rate limiter for auth endpoints
	authRateLimiter := appmiddleware.NewRateLimiter(config.AuthRateLimitRequests, config.AuthRateLimitWindow)

	// Rate limiter for agent auth (stricter - 10 requests/minute per IP)
	agentAuthRateLimiter := appmiddleware.NewRateLimiter(10, time.Minute)

	// Health check (no auth)
	r.Get("/health", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/plain")
		w.WriteHeader(http.StatusOK)
		_, _ = w.Write([]byte("ok"))
	})

	// Public routes (no auth required)
	r.Get("/login", authHandlers.HandleLoginPage)
	r.With(authRateLimiter.Limit).Post("/login", authHandlers.HandleLogin)
	r.Post("/logout", authHandlers.HandleLogout)

	// WebAuthn public routes (rate-limited)
	r.With(authRateLimiter.Limit).Post("/passkeys/login/begin", authHandlers.HandlePasskeyLoginBegin)
	r.With(authRateLimiter.Limit).Post("/passkeys/login/finish", authHandlers.HandlePasskeyLoginFinish)

	// Serve static files (public)
	fileServer := http.FileServer(http.Dir(cfg.StaticDir))
	r.Handle("/static/*", http.StripPrefix("/static/", fileServer))

	// Conditions page (public - no auth required)
	r.Get("/conditions", h.HandleConditionsPage)

	// Agent API
	r.Route("/agent", func(r chi.Router) {
		// Public endpoints (no browser auth, but rate limited)
		r.With(agentAuthRateLimiter.Limit).Post("/auth/request", h.HandleAgentAuthRequest)
		r.Get("/auth/poll", h.HandleAgentAuthPoll)

		// Browser auth required for approve/deny
		r.Group(func(r chi.Router) {
			r.Use(authHandlers.Middleware().RequireAuth)
			r.Post("/auth/approve", h.HandleAgentAuthApprove)
			r.Post("/auth/deny", h.HandleAgentAuthDeny)
		})

		// Agent session required for context and write operations
		r.Group(func(r chi.Router) {
			r.Use(h.AgentAuthMiddleware)
			r.Get("/context", h.HandleAgentContext)

			// Write Operations
			r.Post("/tasks/{id}/complete", h.HandleAgentTaskComplete)
			r.Post("/tasks/{id}/uncomplete", h.HandleAgentTaskUncomplete)
			r.Patch("/tasks/{id}/due", h.HandleAgentTaskUpdateDue)
			r.Patch("/tasks/{id}", h.HandleAgentTaskUpdate)

			// Create Operations
			r.Post("/tasks", h.HandleAgentTaskCreate)
			r.Post("/shopping", h.HandleAgentShoppingAdd)
		})

		// HTML endpoints for browser-only agents (GET requests only)
		r.Route("/web", func(r chi.Router) {
			r.With(agentAuthRateLimiter.Limit).Get("/request", h.HandleAgentWebRequest)
			r.Get("/status", h.HandleAgentWebStatus)
			r.Get("/context", h.HandleAgentWebContext)
		})
	})

	// Register service gateway mounts — each upstream proxied behind doot's auth layer.
	for _, m := range mounts {
		proxy := handlers.NewServiceProxy(m.upstream, cfg.WebAuthnOrigin, m.prefix)

		// Bare prefix → redirect to prefix/
		prefix := m.prefix
		r.Get(prefix, func(w http.ResponseWriter, r *http.Request) {
			http.Redirect(w, r, prefix+"/", http.StatusMovedPermanently)
		})

		// Public webhook paths bypass session auth (rely on service-level HMAC/token)
		for _, wp := range m.webhookPaths {
			r.Post(wp, proxy.ServeHTTP)
		}
		// Public all-method paths bypass session auth (rely on service-level bearer token)
		for _, pp := range m.publicPaths {
			r.Handle(pp, http.HandlerFunc(proxy.ServeHTTP))
		}

		// All other routes require auth + origin check (CSRF protection for proxy)
		r.Group(func(r chi.Router) {
			r.Use(authHandlers.Middleware().RequireAuth)
			r.Use(auth.OriginCheck(cfg.WebAuthnOrigin))
			r.Handle(prefix+"/*", proxy)
		})
	}


	// Protected routes (auth required)
	r.Group(func(r chi.Router) {
		r.Use(authHandlers.Middleware().CSRFProtect)
		r.Use(authHandlers.Middleware().RequireAuth)

		// Dashboard
		r.Get("/", h.HandleDashboard)
		r.Post("/api/refresh", h.HandleRefresh)
		r.Get("/api/meals", h.HandleGetMeals)
		r.Get("/api/boards", h.HandleGetBoards)
		r.Get("/api/shopping", h.HandleGetShoppingList)

		// Tab routes for HTMX
		r.Get("/tabs/tasks", h.HandleTabTasks)
		r.Get("/tabs/planning", h.HandleTabPlanning)
		r.Get("/tabs/meals", h.HandleTabMeals)
		r.Get("/tabs/timeline", h.HandleTimeline)
		r.Get("/tabs/shopping", h.HandleTabShopping)
		r.Get("/tabs/conditions", h.HandleTabConditions)

		// Trello card operations
		r.Post("/cards", h.HandleCreateCard)
		r.Post("/cards/complete", h.HandleCompleteCard)

		// Unified task completion (for Tasks tab Atoms)
		r.Post("/complete-atom", h.HandleCompleteAtom)
		r.Post("/uncomplete-atom", h.HandleUncompleteAtom)

		// Unified Quick Add (for Tasks tab)
		r.Post("/unified-add", h.HandleUnifiedAdd)
		r.Get("/partials/lists", h.HandleGetListsOptions)
		r.Get("/partials/shopping-lists", h.HandleGetShoppingLists)

		// Task detail/edit
		r.Get("/tasks/detail", h.HandleGetTaskDetail)
		r.Get("/task", h.HandleTaskDetailPage)
		r.Post("/tasks/update", h.HandleUpdateTask)

		// Shopping quick-add
		r.Post("/shopping/add", h.HandleShoppingQuickAdd)
		r.Post("/shopping/toggle", h.HandleShoppingToggle)

		// Shopping mode (focused single-store view)
		r.Get("/shopping/mode/{store}", h.HandleShoppingMode)
		r.Post("/shopping/mode/{store}/toggle", h.HandleShoppingModeToggle)
		r.Post("/shopping/mode/{store}/complete", h.HandleShoppingModeComplete)

		// Passkey management (WebAuthn)
		r.Get("/settings/passkeys", authHandlers.HandleListPasskeys)
		r.Post("/passkeys/register/begin", authHandlers.HandlePasskeyRegisterBegin)
		r.Post("/passkeys/register/finish", authHandlers.HandlePasskeyRegisterFinish)
		r.Delete("/passkeys/{id}", authHandlers.HandleDeletePasskey)

		// Settings
		r.Get("/settings", h.HandleSettingsPage)
		r.Post("/settings/sync", h.HandleSyncSources)
		r.Post("/settings/clear-cache", h.HandleClearCache)
		r.Post("/settings/toggle", h.HandleToggleSourceConfig)
		r.Post("/settings/features", h.HandleCreateFeature)
		r.Post("/settings/features/toggle", h.HandleToggleFeature)
		r.Delete("/settings/features/{name}", h.HandleDeleteFeature)
		r.Delete("/settings/agents/{id}", h.HandleDeleteAgent)

		// WebSocket for notifications
		r.Get("/ws/notifications", h.HandleWebSocket)
	})

	// Widget API — bearer token auth, no session required
	if cfg.WidgetToken != "" {
		widgetAuth := func(next http.Handler) http.Handler {
			return handlers.WidgetAuthMiddleware(cfg.WidgetToken, next)
		}
		r.With(widgetAuth).Get("/api/widget", h.HandleWidgetGet)
		r.With(widgetAuth).Post("/api/widget/complete", h.HandleWidgetComplete)
		r.With(widgetAuth).Post("/api/widget/reschedule", h.HandleWidgetReschedule)
	} else {
		log.Println("WIDGET_TOKEN not set — /api/widget disabled")
	}

	// Start server
	addr := ":" + cfg.Port
	srv := &http.Server{
		Addr:         addr,
		Handler:      r,
		ReadTimeout:  15 * time.Second,
		WriteTimeout: 15 * time.Second,
		IdleTimeout:  60 * time.Second,
	}

	// Graceful shutdown
	go func() {
		log.Printf("Starting server on http://localhost%s", addr)
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("Server failed: %v", err)
		}
	}()

	// Wait for interrupt signal
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit

	log.Println("Shutting down server...")

	// Graceful shutdown with timeout
	ctx, cancel := context.WithTimeout(context.Background(), config.GracefulShutdownTimeout)
	defer cancel()

	if err := srv.Shutdown(ctx); err != nil {
		log.Fatalf("Server forced to shutdown: %v", err)
	}

	log.Println("Server exited")
}