Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,16 @@ All notable changes to LightCMS are documented here, organized by version.

---

## [7.4.6] - 2026-11-06

### Fixed
- **Images uploaded in the admin editor survive a deploy.** An image field or OG image uploaded through the page form was written to `static/uploads` inside the running image, which every deploy replaces, so the picture disappeared at the next deploy and the page showed a broken image, unless the machine that ran the deploy happened to have a copy of the file. These uploads are now written to `content/uploads`, on the persistent volume, and `/uploads/` is served from there; their URLs are unchanged. At startup the server copies any file the image still carries in `static/uploads` into `content/uploads` (never overwriting one), so files baked into earlier images keep working. Asset-library, API and MCP uploads were already on the volume.

### Internal
- **Docker base images are pinned by digest** in `Dockerfile`, `Dockerfile.mcp` and `Dockerfile.smithery`, with the tag each was resolved from in a comment above it. `Dockerfile.smithery` builds again: its Go 1.24 image refused this module's `go 1.25.0` requirement. It now uses the same Go 1.25.14 as the other two, and Alpine 3.23 instead of `alpine:latest`.

---

## [7.4.5] - 2026-10-16

### Changed
Expand Down
3 changes: 2 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ Hard-won rules from building v7. Violating these has bitten us before:
- The handlers package has its OWN cleanup list (`cleanupCollections` in `internal/handlers/testhelper_test.go`), separate from `testutil.CleanupCollections`: add a new collection to both. It did not drop `content_forks` until 7.4.3, and `createTestFork` derives the preview token from the fork name, so a test that looks a fork up by token should use a unique name.
- When the Atlas test cluster is flaky a full `go test ./...` can fail a different handful of tests on each run (stalls of 15–100s, "i/o timeout", "server selection"). Read the failure text before debugging; a test that fails fast and repeatably on its own is real, the rest are the network.
- New MongoDB collections MUST be added to `CleanupCollections` in `internal/testutil/testutil.go`, or leftover data makes tests flake across runs (bit us with `maintenance_reports`).
- Tests must not write tracked files. The handlers and services write `static/sitemap.xml` and `static/css/theme-vars.css` relative to the working directory, which under `go test` is the package directory, where copies of both are checked in. `TestMain` in `internal/handlers` and `internal/services` points them at a temp directory (`sitemapFile`, `services.ThemeCSSFile`) and fails the run if any tracked file under the package changed (`testutil.SnapshotTrackedFiles`). Give any new file the server writes the same kind of variable.
- Tests must not write tracked files. The handlers and services write `static/sitemap.xml`, `static/css/theme-vars.css` and the admin editor's uploads relative to the working directory, which under `go test` is the package directory, where copies of the first two are checked in. `TestMain` in `internal/handlers` and `internal/services` points them at a temp directory (`sitemapFile`, `services.ThemeCSSFile`, `UploadsDir`) and fails the run if any tracked file under the package changed (`testutil.SnapshotTrackedFiles`). Give any new file the server writes the same kind of variable.
- Tests asserting on collection contents should match by seeded paths/IDs, not exact counts — background goroutines (index regen, keyword rebuild) can insert content mid-test.
- Coverage gate: Codecov ≥80% (target margin ~85%); codecov.yml excludes cmd/, testutil, internal/handlers, content_watcher.go. Codecov's line metric reads ~2 points BELOW `go tool cover` statement totals.
- Transient Atlas DNS failures ("no such host", "server selection timeout") are environmental — rerun before investigating.
Expand Down Expand Up @@ -259,6 +259,7 @@ Hard-won rules from building v7. Violating these has bitten us before:
- `/mcp-public` — read-only MCP server for visitors' agents (search_site, get_page, list_pages, get_site_info); drafts/forks structurally excluded

### Deploy quirks
- A file the server writes at runtime that must outlast a deploy goes under `content/`, the Fly volume mounted at `/app/content`. `static/` is part of the image: `./deploy.sh` builds it from the deploying machine's checkout and every deploy replaces it. Admin editor uploads (image fields, OG images) moved from `static/uploads` to `handlers.UploadsDir` (`content/uploads`, still served at `/uploads/`) in 7.4.6; `MigrateLegacyUploads` copies files an image still carries in `static/uploads` at startup. Files the server regenerates (`static/sitemap.xml` when missing, `static/css/theme-vars.css` at startup) can stay in `static/`.
- The `fly deploy --detach` step inside `./deploy.sh` (never run `fly deploy` yourself) uploads a ~185MB build context (content/ + static/) with no visible progress — deploys take ~8 minutes and are NOT hung.
- `fly secrets set` does NOT restart the legacy machine (it is outside Fly release management, same reason deploy.sh exists). Secrets stay staged until `fly machines update d890122a371528 -a metavert-cms --yes` or the next `./deploy.sh` — a plain `fly machines restart` reuses the old machine config and does NOT inject new secrets (verify with `fly ssh console -C 'sh -c env'`).

Expand Down
2 changes: 1 addition & 1 deletion build.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{"version":"7.4.5"}
{"version":"7.4.6"}
10 changes: 9 additions & 1 deletion cmd/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,14 @@ func main() {
log.Printf("Warning: Failed to regenerate theme CSS on startup: %v", err)
}

// Admin editor uploads live in content/uploads, on the persistent volume. Copy any that
// this image still carries in static/uploads, where they were written before 7.4.6.
if n, err := handlers.MigrateLegacyUploads(); err != nil {
log.Printf("Warning: Failed to copy legacy uploads: %v", err)
} else if n > 0 {
log.Printf("Copied %d legacy upload(s) into %s", n, handlers.UploadsDir)
}

// Initialize services for API and change watcher
contentService := services.NewContentService(db)
h.SetContentService(contentService)
Expand Down Expand Up @@ -228,7 +236,7 @@ func main() {

// Static files
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
r.PathPrefix("/uploads/").Handler(http.StripPrefix("/uploads/", http.FileServer(http.Dir("static/uploads"))))
r.PathPrefix("/uploads/").Handler(http.StripPrefix("/uploads/", http.FileServer(http.Dir(handlers.UploadsDir))))

// CSRF protection for admin routes
// Derive a 32-byte CSRF key by hashing the session secret with SHA-256.
Expand Down
44 changes: 16 additions & 28 deletions internal/handlers/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -913,13 +913,10 @@ func (h *Handler) CreateContent(w http.ResponseWriter, r *http.Request) {
file, header, err := r.FormFile("field_" + field.Name)
if err == nil {
defer file.Close()
filename := fmt.Sprintf("%d_%s", time.Now().UnixNano(), header.Filename)
filepath := filepath.Join("static/uploads", filename)
dst, err := os.Create(filepath)
if err == nil {
defer dst.Close()
io.Copy(dst, file)
data[field.Name] = "/uploads/" + filename
if uploaded, err := saveUpload(file, "", header.Filename); err == nil {
data[field.Name] = uploaded
} else {
log.Printf("Failed to save upload for field %s: %v", field.Name, err)
}
}
} else {
Expand Down Expand Up @@ -1033,13 +1030,10 @@ func (h *Handler) CreateContent(w http.ResponseWriter, r *http.Request) {
ogFile, ogHeader, err := r.FormFile("og_image")
if err == nil {
defer ogFile.Close()
filename := fmt.Sprintf("%d_og_%s", time.Now().UnixNano(), ogHeader.Filename)
ogFilepath := filepath.Join("static/uploads", filename)
dst, err := os.Create(ogFilepath)
if err == nil {
defer dst.Close()
io.Copy(dst, ogFile)
ogImage = "/uploads/" + filename
if uploaded, err := saveUpload(ogFile, "og_", ogHeader.Filename); err == nil {
ogImage = uploaded
} else {
log.Printf("Failed to save OG image upload: %v", err)
}
}

Expand Down Expand Up @@ -1312,13 +1306,10 @@ func (h *Handler) UpdateContent(w http.ResponseWriter, r *http.Request) {
file, header, err := r.FormFile("field_" + field.Name)
if err == nil {
defer file.Close()
filename := fmt.Sprintf("%d_%s", time.Now().UnixNano(), header.Filename)
filepath := filepath.Join("static/uploads", filename)
dst, err := os.Create(filepath)
if err == nil {
defer dst.Close()
io.Copy(dst, file)
data[field.Name] = "/uploads/" + filename
if uploaded, err := saveUpload(file, "", header.Filename); err == nil {
data[field.Name] = uploaded
} else {
log.Printf("Failed to save upload for field %s: %v", field.Name, err)
}
} else if existingData, ok := existingContent.Data[field.Name]; ok {
data[field.Name] = existingData
Expand Down Expand Up @@ -1503,13 +1494,10 @@ func (h *Handler) UpdateContent(w http.ResponseWriter, r *http.Request) {
ogFile, ogHeader, err := r.FormFile("og_image")
if err == nil {
defer ogFile.Close()
filename := fmt.Sprintf("%d_og_%s", time.Now().UnixNano(), ogHeader.Filename)
ogFilepath := filepath.Join("static/uploads", filename)
dst, err := os.Create(ogFilepath)
if err == nil {
defer dst.Close()
io.Copy(dst, ogFile)
ogImage = "/uploads/" + filename
if uploaded, err := saveUpload(ogFile, "og_", ogHeader.Filename); err == nil {
ogImage = uploaded
} else {
log.Printf("Failed to save OG image upload: %v", err)
}
}

Expand Down
2 changes: 2 additions & 0 deletions internal/handlers/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ func TestMain(m *testing.M) {
}
sitemapFile = filepath.Join(tmp, "sitemap.xml")
services.ThemeCSSFile = filepath.Join(tmp, "css", "theme-vars.css")
UploadsDir = filepath.Join(tmp, "uploads")
legacyUploadsDir = filepath.Join(tmp, "legacy-uploads")
changed := testutil.SnapshotTrackedFiles()

code := m.Run()
Expand Down
99 changes: 99 additions & 0 deletions internal/handlers/uploads.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
package handlers

import (
"fmt"
"io"
"mime/multipart"
"os"
"path/filepath"
"strings"
"time"
)

// UploadsDir is where the admin editor's uploads (image fields and OG images)
// are written, and where /uploads/ serves from, relative to the working
// directory. It is under content/, the persistent volume in production.
// static/ is part of the image and is replaced on every deploy, which lost
// these files until 7.4.6. A variable so the tests point it at a temp
// directory.
var UploadsDir = "content/uploads"

// legacyUploadsDir is where the editor wrote uploads before 7.4.6. A deploy
// can still carry files there in the image; MigrateLegacyUploads copies them
// into UploadsDir at startup.
var legacyUploadsDir = "static/uploads"

// saveUpload writes an uploaded file to UploadsDir as <unix nanos>_<prefix><name>
// and returns the URL it is served at.
func saveUpload(file multipart.File, prefix, name string) (string, error) {
if err := os.MkdirAll(UploadsDir, 0755); err != nil {
return "", err
}
filename := fmt.Sprintf("%d_%s%s", time.Now().UnixNano(), prefix, name)
path := filepath.Join(UploadsDir, filename)
dst, err := os.Create(path)
if err != nil {
return "", err
}
_, err = io.Copy(dst, file)
if cerr := dst.Close(); err == nil {
err = cerr
}
if err != nil {
os.Remove(path)
return "", err
}
return "/uploads/" + filename, nil
}

// MigrateLegacyUploads copies the files in the pre-7.4.6 uploads directory
// that UploadsDir does not have yet, so uploads an image still carries keep
// being served. It never overwrites a file and returns how many it copied.
func MigrateLegacyUploads() (int, error) {
entries, err := os.ReadDir(legacyUploadsDir)
if os.IsNotExist(err) {
return 0, nil
}
if err != nil {
return 0, err
}
if err := os.MkdirAll(UploadsDir, 0755); err != nil {
return 0, err
}
copied := 0
for _, e := range entries {
if !e.Type().IsRegular() || strings.HasPrefix(e.Name(), ".") {
continue
}
dst := filepath.Join(UploadsDir, e.Name())
if _, err := os.Lstat(dst); err == nil {
continue
}
if err := copyNewFile(filepath.Join(legacyUploadsDir, e.Name()), dst); err != nil {
return copied, fmt.Errorf("copy %s: %w", e.Name(), err)
}
copied++
}
return copied, nil
}

// copyNewFile copies src to dst, failing if dst already exists.
func copyNewFile(src, dst string) error {
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()
out, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0644)
if err != nil {
return err
}
_, err = io.Copy(out, in)
if cerr := out.Close(); err == nil {
err = cerr
}
if err != nil {
os.Remove(dst)
}
return err
}
143 changes: 143 additions & 0 deletions internal/handlers/uploads_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
package handlers

import (
"bytes"
"context"
"net/url"
"os"
"path/filepath"
"strings"
"testing"
"time"

"go.mongodb.org/mongo-driver/bson"
)

// memFile is an in-memory multipart.File.
type memFile struct{ *bytes.Reader }

func (memFile) Close() error { return nil }

// useUploadDirs points UploadsDir and legacyUploadsDir at fresh temp
// directories for one test.
func useUploadDirs(t *testing.T) (uploads, legacy string) {
t.Helper()
oldUploads, oldLegacy := UploadsDir, legacyUploadsDir
t.Cleanup(func() { UploadsDir, legacyUploadsDir = oldUploads, oldLegacy })
base := t.TempDir()
UploadsDir = filepath.Join(base, "content", "uploads") // created on first use
legacyUploadsDir = filepath.Join(base, "static", "uploads")
return UploadsDir, legacyUploadsDir
}

func TestSaveUpload_WritesToUploadsDir(t *testing.T) {
uploads, _ := useUploadDirs(t)

got, err := saveUpload(memFile{bytes.NewReader([]byte("png bytes"))}, "og_", "card.png")
if err != nil {
t.Fatalf("saveUpload: %v", err)
}
if !strings.HasPrefix(got, "/uploads/") || !strings.HasSuffix(got, "_og_card.png") {
t.Fatalf("URL = %q, want /uploads/<nanos>_og_card.png", got)
}
data, err := os.ReadFile(filepath.Join(uploads, strings.TrimPrefix(got, "/uploads/")))
if err != nil || string(data) != "png bytes" {
t.Fatalf("stored file = %q, %v; want the uploaded bytes", data, err)
}
}

func TestSaveUpload_ErrorWhenDirCannotBeCreated(t *testing.T) {
useUploadDirs(t)
blocker := filepath.Join(t.TempDir(), "file")
if err := os.WriteFile(blocker, nil, 0644); err != nil {
t.Fatal(err)
}
UploadsDir = filepath.Join(blocker, "uploads") // under a regular file

if got, err := saveUpload(memFile{bytes.NewReader([]byte("x"))}, "", "a.png"); err == nil {
t.Fatalf("saveUpload = %q, nil; want an error", got)
}
}

func TestMigrateLegacyUploads_CopiesOnlyMissingFiles(t *testing.T) {
uploads, legacy := useUploadDirs(t)
for _, dir := range []string{uploads, filepath.Join(legacy, "sub")} {
if err := os.MkdirAll(dir, 0755); err != nil {
t.Fatal(err)
}
}
write := func(path, body string) {
t.Helper()
if err := os.WriteFile(path, []byte(body), 0644); err != nil {
t.Fatal(err)
}
}
write(filepath.Join(legacy, "1_avatar.png"), "avatar")
write(filepath.Join(legacy, "2_og_card.png"), "old card")
write(filepath.Join(legacy, ".gitkeep"), "")
write(filepath.Join(legacy, "sub", "3_nested.png"), "nested")
write(filepath.Join(uploads, "2_og_card.png"), "newer card")

n, err := MigrateLegacyUploads()
if err != nil || n != 1 {
t.Fatalf("MigrateLegacyUploads = %d, %v; want 1, nil", n, err)
}
if data, _ := os.ReadFile(filepath.Join(uploads, "1_avatar.png")); string(data) != "avatar" {
t.Errorf("1_avatar.png = %q, want copied", data)
}
if data, _ := os.ReadFile(filepath.Join(uploads, "2_og_card.png")); string(data) != "newer card" {
t.Errorf("2_og_card.png = %q, want the volume's copy left alone", data)
}
for _, name := range []string{".gitkeep", "sub"} {
if _, err := os.Lstat(filepath.Join(uploads, name)); err == nil {
t.Errorf("%s was copied; want dotfiles and folders skipped", name)
}
}

if n, err := MigrateLegacyUploads(); err != nil || n != 0 {
t.Errorf("second run = %d, %v; want 0, nil", n, err)
}
}

func TestMigrateLegacyUploads_NoLegacyDir(t *testing.T) {
useUploadDirs(t)
if n, err := MigrateLegacyUploads(); err != nil || n != 0 {
t.Fatalf("MigrateLegacyUploads = %d, %v; want 0, nil", n, err)
}
}

// TestCreateContent_OGImageUploadGoesToUploadsDir checks the admin editor
// stores an uploaded OG image under UploadsDir (the persistent volume in
// production), not under static/.
func TestCreateContent_OGImageUploadGoesToUploadsDir(t *testing.T) {
h, cleanup := newTestHandler(t)
defer cleanup()
db := testDB(t)
uploads, _ := useUploadDirs(t)
tmplID := seedTemplate(t, db, "Upload Page", "upload-page")

form := url.Values{
"template_id": {tmplID.Hex()},
"title": {"OG Upload Page"},
"slug": {"og-upload-page"},
}
if rr := postMultipart(t, h.CreateContent, "og_image", "card.png", "png bytes", form, nil); rr.Code >= 500 {
t.Fatalf("CreateContent: %d (%s)", rr.Code, rr.Body.String())
}

var doc struct {
OGImage string `bson:"og_image"`
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := db.FindOne(ctx, "content", bson.M{"slug": "og-upload-page"}, &doc); err != nil {
t.Fatalf("content not created: %v", err)
}
if !strings.HasPrefix(doc.OGImage, "/uploads/") {
t.Fatalf("og_image = %q, want an /uploads/ URL", doc.OGImage)
}
data, err := os.ReadFile(filepath.Join(uploads, strings.TrimPrefix(doc.OGImage, "/uploads/")))
if err != nil || string(data) != "png bytes" {
t.Fatalf("uploaded file under UploadsDir = %q, %v; want the uploaded bytes", data, err)
}
}
2 changes: 1 addition & 1 deletion manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"manifest_version": "0.3",
"name": "lightcms",
"display_name": "LightCMS",
"version": "7.4.5",
"version": "7.4.6",
"description": "AI-native content management system with 130 MCP tools for creating, managing, and publishing website content through natural language.",
"long_description": "LightCMS is a lightweight, AI-native, open-source CMS built with Go and MongoDB. The MCP server provides complete website management: create, edit and publish pages; templates, snippets, assets and themes; redirects, folders and collections; multi-pair search and replace; version history with rollback; agent sandbox sessions (fork-based, human-reviewed merges) and session rollback; content approvals and comments; imports, scheduling and webhooks; maintenance reports; IndexNow and SEO & AI settings (AI crawler policy, feeds, Markdown copies); and AI traffic analytics. Connects via REST API with API key authentication — no direct database access needed.",
"author": {
Expand Down
Loading