-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
602 lines (501 loc) · 16.3 KB
/
main.go
File metadata and controls
602 lines (501 loc) · 16.3 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
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"net/http"
"os"
"os/signal"
"regexp"
"runtime"
"strings"
"syscall"
"time"
"mu/admin"
"mu/agent"
"mu/ai"
"mu/api"
"mu/app"
"mu/auth"
"mu/blog"
"mu/chat"
"mu/data"
"mu/docs"
"mu/home"
"mu/mail"
"mu/markets"
"mu/news"
"mu/places"
"mu/reminder"
"mu/search"
"mu/user"
"mu/video"
"mu/wallet"
"mu/weather"
)
var EnvFlag = flag.String("env", "dev", "Set the environment")
var ServeFlag = flag.Bool("serve", false, "Run the server")
var AddressFlag = flag.String("address", ":8080", "Address for server")
func main() {
flag.Parse()
if !*ServeFlag {
fmt.Errorf("--serve not set")
return
}
// render the api markdwon
md := api.Markdown()
apiDoc := app.Render([]byte(md))
apiHTML := app.RenderHTML("API", "API documentation", string(apiDoc))
// load the data index
data.Load()
// load admin/flags
admin.Load()
// load the chat
chat.Load()
// load the news
news.Load()
// load the videos
video.Load()
// load the blog
blog.Load()
// load the mail (also configures SMTP and DKIM)
mail.Load()
// load places
places.Load()
// load weather
weather.Load()
// load markets and reminder
markets.Load()
reminder.Load()
wallet.Load()
// load the home cards
home.Load()
// load agent
agent.Load()
// load user presence tracking
user.Load()
// Enable indexing after all content is loaded
// This allows the priority queue to process new items first
data.StartIndexing()
// Wire MCP quota checking using wallet credit system
api.QuotaCheck = func(r *http.Request, op string) (bool, int, error) {
sess, err := auth.GetSession(r)
if err != nil {
return false, 0, fmt.Errorf("authentication required")
}
canProceed, _, cost, err := wallet.CheckQuota(sess.Account, op)
return canProceed, cost, err
}
// Wire agent quota checking (same wallet credit system)
agent.QuotaCheck = func(r *http.Request, op string) (bool, int, error) {
sess, err := auth.GetSession(r)
if err != nil {
return false, 0, fmt.Errorf("authentication required")
}
canProceed, _, cost, err := wallet.CheckQuota(sess.Account, op)
return canProceed, cost, err
}
// Register MCP auth tools
usernameRegex := regexp.MustCompile(`^[a-z][a-z0-9_]{3,23}$`)
api.RegisterTool(api.Tool{
Name: "signup",
Description: "Create a new account and return a session token",
Params: []api.ToolParam{
{Name: "id", Type: "string", Description: "Username (4-24 chars, lowercase, starts with letter)", Required: true},
{Name: "secret", Type: "string", Description: "Password (minimum 6 characters)", Required: true},
{Name: "name", Type: "string", Description: "Display name (optional, defaults to username)", Required: false},
},
Handle: func(args map[string]any) (string, error) {
id, _ := args["id"].(string)
secret, _ := args["secret"].(string)
name, _ := args["name"].(string)
if id == "" {
return `{"error":"username is required"}`, fmt.Errorf("username is required")
}
if !usernameRegex.MatchString(id) {
return `{"error":"invalid username format"}`, fmt.Errorf("invalid username format")
}
if len(secret) < 6 {
return `{"error":"password must be at least 6 characters"}`, fmt.Errorf("password too short")
}
if name == "" {
name = id
}
if err := auth.Create(&auth.Account{
ID: id,
Secret: secret,
Name: name,
Created: time.Now(),
}); err != nil {
resp, _ := json.Marshal(map[string]string{"error": err.Error()})
return string(resp), err
}
sess, err := auth.Login(id, secret)
if err != nil {
return `{"error":"account created but login failed"}`, err
}
resp, _ := json.Marshal(map[string]string{
"token": sess.Token,
"account": sess.Account,
})
return string(resp), nil
},
})
api.RegisterTool(api.Tool{
Name: "login",
Description: "Log in and return a session token for use in Authorization header",
Params: []api.ToolParam{
{Name: "id", Type: "string", Description: "Username", Required: true},
{Name: "secret", Type: "string", Description: "Password", Required: true},
},
Handle: func(args map[string]any) (string, error) {
id, _ := args["id"].(string)
secret, _ := args["secret"].(string)
if id == "" || secret == "" {
return `{"error":"username and password are required"}`, fmt.Errorf("missing credentials")
}
sess, err := auth.Login(id, secret)
if err != nil {
return `{"error":"invalid username or password"}`, err
}
resp, _ := json.Marshal(map[string]string{
"token": sess.Token,
"account": sess.Account,
})
return string(resp), nil
},
})
api.RegisterTool(api.Tool{
Name: "web_search",
Description: "Search the web for current information and news",
Params: []api.ToolParam{
{Name: "query", Type: "string", Description: "Search query", Required: true},
},
Handle: func(args map[string]any) (string, error) {
query, _ := args["query"].(string)
if query == "" {
return `{"error":"query is required"}`, fmt.Errorf("query is required")
}
results, err := ai.WebSearch(query)
if err != nil {
return `{"error":"search failed"}`, err
}
type searchResult struct {
Title string `json:"title"`
URL string `json:"url"`
Snippet string `json:"snippet"`
}
var items []searchResult
for _, r := range results {
items = append(items, searchResult{Title: r.Title, URL: r.URL, Snippet: r.Snippet})
}
resp, _ := json.Marshal(map[string]interface{}{"results": items, "query": query})
return string(resp), nil
},
})
authenticated := map[string]bool{
"/video": false, // Public viewing, auth for interactive features
"/news": false, // Public viewing, auth for search
"/chat": false, // Public viewing, auth for chatting
"/home": false, // Public viewing
"/blog": false, // Public viewing, auth for posting
"/markets": false, // Public viewing
"/reminder": false, // Public viewing
"/places": false, // Public map, auth for search
"/weather": false, // Public page, auth for forecast lookup
"/mail": true, // Require auth for inbox
"/logout": true,
"/account": true,
"/token": true, // PAT token management
"/passkey": false, // Passkey login/register (auth checked in handler)
"/session": false, // Public - used to check auth status
"/api": false, // Public - API documentation
"/flag": true,
"/admin": true,
"/admin/users": true,
"/admin/moderate": true,
"/admin/blocklist": true,
"/admin/email": true,
"/admin/api": true,
"/admin/log": true,
"/admin/env": true,
"/plans": false, // Public - shows pricing options
"/donate": false,
"/wallet": false, // Public - shows wallet info; auth checked in handler
"/search": false, // Public - local data index search
"/web": false, // Public page, auth checked in handler (paid Brave web search)
"/status": false, // Public - server health status
"/docs": false, // Public - documentation
"/about": false, // Public - about page
"/mcp": false, // Public - MCP tools page
"/agent": false, // Public page, auth checked in handler
}
// Static assets should not require authentication
staticPaths := []string{
".css", ".js", ".png", ".jpg", ".jpeg", ".gif", ".svg",
".ico", ".webmanifest", ".json",
}
// serve video
http.HandleFunc("/video", video.Handler)
// serve news
http.HandleFunc("/news", news.Handler)
// serve chat
http.HandleFunc("/chat", chat.Handler)
// serve blog (full list)
http.HandleFunc("/blog", blog.Handler)
// serve individual blog post (public, no auth)
// Serves ActivityPub JSON-LD when requested via Accept header
http.HandleFunc("/post", func(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" && blog.WantsActivityPub(r) {
blog.PostObjectHandler(w, r)
return
}
blog.PostHandler(w, r)
})
// handle comments on posts /post/{id}/comment
http.HandleFunc("/post/", blog.CommentHandler)
// flag content
http.HandleFunc("/flag", admin.FlagHandler)
// admin dashboard
http.HandleFunc("/admin", admin.AdminHandler)
// admin user management
http.HandleFunc("/admin/users", admin.UsersHandler)
// moderation queue
http.HandleFunc("/admin/moderate", admin.ModerateHandler)
// mail blocklist management
http.HandleFunc("/admin/blocklist", admin.BlocklistHandler)
// email log
http.HandleFunc("/admin/email", admin.EmailLogHandler)
// external API call log
http.HandleFunc("/admin/api", admin.APILogHandler)
// system log
http.HandleFunc("/admin/log", admin.SysLogHandler)
// environment variables status
http.HandleFunc("/admin/env", admin.EnvHandler)
// plans page (public - overview of options)
http.HandleFunc("/plans", app.Plans)
// donate page (public - handles GoCardless redirects)
http.HandleFunc("/donate", app.Donate)
// wallet - credits and payments
http.HandleFunc("/wallet", wallet.Handler)
http.HandleFunc("/wallet/", wallet.Handler) // Handle sub-routes like /wallet/topup
// serve search page (local + Brave web search)
http.HandleFunc("/search", search.Handler)
// serve web search page (Brave-powered, paid)
http.HandleFunc("/web", search.WebHandler)
// serve the home screen
http.HandleFunc("/home", home.Handler)
// serve the agent
http.HandleFunc("/agent", agent.Handler)
http.HandleFunc("/agent/", agent.Handler) // Handle sub-routes like /agent/flow/...
// serve mail inbox
http.HandleFunc("/mail", mail.Handler)
// serve markets page
http.HandleFunc("/markets", markets.Handler)
// serve reminder page
http.HandleFunc("/reminder", reminder.Handler)
// serve places page
http.HandleFunc("/places", places.Handler)
http.HandleFunc("/places/", places.Handler)
// serve weather page
http.HandleFunc("/weather", weather.Handler)
// auth
http.HandleFunc("/login", app.Login)
http.HandleFunc("/logout", app.Logout)
http.HandleFunc("/signup", app.Signup)
http.HandleFunc("/account", app.Account)
http.HandleFunc("/session", app.Session)
http.HandleFunc("/token", app.TokenHandler)
http.HandleFunc("/passkey/", app.PasskeyHandler)
// status page - public health check
app.DKIMStatusFunc = mail.DKIMStatus
http.HandleFunc("/status", app.StatusHandler)
// documentation
http.HandleFunc("/docs", docs.Handler)
http.HandleFunc("/docs/", docs.Handler)
http.HandleFunc("/about", docs.AboutHandler)
// ActivityPub: WebFinger discovery
http.HandleFunc("/.well-known/webfinger", blog.WebFingerHandler)
// presence WebSocket endpoint
http.HandleFunc("/presence", user.PresenceHandler)
// presence ping endpoint
http.HandleFunc("/ping", func(w http.ResponseWriter, r *http.Request) {
_, acc, err := auth.RequireSession(r)
if err != nil {
app.Unauthorized(w, r)
return
}
auth.UpdatePresence(acc.ID)
w.Header().Set("Content-Type", "application/json")
onlineCount := auth.GetOnlineCount()
w.Write([]byte(fmt.Sprintf(`{"status":"ok","online":%d}`, onlineCount)))
})
// serve the api doc
http.Handle("/api", app.ServeHTML(apiHTML))
// serve the MCP page and server (GET = HTML page, POST = JSON-RPC)
http.HandleFunc("/mcp", api.MCPHandler)
// serve the app
http.Handle("/", app.Serve())
// Create server with handler
server := &http.Server{
Addr: *AddressFlag,
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Request logging (Apache-style)
start := time.Now()
defer func() {
// Skip logging for static assets and frequent endpoints
if !strings.HasSuffix(r.URL.Path, ".css") &&
!strings.HasSuffix(r.URL.Path, ".js") &&
!strings.HasSuffix(r.URL.Path, ".png") &&
!strings.HasSuffix(r.URL.Path, ".ico") &&
!strings.HasPrefix(r.URL.Path, "/chat/ws") {
app.Log("http", "%s %s %s %v", r.Method, r.URL.Path, r.RemoteAddr, time.Since(start))
}
}()
if *EnvFlag == "dev" {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
w.Header().Set("Access-Control-Allow-Credentials", "true")
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
}
if v := len(r.URL.Path); v > 1 && strings.HasSuffix(r.URL.Path, "/") {
r.URL.Path = r.URL.Path[:v-1]
}
// Fast path for static assets - skip all middleware
for _, ext := range staticPaths {
if strings.HasSuffix(r.URL.Path, ext) {
http.DefaultServeMux.ServeHTTP(w, r)
return
}
}
var token string
// set via session cookie
if c, err := r.Cookie("session"); err == nil && c != nil {
token = c.Value
}
// Try Authorization header (Bearer token or PAT)
if token == "" {
authHeader := r.Header.Get("Authorization")
if authHeader != "" {
// Support both "Bearer <token>" and just "<token>"
if len(authHeader) > 7 && authHeader[:7] == "Bearer " {
token = authHeader[7:]
} else {
token = authHeader
}
}
}
// Try X-Micro-Token header (legacy support)
if token == "" {
token = r.Header.Get("X-Micro-Token")
}
// Check if static asset - skip authentication entirely
isStaticAsset := false
for _, ext := range staticPaths {
if strings.HasSuffix(r.URL.Path, ext) {
isStaticAsset = true
break
}
}
// Skip auth check for static assets
if !isStaticAsset {
var isAuthed bool
// Special case: /post should be public, not confused with /blog
if strings.HasPrefix(r.URL.Path, "/post") && !strings.HasPrefix(r.URL.Path, "/blog") {
isAuthed = false
} else {
// Check if path requires authentication
for url, authed := range authenticated {
if strings.HasPrefix(r.URL.Path, url) {
isAuthed = authed
break
}
}
}
// check token
if isAuthed {
// deny access if invalid
if err := auth.ValidateToken(token); err != nil {
http.Redirect(w, r, "/", 302)
return
}
} else if r.URL.Path == "/" {
if err := auth.ValidateToken(token); err == nil {
http.Redirect(w, r, "/home", 302)
return
}
// Serve dynamic landing page for unauthenticated users
home.LandingHandler(w, r)
return
}
}
// Check if this is a user profile request (/@username)
if strings.HasPrefix(r.URL.Path, "/@") {
rest := r.URL.Path[2:]
// Handle ActivityPub sub-endpoints: /@username/outbox, /@username/inbox
if strings.HasSuffix(rest, "/outbox") {
blog.OutboxHandler(w, r)
return
}
if strings.HasSuffix(rest, "/inbox") {
blog.InboxHandler(w, r)
return
}
// Serve ActivityPub actor JSON if requested
if !strings.Contains(rest, "/") && blog.WantsActivityPub(r) {
blog.ActorHandler(w, r)
return
}
// Otherwise serve the HTML profile page
if !strings.Contains(rest, "/") {
user.Handler(w, r)
return
}
}
http.DefaultServeMux.ServeHTTP(w, r)
}),
}
// Channel to listen for interrupt signals
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
// Start SMTP server if enabled (disabled by default)
mail.StartSMTPServerIfEnabled()
// Log initial memory usage
var m runtime.MemStats
runtime.ReadMemStats(&m)
app.Log("main", "Startup complete. Memory: Alloc=%dMB Sys=%dMB NumGC=%d", m.Alloc/1024/1024, m.Sys/1024/1024, m.NumGC)
// Start memory monitoring goroutine
go func() {
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
for range ticker.C {
var m runtime.MemStats
runtime.ReadMemStats(&m)
app.Log("main", "Memory: Alloc=%dMB Sys=%dMB NumGC=%d Goroutines=%d",
m.Alloc/1024/1024, m.Sys/1024/1024, m.NumGC, runtime.NumGoroutine())
}
}()
// Start server in a goroutine
go func() {
app.Log("main", "Starting server on %s", *AddressFlag)
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
app.Log("main", "Server error: %v", err)
}
}()
// Wait for interrupt signal
<-quit
app.Log("main", "Shutting down server...")
// Create shutdown context with timeout
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// Attempt graceful shutdown
if err := server.Shutdown(ctx); err != nil {
app.Log("main", "Server forced to shutdown: %v", err)
}
app.Log("main", "Server stopped")
}