Initial implementation of mcq — document reading queue

Single-binary service: push raw markdown via REST/gRPC API, read rendered
HTML through mobile-friendly web UI. MCIAS auth on all endpoints, SQLite
storage, goldmark rendering with GFM and syntax highlighting.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-03-28 11:53:26 -07:00
commit bc1627915e
36 changed files with 3773 additions and 0 deletions

62
internal/server/auth.go Normal file
View File

@@ -0,0 +1,62 @@
package server
import (
"encoding/json"
"errors"
"net/http"
mcdslauth "git.wntrmute.dev/mc/mcdsl/auth"
)
type loginRequest struct {
Username string `json:"username"`
Password string `json:"password"`
TOTPCode string `json:"totp_code"`
}
type loginResponse struct {
Token string `json:"token"`
}
func loginHandler(auth *mcdslauth.Authenticator) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req loginRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid request body")
return
}
token, _, err := auth.Login(req.Username, req.Password, req.TOTPCode)
if err != nil {
if errors.Is(err, mcdslauth.ErrInvalidCredentials) {
writeError(w, http.StatusUnauthorized, "invalid credentials")
return
}
if errors.Is(err, mcdslauth.ErrForbidden) {
writeError(w, http.StatusForbidden, "access denied by login policy")
return
}
writeError(w, http.StatusServiceUnavailable, "authentication service unavailable")
return
}
writeJSON(w, http.StatusOK, loginResponse{Token: token})
}
}
func logoutHandler(auth *mcdslauth.Authenticator) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
token := extractBearerToken(r)
if token == "" {
writeError(w, http.StatusUnauthorized, "authentication required")
return
}
if err := auth.Logout(token); err != nil {
writeError(w, http.StatusInternalServerError, "logout failed")
return
}
w.WriteHeader(http.StatusNoContent)
}
}

View File

@@ -0,0 +1,131 @@
package server
import (
"encoding/json"
"errors"
"net/http"
"github.com/go-chi/chi/v5"
"git.wntrmute.dev/mc/mcq/internal/db"
)
type putDocumentRequest struct {
Title string `json:"title"`
Body string `json:"body"`
}
func listDocumentsHandler(database *db.DB) http.HandlerFunc {
return func(w http.ResponseWriter, _ *http.Request) {
docs, err := database.ListDocuments()
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to list documents")
return
}
if docs == nil {
docs = []db.Document{}
}
writeJSON(w, http.StatusOK, map[string]any{"documents": docs})
}
}
func getDocumentHandler(database *db.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
slug := chi.URLParam(r, "slug")
doc, err := database.GetDocument(slug)
if errors.Is(err, db.ErrNotFound) {
writeError(w, http.StatusNotFound, "document not found")
return
}
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to get document")
return
}
writeJSON(w, http.StatusOK, doc)
}
}
func putDocumentHandler(database *db.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
slug := chi.URLParam(r, "slug")
var req putDocumentRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid request body")
return
}
if req.Title == "" {
writeError(w, http.StatusBadRequest, "title is required")
return
}
if req.Body == "" {
writeError(w, http.StatusBadRequest, "body is required")
return
}
info := tokenInfoFromContext(r.Context())
pushedBy := "unknown"
if info != nil {
pushedBy = info.Username
}
doc, err := database.PutDocument(slug, req.Title, req.Body, pushedBy)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to save document")
return
}
writeJSON(w, http.StatusOK, doc)
}
}
func deleteDocumentHandler(database *db.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
slug := chi.URLParam(r, "slug")
err := database.DeleteDocument(slug)
if errors.Is(err, db.ErrNotFound) {
writeError(w, http.StatusNotFound, "document not found")
return
}
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to delete document")
return
}
w.WriteHeader(http.StatusNoContent)
}
}
func markReadHandler(database *db.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
slug := chi.URLParam(r, "slug")
doc, err := database.MarkRead(slug)
if errors.Is(err, db.ErrNotFound) {
writeError(w, http.StatusNotFound, "document not found")
return
}
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to mark read")
return
}
writeJSON(w, http.StatusOK, doc)
}
}
func markUnreadHandler(database *db.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
slug := chi.URLParam(r, "slug")
doc, err := database.MarkUnread(slug)
if errors.Is(err, db.ErrNotFound) {
writeError(w, http.StatusNotFound, "document not found")
return
}
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to mark unread")
return
}
writeJSON(w, http.StatusOK, doc)
}
}

View File

@@ -0,0 +1,84 @@
package server
import (
"context"
"log/slog"
"net/http"
"strings"
"time"
mcdslauth "git.wntrmute.dev/mc/mcdsl/auth"
)
type contextKey string
const tokenInfoKey contextKey = "tokenInfo"
// requireAuth returns middleware that validates Bearer tokens via MCIAS.
func requireAuth(auth *mcdslauth.Authenticator) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token := extractBearerToken(r)
if token == "" {
writeError(w, http.StatusUnauthorized, "authentication required")
return
}
info, err := auth.ValidateToken(token)
if err != nil {
writeError(w, http.StatusUnauthorized, "invalid or expired token")
return
}
ctx := context.WithValue(r.Context(), tokenInfoKey, info)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
// tokenInfoFromContext extracts the TokenInfo from the request context.
func tokenInfoFromContext(ctx context.Context) *mcdslauth.TokenInfo {
info, _ := ctx.Value(tokenInfoKey).(*mcdslauth.TokenInfo)
return info
}
// extractBearerToken extracts a bearer token from the Authorization header.
func extractBearerToken(r *http.Request) string {
h := r.Header.Get("Authorization")
if h == "" {
return ""
}
const prefix = "Bearer "
if !strings.HasPrefix(h, prefix) {
return ""
}
return strings.TrimSpace(h[len(prefix):])
}
// loggingMiddleware logs HTTP requests.
func loggingMiddleware(logger *slog.Logger) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
sw := &statusWriter{ResponseWriter: w, status: http.StatusOK}
next.ServeHTTP(sw, r)
logger.Info("http",
"method", r.Method,
"path", r.URL.Path,
"status", sw.status,
"duration", time.Since(start),
"remote", r.RemoteAddr,
)
})
}
}
type statusWriter struct {
http.ResponseWriter
status int
}
func (w *statusWriter) WriteHeader(code int) {
w.status = code
w.ResponseWriter.WriteHeader(code)
}

54
internal/server/routes.go Normal file
View File

@@ -0,0 +1,54 @@
package server
import (
"encoding/json"
"log/slog"
"net/http"
"github.com/go-chi/chi/v5"
mcdslauth "git.wntrmute.dev/mc/mcdsl/auth"
"git.wntrmute.dev/mc/mcdsl/health"
"git.wntrmute.dev/mc/mcq/internal/db"
)
// Deps holds dependencies injected into the REST handlers.
type Deps struct {
DB *db.DB
Auth *mcdslauth.Authenticator
Logger *slog.Logger
}
// RegisterRoutes adds all MCQ REST endpoints to the given router.
func RegisterRoutes(r chi.Router, deps Deps) {
// Public endpoints.
r.Post("/v1/auth/login", loginHandler(deps.Auth))
r.Get("/v1/health", health.Handler(deps.DB.DB))
// Authenticated endpoints.
r.Group(func(r chi.Router) {
r.Use(requireAuth(deps.Auth))
r.Post("/v1/auth/logout", logoutHandler(deps.Auth))
r.Get("/v1/documents", listDocumentsHandler(deps.DB))
r.Get("/v1/documents/{slug}", getDocumentHandler(deps.DB))
r.Put("/v1/documents/{slug}", putDocumentHandler(deps.DB))
r.Delete("/v1/documents/{slug}", deleteDocumentHandler(deps.DB))
r.Post("/v1/documents/{slug}/read", markReadHandler(deps.DB))
r.Post("/v1/documents/{slug}/unread", markUnreadHandler(deps.DB))
})
}
// writeJSON writes a JSON response with the given status code.
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}
// writeError writes a standard error response.
func writeError(w http.ResponseWriter, status int, message string) {
writeJSON(w, status, map[string]string{"error": message})
}