package main import ( "bytes" "crypto/ed25519" "crypto/sha512" "crypto/subtle" "embed" "encoding/base64" "encoding/hex" "flag" "fmt" "html/template" "io" "log" "net/http" "os" "path/filepath" "strings" "time" ) var ( port = flag.Int("port", 42069, "port to listen on") secretsFile = flag.String("secrets", "secrets", "path to the secrets file") notepadFile = flag.String("notepad", "notepad", "path to save user notes") serverStartTime = time.Now() ) var ( notepadPassword []byte privateKey ed25519.PrivateKey publicKey ed25519.PublicKey ) func loadSecrets() error { secrets, err := os.ReadFile(*secretsFile) if err != nil { return err } for _, line := range bytes.Split(bytes.TrimSuffix(secrets, []byte("\n")), []byte("\n")) { if pw, ok := bytes.CutPrefix(line, []byte("notepad-password=")); ok { notepadPassword = make([]byte, hex.DecodedLen(len(pw))) if _, err := hex.Decode(notepadPassword, pw); err != nil { return err } } else if key, ok := bytes.CutPrefix(line, []byte("secret-key=")); ok { seed := make([]byte, hex.DecodedLen(len(key))) if _, err := hex.Decode(seed, key); err != nil { return err } if len(seed) != ed25519.SeedSize { return fmt.Errorf("invalid ed25519 key") } privateKey = ed25519.NewKeyFromSeed(seed) publicKey = privateKey.Public().(ed25519.PublicKey) } } return nil } var ( //go:embed templates/404.html.template notFoundString string notFoundTemplate = template.Must(template.New("notFound").Parse(notFoundString)) ) func notFound(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotFound) type args struct { Path string } if err := notFoundTemplate.Execute(w, args{Path: r.URL.Path}); err != nil { log.Printf("Warning: notFound: %s", err) } } var ( //go:embed templates/outline.html.template outlineString string outlineTemplate = template.Must(template.New("outline").Parse(outlineString)) //go:embed templates/index.html.template indexString string indexTemplate = template.Must(template.Must(outlineTemplate.Clone()).New("body").Parse(indexString)).Lookup("outline") ) func index(w http.ResponseWriter, _ *http.Request) { if err := indexTemplate.Execute(w, nil); err != nil { log.Printf("Warning: index: %s", err) } } var ( //go:embed templates/pong.html.template pongString string pongTemplate = template.Must(template.New("pong").Parse(pongString)) ) func pong(w http.ResponseWriter, _ *http.Request) { if err := pongTemplate.Execute(w, nil); err != nil { log.Printf("Warning: pong: %s", err) } } //go:embed static var staticFiles embed.FS func serveStaticFile(w http.ResponseWriter, r *http.Request, path string) { f, err := staticFiles.Open(path) if err != nil { notFound(w, r) return } defer f.Close() http.ServeContent(w, r, path, serverStartTime, f.(io.ReadSeeker)) } func static(w http.ResponseWriter, r *http.Request) { serveStaticFile(w, r, strings.TrimPrefix(r.URL.Path, "/")) } func favicon(w http.ResponseWriter, r *http.Request) { serveStaticFile(w, r, "static/favicon.ico") } const cookieExpiration = 400 * 24 * time.Hour func attachCookie(w http.ResponseWriter) error { nowBytes, err := time.Now().MarshalBinary() if err != nil { return err } sig := ed25519.Sign(privateKey, nowBytes) http.SetCookie(w, &http.Cookie{ Name: "auth", Value: base64.RawStdEncoding.EncodeToString(append(nowBytes, sig...)), Path: "/notepad", Expires: time.Now().Add(cookieExpiration), Secure: true, HttpOnly: true, SameSite: http.SameSiteStrictMode, Partitioned: true, }) return nil } func cookieAuth(w http.ResponseWriter, r *http.Request) bool { cookie, err := r.Cookie("auth") if err != nil { return false } bytes, err := base64.RawStdEncoding.DecodeString(cookie.Value) if err != nil { return false } if len(bytes) < ed25519.SignatureSize { return false } msg, sig := bytes[:len(bytes)-ed25519.SignatureSize], bytes[len(bytes)-ed25519.SignatureSize:] if !ed25519.Verify(publicKey, msg, sig) { return false } var t time.Time if err := t.UnmarshalBinary(msg); err != nil { return false } if time.Since(t) > cookieExpiration { return false } attachCookie(w) return true } var ( //go:embed templates/login.html.template loginString string loginTemplate = template.Must(template.Must(outlineTemplate.Clone()).New("body").Parse(loginString)).Lookup("outline") ) type loginTemplateArgs struct { Error bool Redirect string } func login(w http.ResponseWriter, r *http.Request) { pwHash := sha512.Sum512([]byte(r.FormValue("password"))) if subtle.ConstantTimeCompare(pwHash[:], notepadPassword) == 0 { if err := loginTemplate.Execute(w, loginTemplateArgs{Error: true, Redirect: r.FormValue("redirect")}); err != nil { log.Printf("Warning: login: %s", err) } return } attachCookie(w) http.Redirect(w, r, r.FormValue("redirect"), http.StatusSeeOther) } var ( //go:embed templates/note.html.template notepadString string notepadTemplate = template.Must(template.Must(outlineTemplate.Clone()).New("body").Parse(notepadString)).Lookup("outline") ) type notepadTemplateArgs struct { Content string } func notepad(w http.ResponseWriter, r *http.Request) { if !cookieAuth(w, r) { if err := loginTemplate.Execute(w, loginTemplateArgs{Redirect: "/notepad"}); err != nil { log.Printf("Warning: login: %s", err) } return } var currentContent string if currentContentBytes, err := os.ReadFile(*notepadFile); err != nil { currentContent = fmt.Sprintf("Error reading notepad file: %s", err) } else { currentContent = string(currentContentBytes) } if err := notepadTemplate.Execute(w, notepadTemplateArgs{Content: currentContent}); err != nil { log.Printf("Warning: notepad: %s", err) } } func saveNote(w http.ResponseWriter, r *http.Request) error { if !cookieAuth(w, r) { return fmt.Errorf("not logged in") } f, err := os.CreateTemp(filepath.Dir(*notepadFile), "notepad") if err != nil { return err } defer f.Close() if _, err = f.Write([]byte(r.FormValue("content"))); err != nil { return err } if err := f.Close(); err != nil { return err } return os.Rename(f.Name(), *notepadFile) } func autosave(w http.ResponseWriter, r *http.Request) { msg := "Saved ✓" if err := saveNote(w, r); err != nil { msg = fmt.Sprintf("Failed to save: %s", err) } if err := notepadTemplate.ExecuteTemplate(w, "saveIndicator", msg); err != nil { log.Printf("Warning: autosave: %s", err) } } func main() { flag.Parse() if err := loadSecrets(); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } http.HandleFunc("GET /pong", pong) http.HandleFunc("POST /login", login) http.HandleFunc("GET /notepad", notepad) http.HandleFunc("POST /notepad/autosave", autosave) http.HandleFunc("GET /static/", static) http.HandleFunc("GET /favicon.ico", favicon) http.HandleFunc("GET /{$}", index) http.HandleFunc("GET /", notFound) addr := fmt.Sprintf(":%d", *port) log.Printf("Listening on %q", addr) log.Fatal(http.ListenAndServe(addr, nil)) }