feat(journal): add category show/update API routes and MCP tools

This commit is contained in:
Jakub Zych
2026-11-28 15:05:45 +01:00
parent a047d4284f
commit 331b80af09
8 changed files with 580 additions and 58 deletions

View File

@@ -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). - **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. - **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. - **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. - **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`. - **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. - **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_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_show_post` | `GET /_journal/api/v1/posts/{slug}` | `slug` |
| `journal_list_categories` | `GET /_journal/api/v1/categories` | none | | `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_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_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 | | `journal_update_post` | `PUT /_journal/api/v1/posts/{id}` | `id` and any of the create fields; only the fields sent change |

View File

@@ -18,6 +18,7 @@ const (
errPublishPermission = "You do not have permission to publish posts" errPublishPermission = "You do not have permission to publish posts"
errEditPermission = "You do not have permission to edit this post" errEditPermission = "You do not have permission to edit this post"
errPostNotFound = "Post not found" errPostNotFound = "Post not found"
errCategoryNotFound = "Category not found"
errImageNotFound = "Image not found" errImageNotFound = "Image not found"
errValidationFailed = "Validation failed" errValidationFailed = "Validation failed"
msgPostDeleted = "Post deleted" msgPostDeleted = "Post deleted"
@@ -26,6 +27,7 @@ const (
permAccessPosts = "golem15.journal.access_posts" permAccessPosts = "golem15.journal.access_posts"
permAccessOtherPosts = "golem15.journal.access_other_posts" permAccessOtherPosts = "golem15.journal.access_other_posts"
permAccessPublish = "golem15.journal.access_publish" permAccessPublish = "golem15.journal.access_publish"
permAccessCategories = "golem15.journal.access_categories"
journalCover = "golem15.journal.*" journalCover = "golem15.journal.*"
) )
@@ -105,6 +107,14 @@ func requireAccessPosts(w http.ResponseWriter, pr *bouncer.Principal) bool {
return true 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) { func gdb(app *backpack.App) (*gorm.DB, error) {
if app == nil { if app == nil {
return nil, errors.New("journal api: application is not configured") return nil, errors.New("journal api: application is not configured")

View File

@@ -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,
}
}

View File

@@ -1,62 +1,126 @@
package api package api
import ( import (
"reflect" "context"
"sort" "net/http"
"net/http/httptest"
"strings"
"testing" "testing"
"git.golem15.com/golem15/sm-journal-plugin/classes"
"git.golem15.com/golem15/sm-journal-plugin/models" "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 { func TestUpdateCategoryAuthAndPermissions(t *testing.T) {
keys := make([]string, 0, len(row)) app := backpack.New(nil)
for k := range row { handler := UpdateCategory(app)
keys = append(keys, k)
} t.Run("unauthenticated returns 401", func(t *testing.T) {
sort.Strings(keys) req := httptest.NewRequest(http.MethodPut, "/_journal/api/v1/categories/1", strings.NewReader(`{"name":"News"}`))
return keys 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) { func TestApplyCategoryUpdateSanitizationAndValidation(t *testing.T) {
html := "<h2>Acme</h2>\n<p>Pillar copy</p>\n" app := backpack.New(nil)
var parentID uint = 1 reg := classes.NewEmbedRegistry()
root := models.Category{ID: 1, Name: "News", Slug: "news", Content: &html} if err := reg.Register(classes.EmbedProvider{
child := models.Category{ID: 2, Name: "Quiet", Slug: "quiet", ParentID: &parentID} Key: "viz",
byParent := map[uint][]models.Category{1: {child}} Name: "Chart",
counts := map[uint]int64{1: 2} IDPattern: `^[a-z0-9-]+$`,
}); err != nil {
row := serializeCategoryNode(&root, byParent, counts, true, true) t.Fatal(err)
if row == nil {
t.Fatal("root row is nil")
} }
if got, ok := row["content"].(string); !ok || got != html { if err := app.Publish(reg); err != nil {
t.Fatalf("root content = %#v, want %q", row["content"], html) t.Fatal(err)
}
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)
} }
listed := serializeCategoryNode(&root, byParent, counts, false, true) t.Run("sanitizes HTML content with app EmbedRegistry and strips XSS", func(t *testing.T) {
if listed == nil { cat := &models.Category{ID: 4, Name: "Old", Slug: "old"}
t.Fatal("root omitted without include_empty") before := snapshotCategory(cat)
} verrs := applyCategoryUpdate(nil, app, cat, map[string]any{
if _, has := listed["children"]; has { "name": "New Name",
t.Fatalf("empty child listed without include_empty: %#v", listed["children"]) "description": " Short summary ",
} "content": `<h2>Intro</h2><script>alert(1)</script><figure data-embed="viz" data-id="chart-1"><img src="/media/abc/c.webp" alt="Chart"></figure>`,
if got, ok := listed["content"].(string); !ok || got != html { })
t.Fatalf("root content without include_empty = %#v, want %q", listed["content"], html) 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, "<script") {
t.Fatalf("XSS survived sanitization: %q", *cat.Content)
}
if !strings.Contains(*cat.Content, `data-embed="viz"`) || !strings.Contains(*cat.Content, `data-id="chart-1"`) {
t.Fatalf("registered custom embed lost: %q", *cat.Content)
}
ev := categorySavedEvent(context.Background(), before, cat)
if ev.Model != cat.MorphName() || ev.ID != "4" || ev.Created {
t.Fatalf("unexpected event header: %+v", ev)
}
if len(ev.Changes) != 3 {
t.Fatalf("expected 3 changed attributes (name, description, content), got %+v", ev.Changes)
}
})
t.Run("blank or null content and description clear fields to nil", func(t *testing.T) {
desc := "Old desc"
body := "<p>Old body</p>"
cat := &models.Category{ID: 4, Name: "News", Slug: "news", Description: &desc, Content: &body}
verrs := applyCategoryUpdate(nil, app, cat, map[string]any{
"description": " ",
"content": " \n\t ",
})
if verrs != nil {
t.Fatalf("unexpected validation errors: %v", verrs)
}
if cat.Description != nil || cat.Content != nil {
t.Fatalf("expected nil description & content, got desc=%v content=%v", cat.Description, cat.Content)
}
})
t.Run("rejects empty name and invalid slug format", func(t *testing.T) {
cat := &models.Category{ID: 4, Name: "News", Slug: "news"}
verrs := applyCategoryUpdate(nil, app, cat, map[string]any{
"name": " ",
"slug": "bad slug!",
})
if verrs == nil || len(verrs["name"]) == 0 || len(verrs["slug"]) == 0 {
t.Fatalf("expected name and slug validation errors, got %v", verrs)
}
})
} }

40
mcp.go
View File

@@ -15,10 +15,13 @@ var _ pact.HasMCP = (*Plugin)(nil)
// to the MCP user (the routes resolve the backend principal themselves). // to the MCP user (the routes resolve the backend principal themselves).
const mcpGuard = "backend" const mcpGuard = "backend"
// mcpAccessPosts is the permission every Journal tool and the prompt are // mcpAccessPosts is the permission every Journal post tool and the prompt are
// listed with (the routes check it, and access_publish, themselves). // listed with (the routes check it, and access_publish, themselves).
const mcpAccessPosts = "golem15.journal.access_posts" const mcpAccessPosts = "golem15.journal.access_posts"
// mcpAccessCategories is the permission for editing Journal categories.
const mcpAccessCategories = "golem15.journal.access_categories"
// mcpListPostsInput is the query of GET /_journal/api/v1/posts. // mcpListPostsInput is the query of GET /_journal/api/v1/posts.
type mcpListPostsInput struct { type mcpListPostsInput struct {
Page int `json:"page,omitempty" query:"page" jsonschema:"the page number, from 1"` Page int `json:"page,omitempty" query:"page" jsonschema:"the page number, from 1"`
@@ -69,6 +72,21 @@ type mcpDeletePostInput struct {
ID uint `json:"id" path:"id" jsonschema:"the post id"` ID uint `json:"id" path:"id" jsonschema:"the post id"`
} }
// mcpShowCategoryInput names one category by slug or id.
type mcpShowCategoryInput struct {
Slug string `json:"slug" path:"slug" jsonschema:"the category slug or numeric id"`
}
// mcpUpdateCategoryInput is PUT /_journal/api/v1/categories/{id}: only the
// fields sent are changed.
type mcpUpdateCategoryInput struct {
ID uint `json:"id" path:"id" jsonschema:"the category id"`
Name *string `json:"name,omitempty" jsonschema:"the category name"`
Slug *string `json:"slug,omitempty" jsonschema:"the URL slug"`
Description *string `json:"description,omitempty" jsonschema:"a short category description; empty clears it"`
Content *string `json:"content,omitempty" jsonschema:"the category page HTML body (sanitized with the Journal policy, H1 converted to H2 while the H1 setting is on); empty clears it"`
}
// mcpManageSettings is the permission of the settings and heading tools. // mcpManageSettings is the permission of the settings and heading tools.
const mcpManageSettings = "golem15.journal.manage_settings" const mcpManageSettings = "golem15.journal.manage_settings"
@@ -155,6 +173,26 @@ func (p *Plugin) MCP() pact.MCP {
Input: struct{}{}, Input: struct{}{},
Permissions: []string{mcpAccessPosts}, Permissions: []string{mcpAccessPosts},
}, },
{
Name: "show_category",
Title: "Show category",
Description: "Shows one Journal category by slug or id, including its description, HTML content, and translations.",
Guard: mcpGuard,
Method: http.MethodGet,
Path: "/_journal/api/v1/categories/{slug}",
Input: mcpShowCategoryInput{},
Permissions: []string{mcpAccessPosts},
},
{
Name: "update_category",
Title: "Update category",
Description: "Changes the fields sent of one Journal category by id (name, slug, description, and sanitized HTML content).",
Guard: mcpGuard,
Method: http.MethodPut,
Path: "/_journal/api/v1/categories/{id}",
Input: mcpUpdateCategoryInput{},
Permissions: []string{mcpAccessCategories},
},
{ {
Name: "list_tags", Name: "list_tags",
Title: "List tags", Title: "List tags",

View File

@@ -28,10 +28,12 @@ func TestJournalMCPSmoke(t *testing.T) {
var _ pact.HasMCP = (*journal.Plugin)(nil) var _ pact.HasMCP = (*journal.Plugin)(nil)
decl := (&journal.Plugin{}).MCP() decl := (&journal.Plugin{}).MCP()
wantTools := []string{"list_posts", "show_post", "list_categories", "list_tags", "create_post", "update_post", "delete_post", wantTools := []string{"list_posts", "show_post", "list_categories", "show_category", "update_category", "list_tags", "create_post", "update_post", "delete_post",
"get_settings", "update_settings", "fix_headings", "set_image_alt"} "get_settings", "update_settings", "fix_headings", "set_image_alt"}
// The settings and heading tools need manage_settings (33-02, D-10). // The settings and heading tools need manage_settings (33-02, D-10);
// update_category needs access_categories.
manageSettings := map[string]bool{"get_settings": true, "update_settings": true, "fix_headings": true} manageSettings := map[string]bool{"get_settings": true, "update_settings": true, "fix_headings": true}
accessCategories := map[string]bool{"update_category": true}
destructive := map[string]bool{"delete_post": true, "set_image_alt": true} destructive := map[string]bool{"delete_post": true, "set_image_alt": true}
var names []string var names []string
for _, tool := range decl.Tools { for _, tool := range decl.Tools {
@@ -39,6 +41,8 @@ func TestJournalMCPSmoke(t *testing.T) {
want := []string{"golem15.journal.access_posts"} want := []string{"golem15.journal.access_posts"}
if manageSettings[tool.Name] { if manageSettings[tool.Name] {
want = []string{"golem15.journal.manage_settings"} want = []string{"golem15.journal.manage_settings"}
} else if accessCategories[tool.Name] {
want = []string{"golem15.journal.access_categories"}
} }
if tool.Guard != "backend" || !slices.Equal(tool.Permissions, want) { if tool.Guard != "backend" || !slices.Equal(tool.Permissions, want) {
t.Errorf("tool %s guard %q permissions %v, want backend and %v", tool.Name, tool.Guard, tool.Permissions, want) t.Errorf("tool %s guard %q permissions %v, want backend and %v", tool.Name, tool.Guard, tool.Permissions, want)

View File

@@ -25,12 +25,13 @@ import (
var ( var (
postBodyKeys = []string{"categories", "content", "excerpt", "is_pinned", "metadata", "published", "published_at", "slug", "sources", "tags", "title", "translations"} postBodyKeys = []string{"categories", "content", "excerpt", "is_pinned", "metadata", "published", "published_at", "slug", "sources", "tags", "title", "translations"}
postQueryKeys = []string{"author", "category", "include_empty", "page", "per_page", "pinned_first", "published", "search", "sort", "tag"} postQueryKeys = []string{"author", "category", "include_empty", "page", "per_page", "pinned_first", "published", "search", "sort", "tag"}
// maintenanceBodyKeys are the body keys of the settings and content // maintenanceBodyKeys are the body keys of the settings, category, and
// fix routes, by path. // content fix routes, by path.
maintenanceBodyKeys = map[string][]string{ maintenanceBodyKeys = map[string][]string{
"/_journal/api/v1/settings": models.Settings{}.Fillable(), "/_journal/api/v1/categories/{id}": {"name", "slug", "description", "content", "translations"},
"/_journal/api/v1/fix-headings": {"dry_run"}, "/_journal/api/v1/settings": models.Settings{}.Fillable(),
"/_journal/api/v1/images/alt": {"dry_run", "changes"}, "/_journal/api/v1/fix-headings": {"dry_run"},
"/_journal/api/v1/images/alt": {"dry_run", "changes"},
} }
) )
@@ -110,7 +111,7 @@ func TestJournalMCP(t *testing.T) {
if !ok { if !ok {
t.Fatal("pier was not mounted") t.Fatal("pier was not mounted")
} }
want := []string{"journal_create_post", "journal_delete_post", "journal_fix_headings", "journal_get_settings", "journal_list_categories", "journal_list_posts", "journal_list_tags", "journal_set_image_alt", "journal_show_post", "journal_update_post", "journal_update_settings"} want := []string{"journal_create_post", "journal_delete_post", "journal_fix_headings", "journal_get_settings", "journal_list_categories", "journal_list_posts", "journal_list_tags", "journal_set_image_alt", "journal_show_category", "journal_show_post", "journal_update_category", "journal_update_post", "journal_update_settings"}
if got := p.ToolNames(); !slices.Equal(got, want) { if got := p.ToolNames(); !slices.Equal(got, want) {
t.Fatalf("compiled tools %v, want %v", got, want) t.Fatalf("compiled tools %v, want %v", got, want)
} }

View File

@@ -17,6 +17,7 @@ func (p *Plugin) Routes(r pact.Router) error {
g.Get("/posts/{slug}", apicontrollers.Show(p.app)) g.Get("/posts/{slug}", apicontrollers.Show(p.app))
g.Where("slug", `[a-z0-9][a-z0-9\-/]*`) g.Where("slug", `[a-z0-9][a-z0-9\-/]*`)
g.Get("/categories", apicontrollers.Categories(p.app)) g.Get("/categories", apicontrollers.Categories(p.app))
g.Get("/categories/{slug}", apicontrollers.ShowCategory(p.app))
g.Get("/tags", apicontrollers.Tags(p.app)) g.Get("/tags", apicontrollers.Tags(p.app))
g.Get("/rss", apicontrollers.RSS(p.app)) g.Get("/rss", apicontrollers.RSS(p.app))
g.Get("/authors/{author}", apicontrollers.AuthorShow(p.app)) g.Get("/authors/{author}", apicontrollers.AuthorShow(p.app))
@@ -27,6 +28,7 @@ func (p *Plugin) Routes(r pact.Router) error {
g.Post("/posts", apicontrollers.Store(p.app)) g.Post("/posts", apicontrollers.Store(p.app))
g.Put("/posts/{id}", apicontrollers.Update(p.app)) g.Put("/posts/{id}", apicontrollers.Update(p.app))
g.Delete("/posts/{id}", apicontrollers.Destroy(p.app)) g.Delete("/posts/{id}", apicontrollers.Destroy(p.app))
g.Put("/categories/{id}", apicontrollers.UpdateCategory(p.app))
g.Post("/posts/{id}/featured-images", apicontrollers.UploadFeaturedImage(p.app)) g.Post("/posts/{id}/featured-images", apicontrollers.UploadFeaturedImage(p.app))
g.Delete("/posts/{id}/featured-images/{fileId}", apicontrollers.DeleteFeaturedImage(p.app)) g.Delete("/posts/{id}/featured-images/{fileId}", apicontrollers.DeleteFeaturedImage(p.app))
g.Where("id", `[0-9]+`) g.Where("id", `[0-9]+`)