diff --git a/README.md b/README.md index c9d9df0..7c35ab2 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ WinterCMS theme components such as `journalPost` and `journalPosts` are a later - **Search.** With a configured search engine and `search_use_typesense` on, published posts are kept in the Typesense collection `golem15_journal_posts` after every committed save, and `GET /posts?search=` answers in relevance order. Otherwise search is a SQL `ILIKE`. `?fields=suggest` serves short rows for a search box, and `journal:reindex` fills the index. See [search](#search). - **Public HTTP.** Anonymous GET `/_journal/api/v1/posts`, `/posts/{slug}`, `/categories`, `/tags`, `/rss`, `/authors/{author}`, and `/authors/{author}/posts`. `/posts/{slug}` finds the post by its default-locale slug, then by its slug in the request locale (the router's locale, from `Accept-Language` or the translate plugin's resolver), then by id, so a translated slug resolves. Writes under the same prefix require a cabana backend JWT (`aud=backend`) or a personal admin API token (`g15_…`) whose scope covers the Journal. - **Record events.** Post writes through the admin fire the framework's record events (`pact.RecordSaved`, `pact.RecordDeleted`) after the commit, like every admin controller. The `/_journal/api/v1` post routes, which MCP tools call, fire the same events with `cabana.EmitRecordSaved` and `cabana.EmitRecordDeleted`: `POST /posts` a RecordSaved with `Created`, `PUT /posts/{id}` a RecordSaved whose changes hold the post's changed columns and each submitted translation that changed (a translated slug per locale), `DELETE /posts/{id}` a RecordDeleted. A tag `POST` or `PUT` creates from a name in `tags` fires its own RecordSaved with `Created`. `POST` and `PUT` write the row, its categories, tags and translations in one transaction and fire the event after it commits, so a write that fails part-way changes nothing and fires nothing. Their `Controller` is empty, as they do not go through an admin form. Another plugin (an SEO plugin creating redirects, a search indexer) therefore hears about a slug changed over MCP without importing the Journal. -- **MCP tools.** `journal.Plugin.MCP` declares eleven tools and one prompt for the framework's MCP endpoint (pier, a binary built with the `summercms_mcp` tag): `journal_list_posts`, `journal_show_post`, `journal_list_categories`, `journal_list_tags`, `journal_create_post`, `journal_update_post`, `journal_delete_post`, `journal_get_settings`, `journal_update_settings`, `journal_fix_headings`, `journal_set_image_alt` and the prompt `journal_draft_post`. Each runs the matching `/_journal/api/v1` route as the backend account linked to the MCP user (guard `backend`) and is listed only when that account has `golem15.journal.access_posts` (`golem15.journal.manage_settings` for the settings and `fix_headings` tools); the route checks its own permissions on every call. See [MCP tools](#mcp-tools). +- **MCP tools.** `journal.Plugin.MCP` declares thirteen tools and one prompt for the framework's MCP endpoint (pier, a binary built with the `summercms_mcp` tag): `journal_list_posts`, `journal_show_post`, `journal_list_categories`, `journal_show_category`, `journal_update_category`, `journal_list_tags`, `journal_create_post`, `journal_update_post`, `journal_delete_post`, `journal_get_settings`, `journal_update_settings`, `journal_fix_headings`, `journal_set_image_alt` and the prompt `journal_draft_post`. Each runs the matching `/_journal/api/v1` route as the backend account linked to the MCP user (guard `backend`) and is listed only when that account has `golem15.journal.access_posts` (`golem15.journal.access_categories` for `update_category`, `golem15.journal.manage_settings` for the settings and `fix_headings` tools); the route checks its own permissions on every call. See [MCP tools](#mcp-tools). - **Author slug.** Plugin migration adds `backend_users.golem15_bloghub_author_slug`. The column stores the public author slug that the author routes resolve. - **Import and export.** `journal:export-posts` and `journal:import-posts` write and read one JSON file per post. The Posts list toolbar exposes the same actions to administrators with `golem15.journal.access_import_export`. - **Phrasebooks.** Embedded `lang/en/lang.yaml` and `lang/pl/lang.yaml` hold plugin, journal, post, category, and tag UI strings. They are independent of model translation JSON. @@ -258,6 +258,8 @@ With the framework's MCP endpoint mounted (`summer.yaml` `build.tags: [summercms | `journal_list_posts` | `GET /_journal/api/v1/posts` | query `page`, `per_page`, `search`, `category`, `tag`, `author`, `published`, `sort` | | `journal_show_post` | `GET /_journal/api/v1/posts/{slug}` | `slug` | | `journal_list_categories` | `GET /_journal/api/v1/categories` | none | +| `journal_show_category` | `GET /_journal/api/v1/categories/{slug}` | `slug` (slug or numeric id) | +| `journal_update_category` | `PUT /_journal/api/v1/categories/{id}` | `id` and any of `name`, `slug`, `description`, `content` (sanitized HTML; `golem15.journal.access_categories`) | | `journal_list_tags` | `GET /_journal/api/v1/tags` | none | | `journal_create_post` | `POST /_journal/api/v1/posts` | `title`, `content`, optional `slug`, `excerpt`, `published`, `published_at`, `is_pinned`, `categories` (ids), `tags` (names) | | `journal_update_post` | `PUT /_journal/api/v1/posts/{id}` | `id` and any of the create fields; only the fields sent change | diff --git a/controllers/api/auth.go b/controllers/api/auth.go index 599de89..3091dc8 100644 --- a/controllers/api/auth.go +++ b/controllers/api/auth.go @@ -18,6 +18,7 @@ const ( errPublishPermission = "You do not have permission to publish posts" errEditPermission = "You do not have permission to edit this post" errPostNotFound = "Post not found" + errCategoryNotFound = "Category not found" errImageNotFound = "Image not found" errValidationFailed = "Validation failed" msgPostDeleted = "Post deleted" @@ -26,6 +27,7 @@ const ( permAccessPosts = "golem15.journal.access_posts" permAccessOtherPosts = "golem15.journal.access_other_posts" permAccessPublish = "golem15.journal.access_publish" + permAccessCategories = "golem15.journal.access_categories" journalCover = "golem15.journal.*" ) @@ -105,6 +107,14 @@ func requireAccessPosts(w http.ResponseWriter, pr *bouncer.Principal) bool { return true } +func requireAccessCategories(w http.ResponseWriter, pr *bouncer.Principal) bool { + if !cabana.Allows(pr, []string{permAccessCategories}) { + writeAPIError(w, http.StatusForbidden, errInsufficientPerms) + return false + } + return true +} + func gdb(app *backpack.App) (*gorm.DB, error) { if app == nil { return nil, errors.New("journal api: application is not configured") diff --git a/controllers/api/categories.go b/controllers/api/categories.go new file mode 100644 index 0000000..097335c --- /dev/null +++ b/controllers/api/categories.go @@ -0,0 +1,401 @@ +package api + +import ( + "context" + "net/http" + "strconv" + "strings" + "unicode/utf8" + + "git.golem15.com/golem15/sm-journal-plugin/classes" + "git.golem15.com/golem15/sm-journal-plugin/models" + translate "git.golem15.com/golem15/sm-translate-plugin/classes" + translatemodels "git.golem15.com/golem15/sm-translate-plugin/models" + "git.golem15.com/golem15/summercms/modules/backpack" + "git.golem15.com/golem15/summercms/modules/cabana" + "git.golem15.com/golem15/summercms/modules/cooler" + "git.golem15.com/golem15/summercms/modules/lagoon" + "git.golem15.com/golem15/summercms/modules/pact" + "git.golem15.com/golem15/summercms/modules/phrasebook" + "git.golem15.com/golem15/summercms/modules/towel" + "git.golem15.com/golem15/summercms/modules/wire" + "gorm.io/gorm" +) + +// ShowCategory is GET /_journal/api/v1/categories/{slug}. Resolves by default +// slug, then translated slug in the request locale, then numeric id. +func ShowCategory(app *backpack.App) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + db, err := gdb(app) + if err != nil { + writeAPIError(w, http.StatusInternalServerError, "Internal server error") + return + } + dbCtx := db.WithContext(r.Context()) + slug := strings.TrimSpace(r.PathValue("slug")) + cat, err := findCategoryBySlugOrID(dbCtx, slug, requestLocale(r)) + if err != nil || cat == nil { + writeAPIError(w, http.StatusNotFound, errCategoryNotFound) + return + } + h1ToH2 := classes.EffectiveH1ToH2(r.Context(), dbCtx, appConfig(app)) + wire.WriteJSON(w, http.StatusOK, map[string]any{"data": serializeCategoryDetail(dbCtx, cat, h1ToH2)}) + } +} + +// UpdateCategory is PUT /_journal/api/v1/categories/{id}. Requires a backend +// principal with golem15.journal.access_categories. Only submitted fields +// change: name, slug, description, content (sanitized through the app's +// EmbedRegistry, with H1→H2 conversion while the H1 setting is on, blank +// stored as NULL), and optional translations. +func UpdateCategory(app *backpack.App) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + r, pr, ok := requireBackendPrincipal(app, w, r) + if !ok { + return + } + if !requireAccessCategories(w, pr) { + return + } + db, err := gdb(app) + if err != nil { + writeAPIError(w, http.StatusInternalServerError, "Internal server error") + return + } + dbCtx := db.WithContext(r.Context()) + cat, err := findCategoryByID(dbCtx, r.PathValue("id")) + if err != nil || cat == nil { + writeAPIError(w, http.StatusNotFound, errCategoryNotFound) + return + } + body, err := readJSONObject(r) + if err != nil { + writeAPIError(w, http.StatusBadRequest, errValidationFailed) + return + } + before := snapshotCategory(cat) + verrs := applyCategoryUpdate(dbCtx, app, cat, body) + if verrs != nil { + writeValidation(w, verrs) + return + } + h1Count := 0 + err = lagoon.Transaction(r.Context(), db, func(ctx context.Context, tx *gorm.DB) error { + if _, has := body["content"]; has && cat.Content != nil { + if classes.EffectiveH1ToH2(ctx, tx, appConfig(app)) { + converted, n := classes.ConvertH1(*cat.Content) + if n > 0 { + cat.Content = &converted + h1Count = n + } + } + } + if err := tx.Save(cat).Error; err != nil { + return err + } + if raw, has := body["translations"]; has { + if err := syncCategoryTranslations(ctx, tx, cat, raw); err != nil { + return err + } + } + cabana.EmitRecordSaved(ctx, app, tx, categorySavedEvent(ctx, before, cat)) + return nil + }) + if err != nil { + writeAPIError(w, http.StatusInternalServerError, "Internal server error") + return + } + cooler.PurgeSiteCacheAfterCommit(r.Context(), nil, cooler.SiteCacheFromApp(app), "category", cat.Slug) + h1ToH2 := classes.EffectiveH1ToH2(r.Context(), dbCtx, appConfig(app)) + payload := map[string]any{"data": serializeCategoryDetail(dbCtx, cat, h1ToH2)} + if h1Count > 0 { + msg := classes.EditorH1ConvertedCategory + if app != nil { + if tr, ok := app.Lookup[*phrasebook.Translator](); ok && tr != nil { + msg = tr.Choice(r.Context(), classes.EditorH1ConvertedCategory, h1Count, nil) + } + } + payload["notices"] = []map[string]any{{"message": msg, "count": h1Count}} + } + wire.WriteJSON(w, http.StatusOK, payload) + } +} + +func findCategoryBySlugOrID(db *gorm.DB, slug, locale string) (*models.Category, error) { + if slug == "" { + return nil, gorm.ErrRecordNotFound + } + var cat models.Category + if err := db.Where("slug = ?", slug).Take(&cat).Error; err == nil { + return &cat, nil + } + if locale != "" { + var ids []string + err := db.Session(&gorm.Session{NewDB: true, Context: db.Statement.Context}). + Table(translatemodels.Index{}.TableName()). + Where("model_type = ? AND locale = ? AND item = ? AND value = ?", models.Category{}.MorphName(), locale, "slug", slug). + Order("id ASC"). + Pluck("model_id", &ids).Error + if err == nil && len(ids) > 0 { + var translated models.Category + if err := db.Where("CAST(id AS TEXT) IN ?", ids).Order("id ASC").Take(&translated).Error; err == nil { + return &translated, nil + } + } + } + if ctypeDigit(slug) { + return findCategoryByID(db, slug) + } + return nil, gorm.ErrRecordNotFound +} + +func findCategoryByID(db *gorm.DB, raw string) (*models.Category, error) { + id, err := strconv.ParseUint(strings.TrimSpace(raw), 10, 64) + if err != nil || id == 0 { + return nil, gorm.ErrRecordNotFound + } + var cat models.Category + if err := db.Where("id = ?", id).Take(&cat).Error; err != nil { + return nil, err + } + return &cat, nil +} + +func categorySlugTaken(db *gorm.DB, slug string, exceptID uint) bool { + q := db.Model(&models.Category{}).Where("slug = ?", slug) + if exceptID > 0 { + q = q.Where("id <> ?", exceptID) + } + var n int64 + _ = q.Count(&n).Error + return n > 0 +} + +func applyCategoryUpdate(db *gorm.DB, app *backpack.App, cat *models.Category, body map[string]any) map[string][]string { + errs := map[string][]string{} + if _, has := body["name"]; has { + name := strings.TrimSpace(asString(body["name"])) + if name == "" { + errs["name"] = []string{"The name field is required."} + } else if utf8.RuneCountInString(name) > 255 { + errs["name"] = []string{"The name may not be greater than 255 characters."} + } else { + cat.Name = name + } + } + if _, has := body["slug"]; has { + slug := strings.TrimSpace(asString(body["slug"])) + if slug == "" { + errs["slug"] = []string{"The slug field is required."} + } else if !slugPattern.MatchString(slug) { + errs["slug"] = []string{"The slug format is invalid."} + } else if categorySlugTaken(db, slug, cat.ID) { + errs["slug"] = []string{"The slug has already been taken."} + } else { + cat.Slug = slug + } + } + if _, has := body["description"]; has { + if body["description"] == nil { + cat.Description = nil + } else { + desc := strings.TrimSpace(asString(body["description"])) + if desc == "" { + cat.Description = nil + } else { + cat.Description = &desc + } + } + } + if _, has := body["content"]; has { + if body["content"] == nil { + cat.Content = nil + } else { + raw := asString(body["content"]) + if strings.TrimSpace(raw) == "" { + cat.Content = nil + } else { + clean := classes.EmbedRegistryFrom(app).SanitizeHTML(raw) + if strings.TrimSpace(clean) == "" { + cat.Content = nil + } else { + cat.Content = &clean + } + } + } + } + if transErr := validateCategoryTranslations(body["translations"]); transErr != nil { + errs["translations"] = []string{transErr.Error()} + } + if len(errs) > 0 { + return errs + } + return nil +} + +func validateCategoryTranslations(raw any) error { + if raw == nil { + return nil + } + m, ok := raw.(map[string]any) + if !ok { + return errInvalidCategoryTranslations + } + for _, v := range m { + attrs, ok := v.(map[string]any) + if !ok { + continue + } + if slug := strings.TrimSpace(asString(attrs["slug"])); slug != "" && !slugPattern.MatchString(slug) { + return errInvalidTranslationSlug + } + if name := asString(attrs["name"]); utf8.RuneCountInString(name) > 255 { + return errInvalidTranslationName + } + } + return nil +} + +var ( + errInvalidCategoryTranslations = categoryValidationError("The translations must be an object.") + errInvalidTranslationSlug = categoryValidationError("The translations slug format is invalid.") + errInvalidTranslationName = categoryValidationError("The translations name may not be greater than 255 characters.") +) + +type categoryValidationError string + +func (e categoryValidationError) Error() string { return string(e) } + +func syncCategoryTranslations(ctx context.Context, db *gorm.DB, cat *models.Category, raw any) error { + m, ok := raw.(map[string]any) + if !ok { + return nil + } + for locale, v := range m { + attrs, ok := v.(map[string]any) + if !ok { + continue + } + for _, field := range []string{"name", "slug", "description"} { + if val, has := attrs[field]; has && val != nil { + if err := translate.SetTranslated(ctx, db, cat, field, locale, val); err != nil { + return err + } + } + } + } + return nil +} + +func serializeCategoryDetail(db *gorm.DB, c *models.Category, h1ToH2 bool) map[string]any { + counts := publishedPostCounts(db, "golem15_journal_posts_categories", "category_id") + var desc, content, parent, depth any + if c.Description != nil { + desc = *c.Description + } + if c.Content != nil { + content = *c.Content + } + if c.ParentID != nil { + parent = *c.ParentID + } + if c.NestDepth != nil { + depth = *c.NestDepth + } + return map[string]any{ + "id": c.ID, + "name": c.Name, + "slug": c.Slug, + "description": desc, + "content": content, + "parent_id": parent, + "nest_depth": depth, + "post_count": counts[c.ID], + "content_h1_to_h2": h1ToH2, + "translations": categoryTranslationsOf(db, c), + } +} + +func categoryTranslationsOf(db *gorm.DB, c *models.Category) any { + if db == nil || c == nil || c.ID == 0 { + return []any{} + } + var locales []struct { + Code string + IsDefault bool + } + if err := db.Table("golem15_translate_locales"). + Select("code, is_default"). + Where("is_enabled = ?", true). + Find(&locales).Error; err != nil { + return []any{} + } + ctx := db.Statement.Context + if ctx == nil { + ctx = context.Background() + } + out := map[string]any{} + for _, loc := range locales { + if loc.IsDefault { + continue + } + attrs := map[string]any{} + for _, field := range []string{"name", "slug", "description"} { + val, ok, err := translate.TranslatedExact(ctx, db, c, field, loc.Code) + if err != nil || !ok || val == nil { + continue + } + if strings.TrimSpace(asString(val)) == "" { + continue + } + attrs[field] = val + } + if len(attrs) > 0 { + out[loc.Code] = attrs + } + } + if len(out) == 0 { + return []any{} + } + return out +} + +type categorySnapshot struct { + name string + slug string + description any + content any +} + +func snapshotCategory(c *models.Category) categorySnapshot { + return categorySnapshot{ + name: c.Name, + slug: c.Slug, + description: derefValue(c.Description), + content: derefValue(c.Content), + } +} + +func categorySavedEvent(ctx context.Context, before categorySnapshot, c *models.Category) pact.RecordSaved { + changes := []pact.RecordChange{} + if before.name != c.Name { + changes = append(changes, pact.RecordChange{Attribute: "name", Old: before.name, New: c.Name}) + } + if before.slug != c.Slug { + changes = append(changes, pact.RecordChange{Attribute: "slug", Old: before.slug, New: c.Slug}) + } + if nextDesc := derefValue(c.Description); !sameEventValue(before.description, nextDesc) { + changes = append(changes, pact.RecordChange{Attribute: "description", Old: before.description, New: nextDesc}) + } + if nextContent := derefValue(c.Content); !sameEventValue(before.content, nextContent) { + changes = append(changes, pact.RecordChange{Attribute: "content", Old: before.content, New: nextContent}) + } + locale, _ := towel.Locale(ctx) + return pact.RecordSaved{ + Model: c.MorphName(), + ID: strconv.FormatUint(uint64(c.ID), 10), + Locale: locale, + Created: false, + Changes: changes, + } +} diff --git a/controllers/api/categories_test.go b/controllers/api/categories_test.go index 96617be..2db6170 100644 --- a/controllers/api/categories_test.go +++ b/controllers/api/categories_test.go @@ -1,62 +1,126 @@ package api import ( - "reflect" - "sort" + "context" + "net/http" + "net/http/httptest" + "strings" "testing" + "git.golem15.com/golem15/sm-journal-plugin/classes" "git.golem15.com/golem15/sm-journal-plugin/models" + "git.golem15.com/golem15/summercms/modules/backpack" + "git.golem15.com/golem15/summercms/modules/bouncer" ) -func sortedCategoryKeys(row map[string]any) []string { - keys := make([]string, 0, len(row)) - for k := range row { - keys = append(keys, k) - } - sort.Strings(keys) - return keys +func TestUpdateCategoryAuthAndPermissions(t *testing.T) { + app := backpack.New(nil) + handler := UpdateCategory(app) + + t.Run("unauthenticated returns 401", func(t *testing.T) { + req := httptest.NewRequest(http.MethodPut, "/_journal/api/v1/categories/1", strings.NewReader(`{"name":"News"}`)) + req.SetPathValue("id", "1") + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, req) + if rec.Code != http.StatusUnauthorized { + t.Fatalf("status = %d, want 401; body = %s", rec.Code, rec.Body.String()) + } + }) + + t.Run("dispatched backend principal without access_categories returns 403", func(t *testing.T) { + pr := &bouncer.Principal{ + ID: 7, + Backend: true, + PermissionGrants: map[string]bool{permAccessPosts: true}, + } + req := httptest.NewRequest(http.MethodPut, "/_journal/api/v1/categories/1", strings.NewReader(`{"name":"News"}`)) + req.SetPathValue("id", "1") + req = req.WithContext(bouncer.WithDispatch(req.Context(), &bouncer.Dispatch{ + Principal: pr, + Guards: []string{"backend"}, + })) + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, req) + if rec.Code != http.StatusForbidden { + t.Fatalf("status = %d, want 403; body = %s", rec.Code, rec.Body.String()) + } + }) } -func TestSerializeCategoryNodeContent(t *testing.T) { - html := "

Acme

\n

Pillar copy

\n" - var parentID uint = 1 - root := models.Category{ID: 1, Name: "News", Slug: "news", Content: &html} - child := models.Category{ID: 2, Name: "Quiet", Slug: "quiet", ParentID: &parentID} - byParent := map[uint][]models.Category{1: {child}} - counts := map[uint]int64{1: 2} - - row := serializeCategoryNode(&root, byParent, counts, true, true) - if row == nil { - t.Fatal("root row is nil") +func TestApplyCategoryUpdateSanitizationAndValidation(t *testing.T) { + app := backpack.New(nil) + reg := classes.NewEmbedRegistry() + if err := reg.Register(classes.EmbedProvider{ + Key: "viz", + Name: "Chart", + IDPattern: `^[a-z0-9-]+$`, + }); err != nil { + t.Fatal(err) } - if got, ok := row["content"].(string); !ok || got != html { - t.Fatalf("root content = %#v, want %q", row["content"], html) - } - wantRoot := []string{"children", "content", "content_h1_to_h2", "description", "id", "name", "nest_depth", "parent_id", "post_count", "slug"} - if got := sortedCategoryKeys(row); !reflect.DeepEqual(got, wantRoot) { - t.Fatalf("root keys = %v, want %v", got, wantRoot) - } - kids, ok := row["children"].([]map[string]any) - if !ok || len(kids) != 1 { - t.Fatalf("children = %#v, want one row", row["children"]) - } - v, present := kids[0]["content"] - if !present || v != nil { - t.Fatalf("child content = %#v (present %v), want nil", v, present) - } - wantChild := []string{"content", "content_h1_to_h2", "description", "id", "name", "nest_depth", "parent_id", "post_count", "slug"} - if got := sortedCategoryKeys(kids[0]); !reflect.DeepEqual(got, wantChild) { - t.Fatalf("child keys = %v, want %v", got, wantChild) + if err := app.Publish(reg); err != nil { + t.Fatal(err) } - listed := serializeCategoryNode(&root, byParent, counts, false, true) - if listed == nil { - t.Fatal("root omitted without include_empty") - } - if _, has := listed["children"]; has { - t.Fatalf("empty child listed without include_empty: %#v", listed["children"]) - } - if got, ok := listed["content"].(string); !ok || got != html { - t.Fatalf("root content without include_empty = %#v, want %q", listed["content"], html) - } + t.Run("sanitizes HTML content with app EmbedRegistry and strips XSS", func(t *testing.T) { + cat := &models.Category{ID: 4, Name: "Old", Slug: "old"} + before := snapshotCategory(cat) + verrs := applyCategoryUpdate(nil, app, cat, map[string]any{ + "name": "New Name", + "description": " Short summary ", + "content": `

Intro

Chart
`, + }) + if verrs != nil { + t.Fatalf("unexpected validation errors: %v", verrs) + } + if cat.Name != "New Name" { + t.Fatalf("Name = %q, want New Name", cat.Name) + } + if cat.Description == nil || *cat.Description != "Short summary" { + t.Fatalf("Description = %v, want Short summary", cat.Description) + } + if cat.Content == nil { + t.Fatal("Content is nil") + } + if strings.Contains(*cat.Content, "