aboutsummaryrefslogtreecommitdiff
path: root/modules/services/nixos/jta/main.go
blob: e7b5a0ff7e30fa0947748fbbc671a17d3f68309b (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
package main

import (
	"bytes"
	_ "embed"
	"html/template"
	"net/http"
	"os"
	"path/filepath"
	"strings"

	"github.com/yuin/goldmark"
	"github.com/yuin/goldmark/extension"
)

// Configure Goldmark with GitHub Flavored Markdown
var mdParser = goldmark.New(
	goldmark.WithExtensions(
		extension.GFM,
	),
)

//go:embed md_template.html
var mdTemplate string

//go:embed style.css
var styleCSS string

//go:embed index.html
var indexHTML string

//go:embed assignments.html
var assignmentsHTML string

var pageTmpl = template.Must(template.New("md_template.html").Parse(mdTemplate))

const authCookieName = "jta_auth"

func isAuthenticated(w http.ResponseWriter, r *http.Request) bool {
	expectedHash := strings.TrimSpace(os.Getenv("AUTH_PASSWORD_HASH"))
	if expectedHash == "" {
		return false
	}

	// Try cookie first
	if cookie, err := r.Cookie(authCookieName); err == nil {
		providedHash := strings.TrimSpace(cookie.Value)
		if providedHash != "" && strings.EqualFold(providedHash, expectedHash) {
			return true
		}
	}

	// Fallback to URL parameter
	paramHash := strings.TrimSpace(r.URL.Query().Get(authCookieName))
	if paramHash != "" && strings.EqualFold(paramHash, expectedHash) {
		http.SetCookie(w, &http.Cookie{
			Name:     authCookieName,
			Value:    paramHash,
			Path:     "/",
			HttpOnly: true,                 // Security: Protects against XSS cookie theft
			Secure:   false,                // Set to true if you are hosting over HTTPS
			SameSite: http.SameSiteLaxMode, // Prevents CSRF vulnerabilities
		})
		return true
	}

	return false
}

func serveMarkdown(w http.ResponseWriter, r *http.Request) {
	// Prevent path traversal
	clean := filepath.Clean(r.URL.Path)
	path := filepath.Join(rootDir, strings.TrimPrefix(clean, "/"))

	mdBytes, err := os.ReadFile(path)
	if err != nil {
		http.NotFound(w, r)
		return
	}

	var buf bytes.Buffer
	if err := mdParser.Convert(mdBytes, &buf); err != nil {
		http.Error(w, "failed to render markdown", 500)
		return
	}

	w.Header().Set("Content-Type", "text/html; charset=utf-8")

	pageTmpl.Execute(w, map[string]template.HTML{
		"Content": template.HTML(buf.String()),
	})
}

var rootDir = "."

func main() {
	if envRootDir := os.Getenv("ROOT_DIR"); envRootDir != "" {
		rootDir = envRootDir
	}

	fs := http.FileServer(http.Dir(rootDir))
	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path == "/" || r.URL.Path == "/index.html" {
			w.Header().Set("Content-Type", "text/html; charset=utf-8")
			w.Write([]byte(indexHTML))
			return
		}

		if r.URL.Path == "/style.css" {
			w.Header().Set("Content-Type", "text/css; charset=utf-8")
			w.Write([]byte(styleCSS))
			return
		}

		if !isAuthenticated(w, r) {
			http.Error(w, "unauthorized", http.StatusUnauthorized)
			return
		}

		if r.URL.Path == "/assignments" || r.URL.Path == "/assignments.html" {
			w.Header().Set("Content-Type", "text/html; charset=utf-8")
			w.Write([]byte(assignmentsHTML))
			return
		}

		// Intercept markdown files
		if strings.HasSuffix(r.URL.Path, ".md") {
			serveMarkdown(w, r)
			return
		}

		// Otherwise serve normally
		fs.ServeHTTP(w, r)
	})

	http.ListenAndServe(":"+port, nil)
}