Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
2359 lines (2106 loc) · 75.8 KB
/
Copy pathmain.go
File metadata and controls
2359 lines (2106 loc) · 75.8 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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"context"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"database/sql"
"embed"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"html/template"
"io/fs"
"log/slog"
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/google/go-github/v60/github"
"github.com/lib/pq"
"golang.org/x/oauth2"
githuboauth "golang.org/x/oauth2/github"
)
// Configure OAuth
var sessionSecret []byte
// sessionTTL bounds how long a signed session cookie stays valid. The expiry is
// part of the signed payload, so a stolen cookie cannot outlive it even though
// sessions are stateless.
const sessionTTL = 24 * time.Hour
// signCookie signs "<value>|<expiryUnix>" so that verification is
// self-contained: tampering breaks the MAC and replay stops at the expiry.
func signCookie(value string) string {
return signCookieAt(value, time.Now().Add(sessionTTL))
}
func signCookieAt(value string, expiry time.Time) string {
payload := value + "|" + strconv.FormatInt(expiry.Unix(), 10)
mac := hmac.New(sha256.New, sessionSecret)
mac.Write([]byte(payload))
signature := hex.EncodeToString(mac.Sum(nil))
encoded := base64.URLEncoding.EncodeToString([]byte(payload))
return encoded + "." + signature
}
func verifyCookie(signed string) (string, bool) {
parts := strings.SplitN(signed, ".", 2)
if len(parts) != 2 {
return "", false
}
decoded, err := base64.URLEncoding.DecodeString(parts[0])
if err != nil {
return "", false
}
mac := hmac.New(sha256.New, sessionSecret)
mac.Write(decoded)
expected := hex.EncodeToString(mac.Sum(nil))
if !hmac.Equal([]byte(parts[1]), []byte(expected)) {
return "", false
}
payload := string(decoded)
sep := strings.LastIndex(payload, "|")
if sep < 0 {
// Unversioned cookie issued before expiries were signed in.
return "", false
}
expiryUnix, err := strconv.ParseInt(payload[sep+1:], 10, 64)
if err != nil {
return "", false
}
if time.Now().Unix() >= expiryUnix {
return "", false
}
return payload[:sep], true
}
func getSessionEmail(r *http.Request) string {
cookie, err := r.Cookie("session")
if err != nil {
return ""
}
email, ok := verifyCookie(cookie.Value)
if !ok {
return ""
}
return email
}
var oauthConfig = &oauth2.Config{
ClientID: os.Getenv("GITHUB_CLIENT_ID"),
ClientSecret: os.Getenv("GITHUB_CLIENT_SECRET"),
Scopes: []string{"public_repo", "user:email"},
Endpoint: githuboauth.Endpoint,
}
//go:embed templates/*
var templateFS embed.FS
//go:embed static/*
var staticFS embed.FS
// assetVersion fingerprints the bundled stylesheet so a redeploy invalidates
// the browser cache without anyone remembering to bump a number.
var assetVersion = fingerprintAssets()
func fingerprintAssets() string {
css, err := staticFS.ReadFile("static/app.css")
if err != nil {
return "dev"
}
sum := sha256.Sum256(css)
return hex.EncodeToString(sum[:])[:12]
}
//go:embed schema.sql
var schemaSQL string
//go:embed data/technologies.json
var technologiesJSON []byte
var (
prodTmpl *template.Template
db *sql.DB
)
// seriesPalette is the categorical ramp used for language bars and dots. It
// matches --series-N in static/app.css; keep the two in step.
var seriesPalette = []template.CSS{"#7c3aed", "#2f4bff", "#0891b2", "#0e9f6e", "#c2660a", "#e5484d", "#64748b"}
var templateFuncs = template.FuncMap{
"series": func(i int) template.CSS { return seriesPalette[i%len(seriesPalette)] },
"add": func(a, b int) int { return a + b },
"sub": func(a, b int) int { return a - b },
"limitTokens": func(tokens []string, limit int) []string {
if len(tokens) <= limit {
return tokens
}
return tokens[:limit]
},
"hasMoreTokens": func(tokens []string, limit int) bool {
return len(tokens) > limit
},
"moreTokenCount": func(tokens []string, limit int) int {
if len(tokens) <= limit {
return 0
}
return len(tokens) - limit
},
// asset builds a cache-busted URL for a file under static/.
"asset": func(name string) string { return "/static/" + name + "?v=" + assetVersion },
// pctOf renders a's share of a+b as a CSS percentage, used by the diff
// ribbon. Returns 0 when there is nothing to divide.
"pctOf": func(a, b int) string {
total := a + b
if total <= 0 {
return "0"
}
return strconv.FormatFloat(float64(a)*100/float64(total), 'f', 2, 64)
},
// dec1 renders a float with a single decimal, for chart geometry that goes
// straight into an attribute.
"dec1": func(v float64) string { return strconv.FormatFloat(v, 'f', 1, 64) },
}
// staticHandler serves the stylesheet. Dev mode reads from disk so edits show
// up on reload; production serves the embedded copy with a long cache, which is
// safe because the URL carries the content fingerprint.
func staticHandler() http.Handler {
sub, err := fs.Sub(staticFS, "static")
if err != nil {
slog.Error("Error opening embedded static assets", "error", err)
os.Exit(1)
}
embedded := http.FileServer(http.FS(sub))
onDisk := http.FileServer(http.Dir("static"))
return http.StripPrefix("/static/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if isDevMode() {
w.Header().Set("Cache-Control", "no-store")
if _, err := os.Stat("static"); err == nil {
onDisk.ServeHTTP(w, r)
return
}
} else {
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
}
embedded.ServeHTTP(w, r)
}))
}
func isDevMode() bool {
env := strings.ToLower(os.Getenv("ENV"))
if env == "development" || env == "dev" {
return true
}
return false
}
// publicReadOnlyCORSPrefixes are the anonymous, read-only JSON endpoints that
// third-party pages (README embeds, dashboards) are meant to fetch. Everything
// else — session-backed dashboard partials and the ingestion API — gets no CORS
// headers at all, so a foreign origin can never read it.
var publicReadOnlyCORSPrefixes = []string{
"/api/hall-of-fame/",
"/api/libraries",
"/fame/",
"/api/face/hof",
"/api/fame",
"/api/sync-status",
}
func allowedCORSOrigins() map[string]bool {
raw := os.Getenv("CORS_ALLOWED_ORIGINS")
if raw == "" {
return nil
}
allowed := make(map[string]bool)
for _, o := range strings.Split(raw, ",") {
if o = strings.TrimSpace(o); o != "" {
allowed[o] = true
}
}
return allowed
}
var corsOrigins = allowedCORSOrigins()
func isPublicReadOnlyPath(path string) bool {
for _, prefix := range publicReadOnlyCORSPrefixes {
if strings.HasPrefix(path, prefix) {
return true
}
}
return false
}
func corsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
if origin != "" {
switch {
case corsOrigins[origin]:
// Explicitly configured origin: credentials are permitted.
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
w.Header().Add("Vary", "Origin")
case isPublicReadOnlyPath(r.URL.Path):
// Anonymous public data only; never credentialed.
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
}
}
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
}
// contentSecurityPolicy matches what the templates actually load: htmx from
// unpkg (SRI-pinned), Google Fonts, inline styles/scripts emitted by the
// templates, and same-origin SVG badges.
const contentSecurityPolicy = "default-src 'self'; " +
"script-src 'self' 'unsafe-inline' https://unpkg.com; " +
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; " +
"font-src 'self' https://fonts.gstatic.com; " +
"img-src 'self' data:; " +
"connect-src 'self'; " +
"frame-ancestors 'none'; " +
"base-uri 'self'; " +
"form-action 'self'"
func securityHeadersMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h := w.Header()
h.Set("X-Content-Type-Options", "nosniff")
h.Set("X-Frame-Options", "DENY")
h.Set("Referrer-Policy", "strict-origin-when-cross-origin")
h.Set("Content-Security-Policy", contentSecurityPolicy)
next.ServeHTTP(w, r)
})
}
// maskEmail reduces an address to a non-harvestable display form:
// "ada@example.com" becomes "ad***@example.com".
func maskEmail(email string) string {
at := strings.LastIndex(email, "@")
if at <= 0 {
if len(email) <= 2 {
return "***"
}
return email[:2] + "***"
}
local, domain := email[:at], email[at+1:]
if len(local) <= 2 {
return "***@" + domain
}
return local[:2] + "***@" + domain
}
// renderTemplate renders HTML templates, dynamically hot-reloading from disk in dev mode
// or using embedded templates in production mode for optimal performance.
func renderTemplate(w http.ResponseWriter, name string, data any) {
t := prodTmpl
if isDevMode() {
// Hot-reload from disk when the templates are actually there. Running
// the production image with ENV=development has no templates/ next to
// the binary (they are embedded), so fall back rather than 500.
if reloaded, err := template.New("").Funcs(templateFuncs).ParseGlob("templates/*.html"); err != nil {
slog.Debug("Template hot reload unavailable, using embedded templates", "error", err)
} else {
t = reloaded
}
}
if err := t.ExecuteTemplate(w, name, data); err != nil {
slog.Error("Failed to execute template", "template", name, "error", err)
http.Error(w, "Template execution error", http.StatusInternalServerError)
}
}
func main() {
// Initialize structured logger (log/slog)
var logHandler slog.Handler
if isDevMode() {
logHandler = slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug})
} else {
logHandler = slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo})
}
slog.SetDefault(slog.New(logHandler))
secretStr := os.Getenv("SESSION_SECRET")
if secretStr != "" {
sessionSecret = []byte(secretStr)
} else {
if !isDevMode() {
slog.Error("SESSION_SECRET must be set in production mode")
os.Exit(1)
}
sessionSecret = make([]byte, 32)
if _, err := rand.Read(sessionSecret); err != nil {
slog.Error("Failed to generate session secret", "error", err)
os.Exit(1)
}
slog.Warn("SESSION_SECRET not set. Generated a random one. Sessions will not persist across restarts.")
}
if !isDevMode() && os.Getenv("API_INTERNAL_TOKEN") == "" {
slog.Error("API_INTERNAL_TOKEN must be set in production mode")
os.Exit(1)
}
// Parse embedded production templates
var err error
prodTmpl, err = template.New("").Funcs(templateFuncs).ParseFS(templateFS, "templates/*.html")
if err != nil {
slog.Error("Error parsing embedded templates", "error", err)
os.Exit(1)
}
if isDevMode() {
slog.Info("Running in development mode: template hot-reloading enabled from disk")
} else {
slog.Info("Running in production mode: using embedded templates")
}
// Connect to Postgres
connStr := os.Getenv("DATABASE_URL")
if connStr == "" {
connStr = "host=localhost user=postgres password=postgres dbname=postgres sslmode=disable"
}
db, err = sql.Open("postgres", connStr)
if err != nil {
slog.Error("Failed to open database connection", "error", err)
os.Exit(1)
}
defer db.Close()
// Configure connection pool
db.SetMaxOpenConns(25)
db.SetMaxIdleConns(25)
db.SetConnMaxLifetime(5 * time.Minute)
if err := db.Ping(); err != nil {
// In production an unreachable database means every request would
// serve empty or broken data; fail fast so the orchestrator restarts
// us once Postgres is actually up.
if !isDevMode() {
slog.Error("Cannot reach database on startup", "error", err)
os.Exit(1)
}
slog.Warn("Could not ping database on startup. Ensure Postgres is running", "error", err)
} else {
slog.Info("Successfully connected to PostgreSQL")
// Automatically apply database schema. The statements are idempotent
// (CREATE ... IF NOT EXISTS / ADD COLUMN IF NOT EXISTS), so a failure
// here means the schema is genuinely wrong — running on against it
// would produce query errors on every request.
if schemaSQL != "" {
if _, err := db.Exec(schemaSQL); err != nil {
slog.Error("Failed to apply database schema", "error", err)
if !isDevMode() {
os.Exit(1)
}
} else {
slog.Info("Database schema verified and applied successfully")
}
}
// Automatically seed Awesome Libraries catalog
seedTechnologies(db)
}
api := &API{db: db}
jarPath, err := resolveJarPath()
if err != nil {
slog.Error("Ingestion CLI unavailable. Build it with ./build_cli.sh (or `docker compose --profile build run --rm cli-build`).", "error", err)
os.Exit(1)
}
slog.Info("Ingestion CLI located", "path", jarPath)
// Start background worker
ctxWorker, cancelWorker := context.WithCancel(context.Background())
defer cancelWorker()
workerDone := make(chan struct{})
go func() {
defer close(workerDone)
StartWorker(ctxWorker)
}()
r := chi.NewRouter()
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
// Rate limiting / request throttling (protects backend against excessive concurrent requests)
r.Use(middleware.ThrottleBacklog(100, 50, 5*time.Second))
r.Use(securityHeadersMiddleware)
r.Use(robotsHeaderMiddleware)
r.Use(corsMiddleware)
// API routes for Sourcerer CLI ingestion
r.Mount("/api", api.Routes())
// Bundled stylesheet and generated icons
r.Handle("/static/*", staticHandler())
// Crawler surfaces. Icons and the manifest live under /static but are also
// aliased at the root, where browsers and crawlers look for them first.
r.Get("/robots.txt", handleRobotsTxt)
r.Get("/sitemap.xml", handleSitemapXML)
for path, asset := range map[string]string{
"/favicon.ico": "favicon.ico",
"/favicon.svg": "favicon.svg",
"/apple-touch-icon.png": "apple-touch-icon.png",
"/site.webmanifest": "site.webmanifest",
} {
name := asset
r.Get(path, func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/static/"+name+"?v="+assetVersion, http.StatusMovedPermanently)
})
}
r.Get("/healthz", func(w http.ResponseWriter, r *http.Request) {
if err := db.Ping(); err != nil {
slog.Warn("Health check failed: database unreachable", "error", err)
w.WriteHeader(http.StatusServiceUnavailable)
w.Write([]byte("db: unhealthy"))
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("ok"))
})
// OAuth & Auth Routes
r.Get("/auth/github/login", handleGitHubLogin)
r.Get("/auth/github/callback", handleGitHubCallback)
r.Get("/auth/logout", handleLogout)
// HTMX Dashboard Routes
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
sessionEmail := getSessionEmail(r)
if sessionEmail == "" {
// Signed-out visitors — including crawlers — get a real page here.
// Redirecting straight into OAuth left the site with no indexable
// front door at all.
handleLanding(w, r)
return
}
type Author struct {
Email string
Name string
}
type UserInfo struct {
Name string
Email string
PublicProfileID string
}
profileID, err := ensureProfileID(sessionEmail)
if err != nil {
slog.Error("Failed to resolve public profile id", "email", sessionEmail, "error", err)
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
user := &UserInfo{Name: sessionEmail, Email: sessionEmail, PublicProfileID: profileID}
authors := []Author{{Email: sessionEmail, Name: sessionEmail}}
base := getPublicBaseURL(r)
seo := newSEO(base, "/", "Sourcerer — engineering profiles from git history",
"Sourcerer reads your git history and turns it into a profile: commit volume, language split, coding habits, recognized libraries and a shareable README badge.")
// The dashboard is behind a session; only the marketing-facing root is
// worth indexing, and this page is what a signed-in user sees.
seo.NoIndex = true
seo.JSONLD = newJSONLD(map[string]any{
"@context": "https://schema.org",
"@type": "SoftwareApplication",
"name": siteName,
"url": base,
"applicationCategory": "DeveloperApplication",
"operatingSystem": "Web",
"description": seo.Description,
})
seo.Nav = navFor(r, "overview")
data := struct {
Authors []Author
User *UserInfo
SEO SEOMeta
}{
Authors: authors,
User: user,
SEO: seo,
}
renderTemplate(w, "index.html", data)
})
r.Get("/dashboard/languages", func(w http.ResponseWriter, r *http.Request) {
email := getSessionEmail(r)
if email == "" {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
renderTemplate(w, "languages.html", buildLanguageDonut(getLanguagesForEmail(email)))
})
// Repositories live on their own page rather than in an overview card:
// there is more to say per repository than a panel has room for.
r.Get("/repositories", handleRepositoriesPage)
r.Get("/dashboard/repo-cards", handleDashboardRepoCards)
r.Get("/dashboard/facts", handleDashboardFacts)
r.Get("/dashboard/activity", handleDashboardActivity)
r.Get("/dashboard/punchcard", handleDashboardPunchcard)
// Public Sharable Profile Routes (e.g. /u/username or /p/email)
r.Get("/u/{username}", handlePublicProfile)
r.Get("/p/{email}", handlePublicProfile)
// Dynamic SVG Profile Badge for GitHub READMEs
r.Get("/badge/{identifier}", handleBadgeSVG)
r.Get("/badge/{identifier}.svg", handleBadgeSVG)
// Repository Hall of Fame Routes (Feature: hall-of-fame)
r.Get("/hall-of-fame/{repo}", handleHallOfFameHTML)
r.Get("/hall-of-fame/{repo}.svg", handleHallOfFameSVG)
r.Get("/r/{repo}", handleHallOfFameHTML)
r.Get("/r/{repo}.svg", handleHallOfFameSVG)
r.Get("/api/hall-of-fame/{repo}", handleHallOfFameAPI)
// Individual Contributor Fame Avatar Badges & Links (Feature: hall-of-fame widget)
r.Get("/fame/{repo}/images/{num}", handleFameImage)
r.Get("/fame/{owner}/{repo}/images/{num}", handleFameImage)
r.Get("/fame/{user}/{owner}/{repo}/images/{num}", handleFameImage)
r.Get("/fame/{repo}/links/{num}", handleFameLink)
r.Get("/fame/{owner}/{repo}/links/{num}", handleFameLink)
r.Get("/fame/{user}/{owner}/{repo}/links/{num}", handleFameLink)
// Hall of Fame GitHub username matching, token, and management APIs
r.Get("/api/face/hof/match", handleFaceHofMatch)
r.Get("/api/hall-of-fame/match", handleFaceHofMatch)
r.Get("/api/face/hof/token", handleFaceHofToken)
r.Post("/api/face/hof/manage", handleFaceHofManage)
r.Post("/api/fame/manage", handleFaceHofManage)
// Framework & Library Hall of Fame Routes (Feature: library hall-of-fame)
r.Get("/fame/lib/{tech}/images/{num}", handleLibraryFameImage)
r.Get("/fame/lib/{tech}/links/{num}", handleLibraryFameLink)
r.Get("/libraries/{tech}/fame/images/{num}", handleLibraryFameImage)
r.Get("/libraries/{tech}/fame/links/{num}", handleLibraryFameLink)
r.Get("/libraries/{tech}.svg", handleLibraryFameSVG)
r.Get("/api/hall-of-fame/lib/{tech}", handleLibraryFameAPI)
r.Get("/api/libraries/{tech}/fame", handleLibraryFameAPI)
// Real-time Repository Sync Status
r.Get("/dashboard/sync-status", handleDashboardSyncStatus)
r.Get("/api/sync-status", handleAPISyncStatus)
// Awesome Libraries Routes (Feature: awesome-libraries)
r.Get("/libraries", handleLibrariesCatalogHTML)
r.Get("/libraries/{tech}", handleLibraryDetailHTML)
r.Get("/api/libraries", handleLibrariesCatalogAPI)
r.Get("/api/libraries/{tech}", handleLibraryDetailAPI)
r.Get("/dashboard/libraries", handleDashboardLibraries)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
srv := &http.Server{
Addr: ":" + port,
Handler: r,
ReadTimeout: 15 * time.Second,
WriteTimeout: 30 * time.Second,
IdleTimeout: 60 * time.Second,
}
go func() {
slog.Info("Server starting", "port", port)
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
slog.Error("Server listen error", "error", err)
os.Exit(1)
}
}()
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt, syscall.SIGTERM)
<-quit
slog.Info("Shutting down server...")
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
slog.Error("Server forced to shutdown", "error", err)
}
// Let the ingestion worker finish the repository it is currently on rather
// than killing a half-written clone. Jobs still queued are dropped; they
// are re-enqueued on the user's next login.
cancelWorker()
select {
case <-workerDone:
slog.Info("Ingestion worker drained")
case <-ctx.Done():
slog.Warn("Ingestion worker did not drain before shutdown deadline")
}
slog.Info("Server exited cleanly")
}
// ensureProfileID returns the caller's stable public profile identifier,
// minting one on first use. Every public URL (/p, /u, /badge) is keyed on this
// value rather than on an email address.
func ensureProfileID(email string) (string, error) {
var profileID string
err := db.QueryRow("SELECT profile_id FROM public_profiles WHERE email = $1", email).Scan(&profileID)
if err == nil && profileID != "" {
return profileID, nil
}
if err != nil && err != sql.ErrNoRows {
return "", err
}
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
return "", err
}
profileID = hex.EncodeToString(b)
// Concurrent dashboard loads can race here; the upsert keeps whichever id
// landed first and returns it.
err = db.QueryRow(`
INSERT INTO public_profiles (email, profile_id) VALUES ($1, $2)
ON CONFLICT (email) DO UPDATE SET profile_id = COALESCE(public_profiles.profile_id, EXCLUDED.profile_id)
RETURNING profile_id`, email, profileID).Scan(&profileID)
if err != nil {
return "", err
}
return profileID, nil
}
func handleGitHubLogin(w http.ResponseWriter, r *http.Request) {
stateBytes := make([]byte, 32)
if _, err := rand.Read(stateBytes); err != nil {
slog.Error("Failed to generate OAuth state", "error", err)
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
state := hex.EncodeToString(stateBytes)
http.SetCookie(w, &http.Cookie{
Name: "oauth_state",
Value: state,
HttpOnly: true,
Secure: !isDevMode(),
SameSite: http.SameSiteLaxMode,
MaxAge: 600,
Path: "/",
})
url := oauthConfig.AuthCodeURL(state, oauth2.AccessTypeOffline)
http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}
func handleGitHubCallback(w http.ResponseWriter, r *http.Request) {
stateCookie, err := r.Cookie("oauth_state")
if err != nil {
slog.Warn("OAuth state cookie not found", "remote_addr", r.RemoteAddr)
http.Error(w, "State cookie not found", http.StatusBadRequest)
return
}
queryState := r.URL.Query().Get("state")
if !hmac.Equal([]byte(stateCookie.Value), []byte(queryState)) {
slog.Warn("OAuth CSRF state mismatch", "remote_addr", r.RemoteAddr)
http.Error(w, "Invalid state", http.StatusForbidden)
return
}
http.SetCookie(w, &http.Cookie{
Name: "oauth_state",
Value: "",
MaxAge: -1,
Path: "/",
})
code := r.URL.Query().Get("code")
if code == "" {
slog.Warn("OAuth code parameter missing", "remote_addr", r.RemoteAddr)
http.Error(w, "Code not found", http.StatusBadRequest)
return
}
token, err := oauthConfig.Exchange(context.Background(), code)
if err != nil {
slog.Error("Failed to exchange OAuth token", "error", err)
http.Error(w, "Failed to exchange token", http.StatusInternalServerError)
return
}
client := github.NewClient(oauthConfig.Client(context.Background(), token))
user, _, err := client.Users.Get(context.Background(), "")
if err != nil {
slog.Error("Failed to get authenticated GitHub user", "error", err)
http.Error(w, "Failed to get user", http.StatusInternalServerError)
return
}
email := ""
if user.Email != nil {
email = *user.Email
} else {
email = user.GetLogin() + "@users.noreply.github.com"
}
slog.Info("User logged in via GitHub OAuth", "user", user.GetLogin(), "email", email)
// Register the account so Hall of Fame can mark it as a Sourcerer member.
if _, err := db.Exec(`
INSERT INTO users (email, primary_email, verified) VALUES ($1, TRUE, TRUE)
ON CONFLICT (email) DO UPDATE SET primary_email = TRUE, verified = TRUE`, email); err != nil {
slog.Error("Failed to record authenticated user", "email", email, "error", err)
}
// Set a signed session cookie. Secure is relaxed only in development,
// where the app is served over plain HTTP and the browser would otherwise
// discard the cookie, making local login impossible.
http.SetCookie(w, &http.Cookie{
Name: "session",
Value: signCookie(email),
Path: "/",
HttpOnly: true,
Secure: !isDevMode(),
SameSite: http.SameSiteLaxMode,
MaxAge: int(sessionTTL.Seconds()),
})
// Fetch repos in background to avoid blocking request
// Fetch ALL repos across all pages in background to avoid blocking request
go func(email string, token *oauth2.Token) {
client := github.NewClient(oauthConfig.Client(context.Background(), token))
var allRepos []*github.Repository
opt := &github.RepositoryListByAuthenticatedUserOptions{
Type: "owner",
ListOptions: github.ListOptions{PerPage: 100, Page: 1},
}
for {
repos, resp, err := client.Repositories.ListByAuthenticatedUser(context.Background(), opt)
if err != nil {
slog.Error("Failed to fetch repositories for user", "email", email, "page", opt.Page, "error", err)
break
}
allRepos = append(allRepos, repos...)
if resp.NextPage == 0 {
break
}
opt.Page = resp.NextPage
// Gentle 50ms pause between pages to stay safely below GitHub secondary rate limits
time.Sleep(50 * time.Millisecond)
}
slog.Info("Discovered repositories across all pages for user", "total_count", len(allRepos), "email", email)
skippedCount := 0
enqueuedCount := 0
for _, repo := range allRepos {
// The OAuth scope is public_repo and the worker clones anonymously,
// so private repositories can never be fetched. Skip rather than
// queueing jobs that are guaranteed to fail.
if repo.GetPrivate() {
slog.Debug("Skipping private repository: anonymous clone not possible", "repo", repo.GetFullName())
skippedCount++
continue
}
cloneURL := repo.GetCloneURL()
repoName := repo.GetFullName()
pushedAt := ""
if repo.PushedAt != nil {
pushedAt = repo.PushedAt.String()
}
// Fast Tier-1 verification: check if repo was already synced with identical pushed_at timestamp
if db != nil && pushedAt != "" {
var existingPushedAt string
var lastCommit string
err := db.QueryRow(`
SELECT COALESCE(github_pushed_at, ''), COALESCE(last_commit_rehash, '')
FROM repos
WHERE repo_url = $1 OR repo_name = $2`, cloneURL, repoName).Scan(&existingPushedAt, &lastCommit)
if err == nil && existingPushedAt != "" && existingPushedAt == pushedAt && lastCommit != "" {
slog.Debug("Fast-skipping repository: GitHub pushed_at timestamp unchanged", "repo", repoName, "pushed_at", pushedAt)
skippedCount++
continue
}
}
EnqueueJob(IngestionJob{
RepoURL: cloneURL,
RepoName: repoName,
UserEmail: email,
GitHubPushedAt: pushedAt,
})
enqueuedCount++
}
if enqueuedCount > 0 {
globalSyncTracker.StartBatch(email, enqueuedCount)
}
slog.Info("Repository sync planning complete", "total_repos", len(allRepos), "skipped_unchanged", skippedCount, "enqueued_for_sync", enqueuedCount, "email", email)
}(email, token)
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
}
func handleLogout(w http.ResponseWriter, r *http.Request) {
http.SetCookie(w, &http.Cookie{
Name: "session",
Value: "",
Path: "/",
HttpOnly: true,
Secure: !isDevMode(),
SameSite: http.SameSiteLaxMode,
MaxAge: -1,
})
slog.Info("User logged out", "remote_addr", r.RemoteAddr)
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
}
type LangStat struct {
Tech string
Lines int
Percentage int
}
// withPercentages fills in each language's share of the total, rounding any
// non-zero contribution up to 1% so small languages stay visible.
func withPercentages(stats []LangStat) []LangStat {
totalLines := 0
for _, s := range stats {
totalLines += s.Lines
}
if totalLines <= 0 {
return stats
}
for i := range stats {
stats[i].Percentage = int((float64(stats[i].Lines) / float64(totalLines)) * 100.0)
if stats[i].Percentage == 0 && stats[i].Lines > 0 {
stats[i].Percentage = 1
}
}
return stats
}
func getLanguagesForEmail(email string) []LangStat {
rows, err := db.Query(`
SELECT s.tech, SUM(s.num_lines_added) as lines
FROM commit_stats s
JOIN commits c ON c.rehash = s.commit_rehash
WHERE c.author_email = $1
GROUP BY s.tech
ORDER BY lines DESC
LIMIT 10`, email)
if err != nil {
slog.Error("Error querying languages", "email", email, "error", err)
return nil
}
defer rows.Close()
var stats []LangStat
for rows.Next() {
var s LangStat
if err := rows.Scan(&s.Tech, &s.Lines); err == nil && s.Tech != "" {
stats = append(stats, s)
}
}
if err := rows.Err(); err != nil {
slog.Error("Error iterating languages", "email", email, "error", err)
}
return withPercentages(stats)
}
// getReposForEmail lists the repositories the given author has commits in,
// ordered by contribution volume. Shared by the dashboard partial and the
// public profile so both stay consistent.
func getReposForEmail(email string) []RepoInfo {
rows, err := db.Query(`
SELECT r.rehash, COALESCE(r.repo_name, '') as repo_name,
COUNT(c.rehash) as commit_count,
COALESCE(SUM(c.num_lines_added), 0) as lines_added,
COALESCE(SUM(c.num_lines_deleted), 0) as lines_deleted
FROM repos r
JOIN commits c ON c.repo_rehash = r.rehash
WHERE c.author_email = $1
GROUP BY r.rehash, r.repo_name
ORDER BY commit_count DESC`, email)
if err != nil {
slog.Error("Error querying repos", "email", email, "error", err)
return nil
}
defer rows.Close()
var repos []RepoInfo
for rows.Next() {
var repo RepoInfo
if err := rows.Scan(&repo.Rehash, &repo.Name, &repo.CommitCount, &repo.LinesAdded, &repo.LinesDeleted); err == nil {
repos = append(repos, repo)
}
}
if err := rows.Err(); err != nil {
slog.Error("Error iterating repos", "email", email, "error", err)
}
return repos
}
type FactsData struct {
HasData bool
WorkStyle string
WorkStyleIcon string
WorkStyleDesc string
IndentHabit string
IndentIcon string
IndentDesc string
NamingStyle string
NamingIcon string
NamingDesc string
ScheduleStyle string
ScheduleIcon string
ScheduleDesc string
AvgCommitSize string
AvgLineLength string
}
func computeFacts(email string) FactsData {
facts := FactsData{}
var rows *sql.Rows
var err error
if email != "" {