agent

package
v1.7.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 27, 2026 License: MIT Imports: 21 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ContentHandler

type ContentHandler struct {
	// contains filtered or unexported fields
}

ContentHandler exposes the Bearer-authenticated agent content endpoints. It reuses the existing ContentService (which already validates custom fields and fires plugin hooks) — it never duplicates that logic.

func NewContentHandler

func NewContentHandler(s ContentService, systemFields SystemFieldResolver, logger *util.Logger) *ContentHandler

NewContentHandler constructs a ContentHandler backed by the given content service. systemFields resolves admin-managed system fields per post type so the authoring endpoints can reject (not silently drop) agent-supplied system-field keys; a nil resolver disables that check. A nil logger degrades to a discard sink so the handler is safe to construct in any context (mirrors NewAPIKeyHandler/NewAPIKeyAuthMiddleware).

func (*ContentHandler) Create

func (h *ContentHandler) Create(w http.ResponseWriter, r *http.Request)

Create handles POST /api/v1/content. It maps the streamlined agent payload onto a contentdomain.CreateContentRequest (reusing the same validation + plugin hook path as the admin surface) and returns the created content in the envelope.

func (*ContentHandler) Delete

func (h *ContentHandler) Delete(w http.ResponseWriter, r *http.Request)

Delete handles DELETE /api/v1/content/{id}. It pre-fetches for the ownership check (404 on not-found or not-owned-per-role) then delegates to the existing ContentService.DeleteContent. A successful delete returns 204 No Content; a subsequent GET returns 404 (the service hard-deletes for Admins and scoped-deletes otherwise).

func (*ContentHandler) Get

Get handles GET /api/v1/content/{id}. It returns the content in the envelope, or 404 NOT_FOUND when it does not exist OR the caller is not allowed to see it.

Visibility scoping (review fix for the GET IDOR): the underlying GetByID returns content regardless of owner/status, so the handler enforces "published OR owned by the requesting user" and otherwise returns NOT_FOUND (never FORBIDDEN, so existence is not disclosed to unauthorized callers). This mirrors the ownership pattern the admin Update/DeleteContent paths use (existing.UserID != userID).

func (*ContentHandler) List

List handles GET /api/v1/content. It returns the caller's own content (any status — drafts + published) in newest-first order using opaque keyset (cursor) pagination, each item projected via the ContentProjection whitelist. hasMore/nextCursor are computed by requesting limit+1 rows; nextCursor is the opaque token of the last item on the current page and is only present when there is another page.

Optional filters: ?tag=foo&tag=bar (AND-of-tags), ?language=en, ?status=draft|published, ?post_type=post, ?author=alice (admin only — non-admins get 403), ?search=foo (min 2 chars). All filters AND with the cursor pagination. The agent v1 surface scopes to the caller's own content; the author filter is meaningful only for admins because the agent handler never expands the userID scope (admin still sees their own content here — use the admin surface for cross-user listings).

func (*ContentHandler) Publish

func (h *ContentHandler) Publish(w http.ResponseWriter, r *http.Request)

Publish handles POST /api/v1/content/{id}/publish. It delegates to ContentService.Publish so ownership, the draft→published transition, SEO auto-generation, and the AfterPublish hook fire through the same domain path the Update endpoint uses. The endpoint accepts an empty body and is idempotent: publishing an already-published post returns 200 with the current projection, fires no hook, runs no SEO regen.

A non-admin caller must be the owner; otherwise 404 (never 403, so existence is not disclosed). An admin can publish another user's content. Validation and persistence errors map to the same error envelope the other endpoints use.

func (*ContentHandler) SetSystemFields added in v0.2.0

func (h *ContentHandler) SetSystemFields(w http.ResponseWriter, r *http.Request)

SetSystemFields handles PUT /api/v1/content/{id}/system-fields. System fields are admin-managed metadata (e.g. editorial_status, internal_notes), so this endpoint is admin-only: a non-admin caller gets 403. It mirrors the browser admin's system-fields endpoint but lives in the Bearer/agent realm so the CLI can set them with an admin API key. It delegates to ContentService.SetSystemFields, which validates each key against the post type's system-field schema and each value's type — an unknown key returns ErrUnknownSystemFieldKey and a bad value returns ErrSystemFieldValidation (both → 400 VALIDATION_ERROR via handleError).

func (*ContentHandler) Unpublish

func (h *ContentHandler) Unpublish(w http.ResponseWriter, r *http.Request)

Unpublish handles POST /api/v1/content/{id}/unpublish. It delegates to ContentService.Unpublish so the status flip persists through the same domain path. The endpoint accepts an empty body and is idempotent: unpublishing an already-draft post returns 200 with the current projection, fires no hook, runs no SEO regen. Unpublish never fires the AfterPublish hook (the hook is wired to the draft→published edge only).

Same ownership/role contract as Publish: 404 (not 403) for non-admin non-owners; admins can unpublish anyone's content.

func (*ContentHandler) Update

func (h *ContentHandler) Update(w http.ResponseWriter, r *http.Request)

Update handles PUT /api/v1/content/{id}. It pre-fetches the existing content for an ownership check (404 NOT_FOUND when the caller is neither owner nor Admin — existence is never disclosed) and then delegates to the existing ContentService.Update so hooks + custom-field validation run through the same domain path the admin uses. format=tiptap stores the body unchanged; markdown is rejected (Story 2.4).

v1 settable on update: title, body, format, postType, customFields, isPublished, tags, language. Server-managed (preserved from the existing item): SEO metadata (metaDescription, ogTitle, ogDescription), allowComments, translationGroupId.

func (*ContentHandler) WithIFrameHosts added in v0.10.0

func (h *ContentHandler) WithIFrameHosts(hosts ...string) *ContentHandler

WithIFrameHosts attaches the sanitizer's iframe host allowlist (derived from the CSP frame-src directive) so HTML-format content keeps allowed embeds on the write path. When not called, iframes are stripped on save. Returns the receiver for chaining at construction time.

type ContentProjection

type ContentProjection struct {
	ID            int            `json:"id"`
	Title         string         `json:"title"`
	Slug          string         `json:"slug"`
	Body          string         `json:"body"`
	Format        string         `json:"format,omitempty"`
	Status        string         `json:"status"`
	PostType      string         `json:"postType,omitempty"`
	Language      string         `json:"language,omitempty"`
	Tags          []string       `json:"tags,omitempty"`
	FeaturedImage string         `json:"featuredImage,omitempty"`
	CustomFields  map[string]any `json:"customFields,omitempty"`
	Author        string         `json:"author,omitempty"`
	CreatedAt     time.Time      `json:"createdAt"`
	UpdatedAt     time.Time      `json:"updatedAt"`
}

ContentProjection is the public, whitelisted view of a content item returned by the agent create/get endpoints. It deliberately excludes internal/admin-only fields the raw contentdomain.Content carries (the numeric owner id, updatedBy/updatedByUsername, translationGroupId, SEO metadata, allowComments) so the programmatic API surface does not over-disclose to integrators or — via IDOR — to other tenants. Format rides along so API clients can round-trip the stored body without guessing how to interpret it.

type ContentRequest

type ContentRequest struct {
	Title              string         `json:"title"`
	Body               string         `json:"body"`
	Format             string         `json:"format,omitempty"`
	PostType           string         `json:"postType,omitempty"`
	Slug               string         `json:"slug,omitempty"`
	FeaturedImage      *string        `json:"featuredImage,omitempty"`
	CustomFields       map[string]any `json:"customFields,omitempty"`
	IsPublished        bool           `json:"isPublished,omitempty"`
	Tags               []string       `json:"tags,omitempty"`
	Language           string         `json:"language,omitempty"`
	TranslationGroupID *int           `json:"translationGroupId,omitempty"`
}

ContentRequest is the agent authoring payload for POST /api/v1/content. It maps onto the existing contentdomain.CreateContentRequest (see the mapping table in the story Dev Notes). It is intentionally separate from the admin handler's CreateContentRequest so the agent contract can evolve independently.

Field notes:

  • Body is the canonical content. For Format "tiptap" (default) it is the Tiptap JSON string, stored unchanged. The service validates/sanitizes it.
  • Format defaults to "tiptap" when omitted. "markdown" is reserved for Story 2.4 (Markdown→Tiptap conversion) and is rejected with VALIDATION_ERROR here.
  • Slug is admin-only and honored only at create time: an admin may supply a custom slug (validated and uniqueness-checked per language by the service), while a non-admin's slug is dropped and the service auto-generates one from the title. The slug is immutable after creation — it can never be changed via Update (changing it would break the public URL and harm SEO).
  • IsPublished true maps to StatusPublished; false/omitted maps to StatusDraft.
  • Tags are normalized via contentdomain.ValidateTags; an invalid tag returns VALIDATION_ERROR from the server.
  • Language must be in the server's configured languages (config.toml [languages] list); an unknown code returns VALIDATION_ERROR (ErrInvalidLanguage). The CLI cannot pre-validate this and forwards the value as-given so the server is the single source of truth.
  • TranslationGroupID (the CLI's --translation-of <id>) links the new item to an existing one's translation group. The server validates the id exists (ErrTranslationGroupNotFound → VALIDATION_ERROR) and stores it; a non-nil value is what makes the public language switcher appear on the page.

type ContentResponse

type ContentResponse struct {
	Content ContentProjection `json:"content"`
}

ContentResponse wraps a projected content item for the agent create/get responses. Envelope body: {"data":{"content":{...}}}.

func NewContentResponse

func NewContentResponse(c *contentdomain.Content) ContentResponse

NewContentResponse builds a ContentResponse projecting the given content entity to its public fields. A nil entity yields an empty projection (defensive — the service contract returns a non-nil content on success).

type ContentService

type ContentService interface {
	Create(ctx context.Context, principal kernel.Principal, req contentdomain.CreateContentRequest) (*contentdomain.Content, error)
	GetByID(ctx context.Context, id int) (*contentdomain.Content, error)
	ListByCursor(ctx context.Context, userID int, limit int, beforeID int, filters contentdomain.ContentFilters) ([]*contentdomain.Content, error)
	Update(ctx context.Context, id int, principal kernel.Principal, req contentservice.UpdateContentRequest) (*contentdomain.Content, error)
	DeleteContent(ctx context.Context, id int, principal kernel.Principal) error
	Publish(ctx context.Context, id int, principal kernel.Principal) (*contentdomain.Content, error)
	Unpublish(ctx context.Context, id int, principal kernel.Principal) (*contentdomain.Content, error)
	SetSystemFields(ctx context.Context, contentID int, principal kernel.Principal, systemFields map[string]any) (*contentdomain.Content, error)
}

ContentService is the narrow slice of the content domain service the agent handlers depend on. *contentservice.Service satisfies it. Declaring it locally — instead of depending on the admin handler's wider ContentServiceInterface — keeps the agent surface independent and makes the dependency explicit. It is exported so mockery can generate an exported constructor callable from the package's *_test files (CLAUDE.md mandates *_test packages, which cannot reach an unexported mock).

type SystemFieldResolver added in v0.2.0

type SystemFieldResolver interface {
	GetSystemFieldsByPostType(slug string) ([]customfield.FieldSchema, error)
}

SystemFieldResolver resolves the admin-managed system field schemas for a post type. *posttype.Service satisfies it. It is exported so mockery can generate a mock reachable from the *_test package (CLAUDE.md mandates *_test packages). It is optional: a nil resolver disables the system-field-rejection check on create/update (the service still strips such keys afterwards).

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL