feat: bootstrap foundation application

This commit is contained in:
2026-04-29 00:26:58 -04:00
parent 8e6646499f
commit 4a72e1e030
53 changed files with 4443 additions and 0 deletions

View File

@@ -0,0 +1,7 @@
package httpserver
import "io/fs"
func fsSub(path string) (fs.FS, error) {
return fs.Sub(assets, path)
}

View File

@@ -0,0 +1,242 @@
package httpserver
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"html/template"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/go-chi/chi/v5"
"github.com/tim/md-hub-secure/apps/server/internal/docs"
)
type layoutData struct {
Title string
WebEnabled bool
BodyClass string
BodyTemplate string
Data any
}
type indexData struct {
Documents []docs.DocumentRecord
}
type documentData struct {
Title string
Path string
Tags []string
Hash string
HTML template.HTML
}
type errorData struct {
Status int
Message string
}
func (s *Server) handleIndex(w http.ResponseWriter, r *http.Request) {
items, err := s.documents.ListDocuments(r.Context())
if err != nil {
s.renderError(w, r, http.StatusInternalServerError, err.Error())
return
}
s.renderTemplate(w, http.StatusOK, "index.gohtml", layoutData{
Title: "MD Hub Secure",
WebEnabled: s.webEnabled,
BodyClass: "page-index",
BodyTemplate: "index_content",
Data: indexData{
Documents: items,
},
})
}
func (s *Server) handleDocsIndexRedirect(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/", http.StatusFound)
}
func (s *Server) handleDocument(w http.ResponseWriter, r *http.Request) {
pagePath := chi.URLParam(r, "*")
page, err := s.documents.LoadPage(r.Context(), pagePath)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
s.renderError(w, r, http.StatusNotFound, "document not found")
return
}
s.renderError(w, r, http.StatusInternalServerError, err.Error())
return
}
s.renderTemplate(w, http.StatusOK, "document.gohtml", layoutData{
Title: page.Title,
WebEnabled: s.webEnabled,
BodyClass: "page-document",
BodyTemplate: "document_content",
Data: documentData{
Title: page.Title,
Path: page.Path,
Tags: page.Tags,
Hash: page.Hash,
HTML: template.HTML(page.HTML),
},
})
}
func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
dbStatus := "ok"
if err := s.repository.Ping(ctx); err != nil {
dbStatus = err.Error()
}
contentStatus := "ok"
if _, err := os.Stat(s.config.Content.StoreDir); err != nil {
contentStatus = err.Error()
}
writeJSON(w, http.StatusOK, map[string]string{
"status": "ok",
"database": dbStatus,
"contentStore": contentStatus,
})
}
func (s *Server) handleUpload(w http.ResponseWriter, r *http.Request) {
if err := r.ParseMultipartForm(32 << 20); err != nil {
s.renderError(w, r, http.StatusBadRequest, "invalid multipart upload")
return
}
file, header, err := r.FormFile("file")
if err != nil {
s.renderError(w, r, http.StatusBadRequest, "file field is required")
return
}
defer file.Close()
content, err := io.ReadAll(io.LimitReader(file, 32<<20))
if err != nil {
s.renderError(w, r, http.StatusInternalServerError, "read upload")
return
}
contentType := http.DetectContentType(content)
if !isAllowedContentType(contentType) {
s.renderError(w, r, http.StatusBadRequest, "unsupported content type")
return
}
record, err := s.contentStore.PutBytes(content)
if err != nil {
s.renderError(w, r, http.StatusInternalServerError, "store upload")
return
}
if err := s.repository.SaveAttachment(r.Context(), docs.AttachmentRecord{
Hash: record.Hash,
OriginalName: header.Filename,
ContentType: contentType,
SizeBytes: record.Size,
CreatedAt: time.Now().UTC(),
}); err != nil {
s.renderError(w, r, http.StatusInternalServerError, "persist upload metadata")
return
}
writeJSONWithStatus(w, http.StatusCreated, map[string]string{
"hash": record.Hash,
"contentType": contentType,
"attachmentUrl": "/attachments/" + record.Hash,
})
}
func (s *Server) handleAttachment(w http.ResponseWriter, r *http.Request) {
hash := chi.URLParam(r, "hash")
attachment, err := s.repository.GetAttachment(r.Context(), hash)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
s.renderError(w, r, http.StatusNotFound, "attachment not found")
return
}
s.renderError(w, r, http.StatusInternalServerError, "lookup attachment")
return
}
content, err := s.contentStore.Read(hash)
if err != nil {
s.renderError(w, r, http.StatusInternalServerError, "read attachment")
return
}
w.Header().Set("Content-Type", attachment.ContentType)
w.Header().Set("Content-Disposition", fmt.Sprintf("inline; filename=%q", sanitizeFilename(attachment.OriginalName)))
w.Header().Set("Content-Length", fmt.Sprintf("%d", len(content)))
w.WriteHeader(http.StatusOK)
_, _ = w.Write(content)
}
func (s *Server) renderTemplate(w http.ResponseWriter, status int, name string, data layoutData) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(status)
if err := s.templates.ExecuteTemplate(w, name, data); err != nil {
http.Error(w, "template error", http.StatusInternalServerError)
}
}
func (s *Server) renderError(w http.ResponseWriter, r *http.Request, status int, message string) {
s.renderTemplate(w, status, "error.gohtml", layoutData{
Title: http.StatusText(status),
WebEnabled: s.webEnabled,
BodyClass: "page-error",
BodyTemplate: "error_content",
Data: errorData{
Status: status,
Message: message,
},
})
}
func isAllowedContentType(contentType string) bool {
allowed := []string{
"image/png",
"image/jpeg",
"image/gif",
"image/webp",
"application/pdf",
"text/plain; charset=utf-8",
}
for _, candidate := range allowed {
if strings.EqualFold(candidate, contentType) {
return true
}
}
return false
}
func sanitizeFilename(name string) string {
name = filepath.Base(name)
return strings.ReplaceAll(name, "\"", "")
}
func writeJSON(w http.ResponseWriter, status int, payload any) {
writeJSONWithStatus(w, status, payload)
}
func writeJSONWithStatus(w http.ResponseWriter, status int, payload any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(payload)
}

View File

@@ -0,0 +1,42 @@
package httpserver
import (
"net/http"
"time"
)
func (s *Server) requestLogger(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ww := &statusWriter{ResponseWriter: w, status: http.StatusOK}
start := time.Now()
next.ServeHTTP(ww, r)
s.logger.Info("http request",
"method", r.Method,
"path", r.URL.Path,
"status", ww.status,
"duration", time.Since(start).String(),
)
})
}
func (s *Server) securityHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Security-Policy", "default-src 'self'; base-uri 'self'; frame-ancestors 'none'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self'; connect-src 'self'; object-src 'none'")
w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("X-Frame-Options", "DENY")
w.Header().Set("Cross-Origin-Opener-Policy", "same-origin")
w.Header().Set("Cross-Origin-Resource-Policy", "same-origin")
next.ServeHTTP(w, r)
})
}
type statusWriter struct {
http.ResponseWriter
status int
}
func (w *statusWriter) WriteHeader(status int) {
w.status = status
w.ResponseWriter.WriteHeader(status)
}

View File

@@ -0,0 +1,93 @@
package httpserver
import (
"embed"
"html/template"
"log/slog"
"net/http"
"os"
"strings"
"time"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/tim/md-hub-secure/apps/server/internal/config"
"github.com/tim/md-hub-secure/apps/server/internal/docs"
"github.com/tim/md-hub-secure/apps/server/internal/store"
)
//go:embed templates/*.gohtml static/*
var assets embed.FS
type Dependencies struct {
Config config.Config
Logger *slog.Logger
Documents *docs.Service
Repository *docs.Repository
ContentStore *store.ContentStore
}
type Server struct {
config config.Config
logger *slog.Logger
documents *docs.Service
repository *docs.Repository
contentStore *store.ContentStore
templates *template.Template
webEnabled bool
}
func New(deps Dependencies) (http.Handler, error) {
templates, err := template.New("").Funcs(template.FuncMap{
"trimMd": func(path string) string {
return strings.TrimSuffix(path, ".md")
},
}).ParseFS(assets, "templates/*.gohtml")
if err != nil {
return nil, err
}
server := &Server{
config: deps.Config,
logger: deps.Logger,
documents: deps.Documents,
repository: deps.Repository,
contentStore: deps.ContentStore,
templates: templates,
}
if _, err := os.Stat(deps.Config.Web.DistDir); err == nil {
server.webEnabled = true
}
router := chi.NewRouter()
router.Use(middleware.RequestID)
router.Use(middleware.RealIP)
router.Use(middleware.Recoverer)
router.Use(middleware.Timeout(30 * time.Second))
router.Use(server.requestLogger)
router.Use(server.securityHeaders)
router.Get("/", server.handleIndex)
router.Get("/health", server.handleHealth)
router.Get("/docs", server.handleDocsIndexRedirect)
router.Get("/docs/*", server.handleDocument)
router.Post("/api/uploads", server.handleUpload)
router.Get("/attachments/{hash}", server.handleAttachment)
router.Handle("/static/*", http.StripPrefix("/static/", http.FileServer(mustSub("static"))))
if server.webEnabled {
router.Handle("/app/*", http.StripPrefix("/app/", http.FileServer(http.Dir(deps.Config.Web.DistDir))))
}
return router, nil
}
func mustSub(path string) http.FileSystem {
sub, err := fsSub(path)
if err != nil {
panic(err)
}
return http.FS(sub)
}

View File

@@ -0,0 +1,194 @@
:root {
color-scheme: light;
--bg: #fbf7ef;
--panel: rgba(255, 255, 255, 0.82);
--panel-strong: #ffffff;
--text: #18202a;
--muted: #5b6675;
--accent: #0f5bd8;
--accent-soft: rgba(15, 91, 216, 0.1);
--border: rgba(24, 32, 42, 0.12);
--shadow: 0 16px 48px rgba(24, 32, 42, 0.08);
--radius-lg: 24px;
--radius-md: 16px;
--radius-sm: 10px;
font-family: "Charter", "Iowan Old Style", "Palatino Linotype", serif;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
min-height: 100vh;
color: var(--text);
background:
radial-gradient(circle at top left, rgba(15, 91, 216, 0.16), transparent 34%),
radial-gradient(circle at bottom right, rgba(14, 163, 125, 0.13), transparent 28%),
linear-gradient(180deg, #fdfaf5 0%, #f5efe6 100%);
}
a {
color: var(--accent);
}
code {
font-family: ui-monospace, SFMono-Regular, monospace;
}
.site-header {
position: sticky;
top: 0;
z-index: 10;
border-bottom: 1px solid rgba(255, 255, 255, 0.42);
background: rgba(251, 247, 239, 0.92);
backdrop-filter: blur(12px);
}
.site-header__inner,
.site-main {
width: min(1080px, calc(100vw - 2rem));
margin: 0 auto;
}
.site-header__inner {
display: flex;
align-items: center;
justify-content: space-between;
min-height: 72px;
}
.site-brand {
color: var(--text);
font-size: 1.15rem;
font-weight: 700;
text-decoration: none;
}
.site-nav {
display: flex;
gap: 1rem;
}
.site-nav a {
text-decoration: none;
}
.site-main {
padding: 2rem 0 4rem;
}
.hero-panel,
.doc-list,
.document-shell,
.error-panel {
border: 1px solid var(--border);
border-radius: var(--radius-lg);
background: var(--panel);
box-shadow: var(--shadow);
}
.hero-panel,
.error-panel {
padding: 2rem;
}
.doc-list,
.document-shell {
margin-top: 1rem;
padding: 1.5rem 2rem;
}
.eyebrow {
margin: 0 0 0.8rem;
color: var(--accent);
font: 700 0.78rem/1.2 ui-monospace, SFMono-Regular, monospace;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.lede {
max-width: 44rem;
color: var(--muted);
line-height: 1.7;
}
.doc-list ul,
.tag-list {
margin: 0;
padding: 0;
list-style: none;
}
.doc-list li {
display: flex;
flex-wrap: wrap;
gap: 0.75rem;
align-items: center;
padding: 0.75rem 0;
border-top: 1px solid var(--border);
}
.doc-list li:first-child {
border-top: 0;
}
.tag-list {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.tag-list a {
display: inline-flex;
padding: 0.35rem 0.65rem;
border-radius: 999px;
background: var(--accent-soft);
text-decoration: none;
}
.hash {
color: var(--muted);
overflow-wrap: anywhere;
}
.markdown-body {
line-height: 1.75;
}
.markdown-body pre {
overflow-x: auto;
padding: 1rem;
border-radius: var(--radius-md);
background: #18202a;
color: #f7f9fc;
}
.markdown-body blockquote {
margin-left: 0;
padding: 0.9rem 1rem;
border-left: 4px solid var(--accent);
border-radius: 0 var(--radius-sm) var(--radius-sm) 0;
background: rgba(15, 91, 216, 0.05);
}
.markdown-body img {
max-width: 100%;
}
@media (max-width: 720px) {
.site-header__inner {
flex-direction: column;
align-items: flex-start;
justify-content: center;
gap: 0.5rem;
padding: 0.75rem 0;
}
.doc-list,
.document-shell {
padding: 1.25rem;
}
}

View File

@@ -0,0 +1,32 @@
{{ define "base" }}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>{{ .Title }}</title>
<link rel="stylesheet" href="/static/site.css" />
</head>
<body class="{{ .BodyClass }}">
<header class="site-header">
<div class="site-header__inner">
<a class="site-brand" href="/">MD Hub Secure</a>
<nav class="site-nav">
<a href="/">Docs</a>
{{ if .WebEnabled }}<a href="/app/">App</a>{{ end }}
<a href="/health">Health</a>
</nav>
</div>
</header>
<main class="site-main">
{{ if eq .BodyTemplate "index_content" }}
{{ template "index_content" .Data }}
{{ else if eq .BodyTemplate "document_content" }}
{{ template "document_content" .Data }}
{{ else if eq .BodyTemplate "error_content" }}
{{ template "error_content" .Data }}
{{ end }}
</main>
</body>
</html>
{{ end }}

View File

@@ -0,0 +1,22 @@
{{ define "document.gohtml" }}{{ template "base" . }}{{ end }}
{{ define "document_content" }}
<article class="document-shell">
<div class="document-meta">
<p class="eyebrow">{{ .Path }}</p>
<h1>{{ .Title }}</h1>
{{ if .Tags }}
<ul class="tag-list">
{{ range .Tags }}
<li><a href="/?tag={{ . }}">#{{ . }}</a></li>
{{ end }}
</ul>
{{ end }}
<p class="hash">SHA-256: <code>{{ .Hash }}</code></p>
</div>
<div class="markdown-body">
{{ .HTML }}
</div>
</article>
{{ end }}

View File

@@ -0,0 +1,9 @@
{{ define "error.gohtml" }}{{ template "base" . }}{{ end }}
{{ define "error_content" }}
<section class="error-panel">
<p class="eyebrow">Error</p>
<h1>{{ .Status }}</h1>
<p>{{ .Message }}</p>
</section>
{{ end }}

View File

@@ -0,0 +1,23 @@
{{ define "index.gohtml" }}{{ template "base" . }}{{ end }}
{{ define "index_content" }}
<section class="hero-panel">
<p class="eyebrow">Foundation</p>
<h1>Server-rendered Markdown, secure attachments, and a clean base for sync.</h1>
<p class="lede">This milestone focuses on a fast read path. Documents are synchronized from the content directory into content-addressed storage and rendered to HTML on demand.</p>
</section>
<section class="doc-list">
<h2>Documents</h2>
<ul>
{{ range .Documents }}
<li>
<a href="/docs/{{ trimMd .Path }}">{{ .Title }}</a>
<code>{{ .Path }}</code>
</li>
{{ else }}
<li>No documents found.</li>
{{ end }}
</ul>
</section>
{{ end }}