feat(32.2-01): per-item rows and item actions on My account contributions

- pact: AccountContribution.Items/ItemActions/ItemsEmpty, AccountItem,
  AccountItemAction, AccountItemActionInput, ErrAccountItemNotFound
- cabana: the list sends items (null without Items), permitted item actions
  and the empty line; boot refuses item actions without Items
- cabana: POST {api}/account/contribution-items/{name}/{item}/actions/{action}
  runs only for an item the administrator's own Items listed, in a transaction
  (path outside /account/contributions/ to avoid a ServeMux overlap)
- swag views; admin.json and schema.d.ts regenerated; route inventories
This commit is contained in:
Jakub Zych
2026-11-21 00:22:13 +01:00
parent 97d7ee0586
commit 3f7ce6020d
16 changed files with 706 additions and 30 deletions

View File

@@ -51,9 +51,27 @@
"type": "string"
},
"error": {
"description": "Error is true when the section's status or one of its actions could\nnot be loaded (the plugin's Status or an action's Applies failed; that\naction is left out); the other sections are answered as usual. Absent\notherwise.",
"description": "Error is true when the section's status, its items or one of its\nactions could not be loaded (the plugin's Status, Items or an action's\nApplies failed; that action is left out); the other sections are\nanswered as usual. Absent otherwise.",
"type": "boolean"
},
"item_actions": {
"description": "ItemActions are the buttons of each row the admin holds the\npermissions for; null for a section without Items. Confirm may hold\n:title, which the admin fills with the row's title.",
"items": {
"$ref": "#/components/schemas/cabana.AccountContributionActionView"
},
"type": "array"
},
"items": {
"description": "Items are the signed-in admin's rows of a section with an Items\nfunction: an array, possibly empty. null for a section without Items\nand when the section's Items failed.",
"items": {
"$ref": "#/components/schemas/cabana.AccountItemView"
},
"type": "array"
},
"items_empty": {
"description": "ItemsEmpty is the translated line for a section with no rows; \"\" means\nthe admin's own empty line.",
"type": "string"
},
"label": {
"type": "string"
},
@@ -68,12 +86,41 @@
"required": [
"actions",
"description",
"item_actions",
"items",
"items_empty",
"label",
"name",
"status"
],
"type": "object"
},
"cabana.AccountItemView": {
"properties": {
"id": {
"type": "string"
},
"meta": {
"items": {
"type": "string"
},
"type": "array"
},
"subtitle": {
"type": "string"
},
"title": {
"type": "string"
}
},
"required": [
"id",
"meta",
"subtitle",
"title"
],
"type": "object"
},
"cabana.AdminAPIToken": {
"properties": {
"created_at": {
@@ -3805,6 +3852,101 @@
]
}
},
"/account/contribution-items/{name}/{item}/actions/{action}": {
"post": {
"description": "Runs one item action of a contributed section on one of the signed-in admin's rows. The action's permissions are checked (403); an item the section's Items does not list for this admin, or one that is gone, is 404. The answer is the action's message and an optional URL to open. Personal API tokens are refused (403 interactive_only).",
"parameters": [
{
"description": "Section name",
"in": "path",
"name": "name",
"required": true,
"schema": {
"type": "string"
}
},
{
"description": "Item id",
"in": "path",
"name": "item",
"required": true,
"schema": {
"type": "string"
}
},
{
"description": "Item action name",
"in": "path",
"name": "action",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/cabana.Envelope-cabana_AccountActionResultView"
}
}
},
"description": "OK"
},
"401": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/cabana.ErrorEnvelope"
}
}
},
"description": "Unauthorized"
},
"403": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/cabana.ErrorEnvelope"
}
}
},
"description": "Forbidden"
},
"404": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/cabana.ErrorEnvelope"
}
}
},
"description": "Not Found"
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/cabana.ErrorEnvelope"
}
}
},
"description": "Unprocessable Entity"
}
},
"security": [
{
"BackendBearer": []
}
],
"summary": "Run a My account item action",
"tags": [
"admin"
]
}
},
"/account/contributions": {
"get": {
"description": "Lists the sections plugins contribute to the signed-in admin's My account page: label, description, the status for this admin and the actions they may run that apply to them. Empty when no plugin contributes. Personal API tokens are refused (403 interactive_only).",

View File

@@ -210,6 +210,88 @@ export interface paths {
patch?: never;
trace?: never;
};
"/account/contribution-items/{name}/{item}/actions/{action}": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get?: never;
put?: never;
/**
* Run a My account item action
* @description Runs one item action of a contributed section on one of the signed-in admin's rows. The action's permissions are checked (403); an item the section's Items does not list for this admin, or one that is gone, is 404. The answer is the action's message and an optional URL to open. Personal API tokens are refused (403 interactive_only).
*/
post: {
parameters: {
query?: never;
header?: never;
path: {
/** @description Section name */
name: string;
/** @description Item id */
item: string;
/** @description Item action name */
action: string;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["cabana.Envelope-cabana_AccountActionResultView"];
};
};
/** @description Unauthorized */
401: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["cabana.ErrorEnvelope"];
};
};
/** @description Forbidden */
403: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["cabana.ErrorEnvelope"];
};
};
/** @description Not Found */
404: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["cabana.ErrorEnvelope"];
};
};
/** @description Unprocessable Entity */
422: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["cabana.ErrorEnvelope"];
};
};
};
};
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/account/contributions": {
parameters: {
query?: never;
@@ -6200,12 +6282,29 @@ export interface components {
actions: components["schemas"]["cabana.AccountContributionActionView"][];
description: string;
/**
* @description Error is true when the section's status or one of its actions could
* not be loaded (the plugin's Status or an action's Applies failed; that
* action is left out); the other sections are answered as usual. Absent
* otherwise.
* @description Error is true when the section's status, its items or one of its
* actions could not be loaded (the plugin's Status, Items or an action's
* Applies failed; that action is left out); the other sections are
* answered as usual. Absent otherwise.
*/
error?: boolean;
/**
* @description ItemActions are the buttons of each row the admin holds the
* permissions for; null for a section without Items. Confirm may hold
* :title, which the admin fills with the row's title.
*/
item_actions: components["schemas"]["cabana.AccountContributionActionView"][];
/**
* @description Items are the signed-in admin's rows of a section with an Items
* function: an array, possibly empty. null for a section without Items
* and when the section's Items failed.
*/
items: components["schemas"]["cabana.AccountItemView"][];
/**
* @description ItemsEmpty is the translated line for a section with no rows; "" means
* the admin's own empty line.
*/
items_empty: string;
label: string;
name: string;
/**
@@ -6214,6 +6313,12 @@ export interface components {
*/
status: string;
};
"cabana.AccountItemView": {
id: string;
meta: string[];
subtitle: string;
title: string;
};
"cabana.AdminAPIToken": {
created_at: string;
expired: boolean;

View File

@@ -156,6 +156,8 @@ Every signed-in administrator can edit their own profile on the My account scree
- **Plugin sections:** a plugin can add its own card below the API tokens, for something only the signed-in administrator does for themselves, such as linking their site account. The plugin implements `pact.HasAccountContributions` and returns `pact.AccountContribution` entries: a name, a label and description, an optional status line computed for the administrator, and buttons (`pact.AccountAction`) with an optional confirmation (danger variant included), extra permissions and an `Applies` rule. The SPA loads them from `GET <prefix>/api/v1/account/contributions` and runs a button through `POST <prefix>/api/v1/account/contributions/{name}/actions/{action}`, which calls the action's `Run` with the signed-in administrator's id inside a transaction (`cabana.TxFromContext`) and shows the returned message; a returned URL is opened in a new tab and shown as a link. Only an absolute `http`/`https` URL or a same-origin path is passed on; the admin drops anything else. A section whose status fails to load is still listed, marked `error: true`, and My account shows it with an error line; an action whose `Applies` fails is left out and marks its section the same way, so a missing button is explained. The other sections are unaffected. Both routes refuse personal API tokens like the rest of My account, and a page without contributing plugins is unchanged.
A section can also list rows that belong to the signed-in administrator, such as connected agents: `pact.AccountContribution.Items` answers them (`pact.AccountItem`: an id, a title, an optional subtitle and meta lines), `pact.AccountContribution.ItemsEmpty` is the line shown when there are none, and `pact.AccountContribution.ItemActions` are the buttons of every row (`pact.AccountItemAction`; a `Confirm` text may hold `:title`, which the admin replaces with the row's title). The list carries `items` (an array, possibly empty), `item_actions` (those the administrator holds the permissions for) and `items_empty`; a section without `Items` sends `items` as null and looks as before. A row button posts to `POST <prefix>/api/v1/account/contribution-items/{name}/{item}/actions/{action}`: 404 for an unknown section or action, 403 without the action's permissions, and 404 when the section's `Items` does not list that item for the signed-in administrator, so nobody can act on another administrator's row by guessing its id. `Run` then gets the administrator's id and the item id inside a transaction; a row that is gone meanwhile answers `pact.ErrAccountItemNotFound` and the route 404.
Plugins that show an administrator, such as an author box, read the subtitle with `cabana.BackendUser.Subtitle` and the picture with `cabana.BackendUserAvatar`, which returns the avatar file (or nil) for an administrator id.
## Managing administrators

View File

@@ -90,7 +90,7 @@ A WinterCMS plugin overrides `register*` methods of `PluginBase`. A SummerCMS pl
| `pact.HasFrontendPermissions` | Frontend permission codes (`pact.FrontendPermission`) a route's permission middleware checks, offered in the user plugin's permission editors. |
| `pact.HasAdminControllers` | Admin controllers built from `fields.yaml` and `columns.yaml`. |
| `pact.HasAdminActionExtensions` | Record actions added to any admin controller by ID (`pact.AdminActionExtension`); a `pact.AdminRecordAction` with a `Prompt` asks the administrator for one text value first and receives it as `pact.AdminRecordActionInput.Value`. |
| `pact.HasAccountContributions` | Sections with a status line and buttons on the administrator's My account page (`pact.AccountContribution`, `pact.AccountAction`), run for the signed-in administrator only. |
| `pact.HasAccountContributions` | Sections with a status line and buttons on the administrator's My account page (`pact.AccountContribution`, `pact.AccountAction`), run for the signed-in administrator only. A section may also list the administrator's rows (`pact.AccountContribution.Items` answering `pact.AccountItem` values, with `pact.AccountContribution.ItemsEmpty` for none) and give each row buttons (`pact.AccountItemAction`, whose `Confirm` may hold `:title`, the row's title); a row button runs only on a row that administrator's own `Items` listed, and its `Run` answers `pact.ErrAccountItemNotFound` for a row that is gone. |
| `pact.HasMCP` | MCP tools and prompts (`pact.MCP`, `pact.MCPTool`, `pact.MCPPrompt`) bound to the plugin's own token-guarded routes, served by the framework's opt-in [MCP endpoint](../services/mcp.md). |
| `pact.HasModels` | The plugin's GORM models. No framework package reads it yet. |

File diff suppressed because one or more lines are too long

View File

@@ -24,17 +24,19 @@ type accountContributionCatalog struct {
// compiledAccountContribution is one contributed section with its owner.
type compiledAccountContribution struct {
pluginID string
section pact.AccountContribution
actions map[string]pact.AccountAction
pluginID string
section pact.AccountContribution
actions map[string]pact.AccountAction
itemActions map[string]pact.AccountItemAction
}
// compileAccountContributions collects pact.HasAccountContributions from
// plugins into reg, in activation order. Every failure stops boot with a
// message naming the plugin and the section: a name that is not an
// identifier, a name another plugin already contributed, an empty label, an
// action whose name is not an identifier or repeats within the section, a
// nil Run or an empty action label.
// action or item action whose name is not an identifier or repeats within
// the section, a nil Run, an empty action label, or item actions without an
// Items func.
func compileAccountContributions(reg *Registry, plugins []party.Plugin) error {
if reg == nil {
return fmt.Errorf("cabana: registry is nil")
@@ -60,7 +62,7 @@ func compileAccountContributions(reg *Registry, plugins []party.Plugin) error {
if strings.TrimSpace(section.Label) == "" {
return fmt.Errorf("%s: it needs a label", prefix)
}
compiled := &compiledAccountContribution{pluginID: pluginID, section: section, actions: map[string]pact.AccountAction{}}
compiled := &compiledAccountContribution{pluginID: pluginID, section: section, actions: map[string]pact.AccountAction{}, itemActions: map[string]pact.AccountItemAction{}}
for _, action := range section.Actions {
if !identifier(action.Name) {
return fmt.Errorf("%s: action name %q is not an identifier", prefix, action.Name)
@@ -76,6 +78,24 @@ func compileAccountContributions(reg *Registry, plugins []party.Plugin) error {
}
compiled.actions[action.Name] = action
}
if len(section.ItemActions) > 0 && section.Items == nil {
return fmt.Errorf("%s: it has item actions but no Items function", prefix)
}
for _, action := range section.ItemActions {
if !identifier(action.Name) {
return fmt.Errorf("%s: item action name %q is not an identifier", prefix, action.Name)
}
if _, dup := compiled.itemActions[action.Name]; dup {
return fmt.Errorf("%s: duplicate item action %q", prefix, action.Name)
}
if action.Run == nil {
return fmt.Errorf("%s: item action %q has no Run function", prefix, action.Name)
}
if strings.TrimSpace(action.Label) == "" {
return fmt.Errorf("%s: item action %q needs a label", prefix, action.Name)
}
compiled.itemActions[action.Name] = action
}
cat.ordered = append(cat.ordered, *compiled)
cat.byName[section.Name] = &cat.ordered[len(cat.ordered)-1]
}
@@ -91,10 +111,13 @@ func compileAccountContributions(reg *Registry, plugins []party.Plugin) error {
// accountContributionsList serves GET /account/contributions: every
// contributed section with its status for the signed-in administrator and
// the actions they may run that apply to them, labels translated. A
// section whose Status fails is sent with Error set and no status, and an
// action whose Applies fails is left out and sets Error on its section (the
// admin sees why a button is missing), both logged: one plugin's error never
// answers 500 for the list.
// section with Items also carries the administrator's rows (an array,
// possibly empty), the item actions they hold the permissions for and the
// empty line; a section without Items sends items null. A section whose
// Status or Items fails is sent with Error set (no status, items null), and
// an action whose Applies fails is left out and sets Error on its section
// (the admin sees why a button is missing), all logged: one plugin's error
// never answers 500 for the list.
func (s *service) accountContributionsList(w http.ResponseWriter, r *http.Request) {
principal := accountPrincipal(w, r)
if principal == nil {
@@ -146,6 +169,34 @@ func (s *service) accountContributionsList(w http.ResponseWriter, r *http.Reques
Danger: action.Danger,
})
}
if item.section.Items != nil {
view.ItemsEmpty = translateKey(ctx, tr, item.section.ItemsEmpty)
view.ItemActions = []AccountContributionActionView{}
for _, action := range item.section.ItemActions {
if !Allows(principal, action.Permissions) {
continue
}
view.ItemActions = append(view.ItemActions, AccountContributionActionView{
Name: action.Name,
Label: translateKey(ctx, tr, action.Label),
Confirm: translateKey(ctx, tr, action.Confirm),
Danger: action.Danger,
})
}
rows, err := item.section.Items(ctx, principal.ID)
if err != nil {
// Items stay null and the section says so; the other
// sections are still answered.
moduleLog.ErrorContext(ctx, "cabana: account contribution items failed", "section", item.section.Name, "plugin", item.pluginID, "error", err)
view.Error = true
} else {
view.Items = make([]AccountItemView, 0, len(rows))
for _, row := range rows {
meta := append([]string{}, row.Meta...)
view.Items = append(view.Items, AccountItemView{ID: row.ID, Title: row.Title, Subtitle: row.Subtitle, Meta: meta})
}
}
}
out = append(out, view)
}
}
@@ -227,6 +278,94 @@ func (s *service) accountContributionAction(w http.ResponseWriter, r *http.Reque
}, nil)
}
// accountContributionItemAction serves
// POST /account/contribution-items/{name}/{item}/actions/{action}: an
// unknown section or item action is 404, a missing permission 403; then the
// section's Items is read for the signed-in administrator and an item ID it
// does not list is 404, so an administrator never acts on someone else's
// row; then Run runs inside a transaction carried by the context, as for
// section actions. pact.ErrAccountItemNotFound from Run is 404.
func (s *service) accountContributionItemAction(w http.ResponseWriter, r *http.Request) {
principal := accountPrincipal(w, r)
if principal == nil {
return
}
var item *compiledAccountContribution
if s.reg != nil && s.reg.accountContributions != nil {
item = s.reg.accountContributions.byName[r.PathValue("name")]
}
if item == nil || item.section.Items == nil {
WriteError(w, http.StatusNotFound, "not_found", msgNotFound)
return
}
action, ok := item.itemActions[r.PathValue("action")]
if !ok {
WriteError(w, http.StatusNotFound, "not_found", msgNotFound)
return
}
if !s.allowAction(w, r, action.Permissions) {
return
}
tr := s.translator()
ctx := towel.WithLocale(r.Context(), schemaLocale(r.Context(), tr))
itemID := r.PathValue("item")
listed := func(ctx context.Context) (bool, error) {
rows, err := item.section.Items(ctx, principal.ID)
if err != nil {
return false, err
}
for _, row := range rows {
if row.ID == itemID {
return true, nil
}
}
return false, nil
}
run := func(ctx context.Context) (pact.AccountActionResult, error) {
ok, err := listed(ctx)
if err != nil {
return pact.AccountActionResult{}, err
}
if !ok {
return pact.AccountActionResult{}, pact.ErrAccountItemNotFound
}
return action.Run(ctx, pact.AccountItemActionInput{AdminID: principal.ID, ItemID: itemID})
}
var result pact.AccountActionResult
var err error
if db, dbErr := s.db(); dbErr == nil {
err = lagoon.Transaction(ctx, db, func(ctx context.Context, tx *gorm.DB) error {
result, err = run(withTx(ctx, tx))
return err
})
} else {
result, err = run(ctx)
}
if errors.Is(err, pact.ErrAccountItemNotFound) {
WriteError(w, http.StatusNotFound, "not_found", msgNotFound)
return
}
if err != nil {
var stale actionConflict
var refused *ForbiddenError
var invalid *ValidationError
if !errors.As(err, &stale) && !errors.As(err, &refused) && !errors.As(err, &invalid) {
moduleLog.ErrorContext(ctx, "cabana: account contribution item action failed", "section", item.section.Name, "action", action.Name, "plugin", item.pluginID, "error", err)
}
writeCRUDError(w, localizeControllerError(ctx, tr, err))
return
}
moduleLog.InfoContext(ctx, "cabana: account contribution item action", "admin_id", principal.ID, "section", item.section.Name, "action", action.Name)
if result.URL != "" && !safeAccountActionURL(result.URL) {
moduleLog.ErrorContext(ctx, "cabana: account contribution item action answered a non-http URL", "section", item.section.Name, "action", action.Name, "plugin", item.pluginID)
result.URL = ""
}
WriteData(w, http.StatusOK, AccountActionResultView{
Message: translateKey(ctx, tr, result.Message),
URL: result.URL,
}, nil)
}
// safeAccountActionURL reports whether an account action's URL may be handed
// to the admin's browser, which renders it as a link and opens it: an
// absolute http or https URL with a host, or a same-origin relative path

View File

@@ -0,0 +1,170 @@
package cabana
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/bouncer"
"git.golem15.com/golem15/summercms/modules/pact"
"git.golem15.com/golem15/summercms/modules/party"
)
// TestAccountItemsSmoke covers per-item rows on My account contributions,
// on Postgres so item actions run in a real transaction: a section without
// Items still answers items null, a section with Items lists the
// administrator's rows and the item actions they may run, an item action on
// a listed id runs with the administrator and item ids inside a
// transaction, the same id posted by another administrator (whose Items
// list it not) is 404 without Run, Run answering pact.ErrAccountItemNotFound
// is 404, a missing permission is 403, and item actions without Items fail
// boot.
func TestAccountItemsSmoke(t *testing.T) {
gdb := consentGorm(t)
var mu sync.Mutex
type call struct {
admin uint
item string
tx bool
}
var calls []call
const adminA, adminB = 41, 42
rows := map[uint][]pact.AccountItem{
adminA: {
{ID: "c1", Title: "Agent one", Subtitle: "Full access", Meta: []string{"Connected 2026-11-20"}},
{ID: "gone", Title: "Agent two"},
},
}
revoke := pact.AccountItemAction{
Name: "revoke", Label: "acme::lang.revoke", Confirm: "Revoke :title?", Danger: true,
Run: func(ctx context.Context, in pact.AccountItemActionInput) (pact.AccountActionResult, error) {
_, tx := TxFromContext(ctx)
mu.Lock()
calls = append(calls, call{admin: in.AdminID, item: in.ItemID, tx: tx})
mu.Unlock()
if in.ItemID == "gone" {
return pact.AccountActionResult{}, pact.ErrAccountItemNotFound
}
return pact.AccountActionResult{Message: "acme::lang.revoked"}, nil
},
}
locked := pact.AccountItemAction{
Name: "rename", Label: "Rename", Permissions: []string{"acme.items.manage"},
Run: func(context.Context, pact.AccountItemActionInput) (pact.AccountActionResult, error) {
return pact.AccountActionResult{}, nil
},
}
sections := []pact.AccountContribution{
{Name: "plain", Label: "Plain section"},
{
Name: "connections", Label: "Connections", ItemsEmpty: "Nothing connected.",
Items: func(_ context.Context, adminID uint) ([]pact.AccountItem, error) {
return rows[adminID], nil
},
ItemActions: []pact.AccountItemAction{revoke, locked},
},
}
reg := &Registry{byID: map[string]*CompiledController{}}
if err := compileAccountContributions(reg, []party.Plugin{contributor{id: "acme.links", sections: sections}}); err != nil {
t.Fatal(err)
}
app := backpack.New(nil)
if err := app.Publish(gdb); err != nil {
t.Fatal(err)
}
svc := &service{app: app, reg: reg}
principal := func(id uint) *bouncer.Principal { return &bouncer.Principal{ID: id, Backend: true} }
list := func(p *bouncer.Principal) []map[string]any {
t.Helper()
req := httptest.NewRequest(http.MethodGet, "/account/contributions", nil)
req = req.WithContext(bouncer.WithUser(req.Context(), p))
rec := httptest.NewRecorder()
interactiveOnly(svc.accountContributionsList)(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("list = %d %s", rec.Code, rec.Body.String())
}
var body struct {
Data []map[string]any `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
return body.Data
}
act := func(p *bouncer.Principal, item, action string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodPost, "/account/contribution-items/connections/"+item+"/actions/"+action, strings.NewReader("{}"))
req.Header.Set("X-Requested-With", "XMLHttpRequest")
req.SetPathValue("name", "connections")
req.SetPathValue("item", item)
req.SetPathValue("action", action)
req = req.WithContext(bouncer.WithUser(req.Context(), p))
rec := httptest.NewRecorder()
interactiveOnly(requireAjax(svc.accountContributionItemAction))(rec, req)
return rec
}
data := list(principal(adminA))
if len(data) != 2 {
t.Fatalf("sections = %+v", data)
}
if items, ok := data[0]["items"]; !ok || items != nil || data[0]["item_actions"] != nil {
t.Fatalf("section without Items = %+v, want items null", data[0])
}
items, _ := data[1]["items"].([]any)
if len(items) != 2 {
t.Fatalf("items = %+v", data[1]["items"])
}
first, _ := items[0].(map[string]any)
if first["id"] != "c1" || first["title"] != "Agent one" || first["subtitle"] != "Full access" {
t.Fatalf("first item = %+v", first)
}
actions, _ := data[1]["item_actions"].([]any)
if len(actions) != 1 || actions[0].(map[string]any)["name"] != "revoke" || actions[0].(map[string]any)["confirm"] != "Revoke :title?" || data[1]["items_empty"] != "Nothing connected." {
t.Fatalf("item actions = %+v empty=%v", data[1]["item_actions"], data[1]["items_empty"])
}
// Admin B has no rows: an empty array, never null.
if dataB := list(principal(adminB)); dataB[1]["items"] == nil {
t.Fatalf("admin B items = %+v, want []", dataB[1])
}
if rec := act(principal(adminA), "c1", "revoke"); rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "acme::lang.revoked") {
t.Fatalf("revoke = %d %s", rec.Code, rec.Body.String())
}
if len(calls) != 1 || calls[0] != (call{admin: adminA, item: "c1", tx: true}) {
t.Fatalf("calls = %+v", calls)
}
// Admin B posts admin A's item id: 404 and Run is not called.
if rec := act(principal(adminB), "c1", "revoke"); rec.Code != http.StatusNotFound || len(calls) != 1 {
t.Fatalf("cross-admin = %d %s calls=%d", rec.Code, rec.Body.String(), len(calls))
}
// Run answering ErrAccountItemNotFound: 404.
if rec := act(principal(adminA), "gone", "revoke"); rec.Code != http.StatusNotFound || len(calls) != 2 {
t.Fatalf("gone item = %d %s calls=%d", rec.Code, rec.Body.String(), len(calls))
}
if rec := act(principal(adminA), "c1", "rename"); rec.Code != http.StatusForbidden {
t.Fatalf("missing permission = %d %s", rec.Code, rec.Body.String())
}
if rec := act(principal(adminA), "c1", "nope"); rec.Code != http.StatusNotFound {
t.Fatalf("unknown item action = %d %s", rec.Code, rec.Body.String())
}
// Boot refuses item actions without Items, and the other bad shapes.
for name, bad := range map[string]pact.AccountContribution{
"item actions without Items": {Name: "x", Label: "x", ItemActions: []pact.AccountItemAction{revoke}},
"bad item action name": {Name: "x", Label: "x", Items: sections[1].Items, ItemActions: []pact.AccountItemAction{{Name: "no!", Label: "x", Run: revoke.Run}}},
"duplicate item action": {Name: "x", Label: "x", Items: sections[1].Items, ItemActions: []pact.AccountItemAction{revoke, revoke}},
"nil item run": {Name: "x", Label: "x", Items: sections[1].Items, ItemActions: []pact.AccountItemAction{{Name: "a", Label: "x"}}},
"empty item label": {Name: "x", Label: "x", Items: sections[1].Items, ItemActions: []pact.AccountItemAction{{Name: "a", Run: revoke.Run}}},
} {
err := compileAccountContributions(&Registry{}, []party.Plugin{contributor{id: "acme.bad", sections: []pact.AccountContribution{bad}}})
if err == nil || !strings.HasPrefix(err.Error(), "cabana: plugin acme.bad contributes account section") {
t.Fatalf("%s: err = %v", name, err)
}
}
}

View File

@@ -341,11 +341,32 @@ type AccountContributionView struct {
// section has none or its status could not be loaded.
Status string `json:"status"`
Actions []AccountContributionActionView `json:"actions"`
// Error is true when the section's status or one of its actions could
// not be loaded (the plugin's Status or an action's Applies failed; that
// action is left out); the other sections are answered as usual. Absent
// otherwise.
// Error is true when the section's status, its items or one of its
// actions could not be loaded (the plugin's Status, Items or an action's
// Applies failed; that action is left out); the other sections are
// answered as usual. Absent otherwise.
Error bool `json:"error,omitempty"`
// Items are the signed-in admin's rows of a section with an Items
// function: an array, possibly empty. null for a section without Items
// and when the section's Items failed.
Items []AccountItemView `json:"items"`
// ItemActions are the buttons of each row the admin holds the
// permissions for; null for a section without Items. Confirm may hold
// :title, which the admin fills with the row's title.
ItemActions []AccountContributionActionView `json:"item_actions"`
// ItemsEmpty is the translated line for a section with no rows; "" means
// the admin's own empty line.
ItemsEmpty string `json:"items_empty"`
}
// AccountItemView is one row of a contributed section: the id the item
// action route names, a title, an optional subtitle and meta lines, all
// plain text.
type AccountItemView struct {
ID string `json:"id"`
Title string `json:"title"`
Subtitle string `json:"subtitle"`
Meta []string `json:"meta"`
}
// AccountContributionActionView is one button of a contributed section: the
@@ -478,6 +499,24 @@ func AdminMCPConsentShow() {}
// @Router /mcp/consent/{request} [post]
func AdminMCPConsentDecide() {}
// AdminAccountContributionItemAction documents POST /account/contribution-items/{name}/{item}/actions/{action}.
//
// @Summary Run a My account item action
// @Description Runs one item action of a contributed section on one of the signed-in admin's rows. The action's permissions are checked (403); an item the section's Items does not list for this admin, or one that is gone, is 404. The answer is the action's message and an optional URL to open. Personal API tokens are refused (403 interactive_only).
// @Tags admin
// @Produce json
// @Security BackendBearer
// @Param name path string true "Section name"
// @Param item path string true "Item id"
// @Param action path string true "Item action name"
// @Success 200 {object} Envelope[AccountActionResultView]
// @Failure 401 {object} ErrorEnvelope
// @Failure 403 {object} ErrorEnvelope
// @Failure 404 {object} ErrorEnvelope
// @Failure 422 {object} ErrorEnvelope
// @Router /account/contribution-items/{name}/{item}/actions/{action} [post]
func AdminAccountContributionItemAction() {}
// AdminAccountTokenScopes documents GET /account/tokens/scopes.
//
// @Summary List available API token scopes

View File

@@ -348,6 +348,7 @@ func (s *service) mount(r pact.Router) {
// Sections plugins contribute to My account (pact.HasAccountContributions).
g.Get("/account/contributions", interactiveOnly(s.accountContributionsList))
g.Post("/account/contributions/{name}/actions/{action}", interactiveOnly(requireAjax(s.accountContributionAction)))
g.Post("/account/contribution-items/{name}/{item}/actions/{action}", interactiveOnly(requireAjax(s.accountContributionItemAction)))
// Consent of administrator-only MCP grants, served for the
// published pact.MCPAdminConsent (404 when none is published).
g.Get("/mcp/consent/{request}", interactiveOnly(s.mcpConsentShow))

View File

@@ -836,6 +836,9 @@ func conformCases() []conformCase {
{"POST /account/contributions/{name}/actions/{action}", 200, "cabana.Envelope-cabana_AccountActionResultView", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder {
return e.send(t, http.MethodPost, "/account/contributions/conform_link/actions/open", nil, true)
}, into[cabana.Envelope[cabana.AccountActionResultView]](), nil},
{"POST /account/contribution-items/{name}/{item}/actions/{action}", 200, "cabana.Envelope-cabana_AccountActionResultView", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder {
return e.send(t, http.MethodPost, "/account/contribution-items/conform_link/conform-item/actions/forget", nil, true)
}, into[cabana.Envelope[cabana.AccountActionResultView]](), nil},
{"GET /mcp/consent/{request}", 200, "cabana.Envelope-cabana_MCPConsentView", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder {
return e.send(t, http.MethodGet, "/mcp/consent/conform-request", nil, true)
}, into[cabana.Envelope[cabana.MCPConsentView]](), nil},
@@ -1298,6 +1301,16 @@ func (conformPlugin) AccountContributions() []pact.AccountContribution {
return pact.AccountActionResult{Message: "Opened", URL: "https://conform.example.test/link"}, nil
},
}},
Items: func(context.Context, uint) ([]pact.AccountItem, error) {
return []pact.AccountItem{{ID: "conform-item", Title: "Conform item", Subtitle: "A row", Meta: []string{"2026-11-21"}}}, nil
},
ItemActions: []pact.AccountItemAction{{
Name: "forget", Label: "Forget", Confirm: "Forget :title?", Danger: true,
Run: func(context.Context, pact.AccountItemActionInput) (pact.AccountActionResult, error) {
return pact.AccountActionResult{Message: "Forgotten"}, nil
},
}},
ItemsEmpty: "No rows.",
}}
}

View File

@@ -94,6 +94,7 @@ func TestPhase10Coverage(t *testing.T) {
"DELETE /{vendor}/{plugin}/{controller}/{id}/files/{field}/{file}",
"DELETE /{vendor}/{plugin}/{controller}/{id}/relations/{name}/records/{child}/files/{field}/{file}",
"POST /account/avatar",
"POST /account/contribution-items/{name}/{item}/actions/{action}",
"POST /account/contributions/{name}/actions/{action}",
"POST /account/tokens",
"POST /auth/login",

View File

@@ -73,9 +73,10 @@ func TestPhase10CSRF(t *testing.T) {
// caption, file remove, relation child create, update and delete, pivot
// update, child file upload, reorder, caption and remove, plugin field
// type upload, tree reorder save, account contribution action,
// mail image upload, mail preview, mail test-send, MCP consent decision
if unsafe != 39 {
t.Fatalf("walked %d state-changing routes, want 39: %v", unsafe, router.order)
// mail image upload, mail preview, mail test-send, MCP consent decision,
// account contribution item action
if unsafe != 40 {
t.Fatalf("walked %d state-changing routes, want 40: %v", unsafe, router.order)
}
loginHandler := router.handlers[login]

View File

@@ -50,6 +50,7 @@ var phase09Routes = []adminRoute{
{key: "DELETE /account/tokens/{id}"},
{key: "GET /account/contributions"},
{key: "POST /account/contributions/{name}/actions/{action}"},
{key: "POST /account/contribution-items/{name}/{item}/actions/{action}"},
{key: "GET /mcp/consent/{request}"},
{key: "POST /mcp/consent/{request}"},
{key: "GET /navigation"},

View File

@@ -45,8 +45,9 @@ var tokenRouteClasses = map[string]tokenRouteClass{
"DELETE /account/tokens/{id}": classInteractive,
"GET /account/contributions": classInteractive,
"POST /account/contributions/{name}/actions/{action}": classInteractive,
"GET /mcp/consent/{request}": classInteractive,
"POST /mcp/consent/{request}": classInteractive,
"POST /account/contribution-items/{name}/{item}/actions/{action}": classInteractive,
"GET /mcp/consent/{request}": classInteractive,
"POST /mcp/consent/{request}": classInteractive,
"GET /navigation": classAllowsNav,
"GET /field-types": classExplicitGate,

View File

@@ -29,7 +29,7 @@ Use cases:
- Member token scopes: `pact.FrontendTokenScope` and `pact.HasFrontendTokenScopes`, the frontend counterpart of `pact.HasTokenScopes`, so a plugin declares scopes for the user plugin's member personal API tokens; the admin token catalog never reads them. `pact.FrontendTokenScope.Implies` is only `""`, `read` or `write`, for a later OAuth MCP check; empty means the scope is not implied, and the route middleware is still what enforces a member scope. The plugin that owns member tokens publishes the compiled list as `pact.MemberTokenScopeCatalog` (`pact.MemberTokenScopeCatalog.MemberTokenScopes`). `pact.ValidTokenScopeName` is the one scope-name rule both catalogs apply.
- Frontend permission codes: `pact.FrontendPermission` and `pact.HasFrontendPermissions`, the frontend counterpart of `pact.HasPermissions`, so a plugin guarding a route with a permission code also declares that code for the user plugin's permission editors.
- MCP declarations, free of any MCP SDK: `pact.HasMCP` with `pact.MCP`, `pact.MCPTool` and `pact.MCPPrompt` bind tools and prompts to the plugin's own token-guarded routes; `pact.MCPGuard` and `pact.MCPGuards` let the owner of a route guard publish how its routes are guarded and dispatched; `pact.MCPTokenVerifier`, `pact.MCPPersonalTokenResolver` and `pact.MCPLinkedBackendResolver` are the services the MCP endpoint looks up; `pact.MCPAdvertisedScopes` (`pact.MCPAdvertisedScopes.MCPScopesSupported`) is the scope list that verifier publishes for protected-resource metadata, separate from `pact.MCPTokenVerifier` so that interface stays `MCPVerifyToken` and `MCPResource`; `pact.MCPSubjectChanged` is the event that refreshes a session's tool list. An in-process tool call carries a `pact.MCPCall`, stored with `pact.WithMCPCall` and read with `pact.MCPCallFrom` (absent on a plain HTTP request).
- My account contributions: `pact.HasAccountContributions` with `pact.AccountContribution` and `pact.AccountAction`, so a plugin adds a section with a status line and buttons to the administrator's own account page, run for the signed-in administrator only.
- My account contributions: `pact.HasAccountContributions` with `pact.AccountContribution` and `pact.AccountAction`, so a plugin adds a section with a status line and buttons to the administrator's own account page, run for the signed-in administrator only; a section can also list the administrator's rows (`pact.AccountItem`) with per-row buttons (`pact.AccountItemAction`).
- Admin controller contracts: `pact.AdminController`, `pact.HasAdminControllers`, `pact.AdminAssets` (embedded Winter-shaped admin YAML), `pact.AdminPermissioned` and `pact.AdminRecordSource`.
- Admin extension contracts, so a plugin extends the compiled admin SPA without a Node build: `pact.AdminClientAssets` (per-controller JS and CSS from the plugin's embedded `assets/` tree, Winter's `addJs`/`addCss`), `pact.HasAdminActions` with `pact.AdminAction`, `pact.AdminActionInput` and `pact.AdminActionResult` (named toolbar and widget actions whose routes, CSRF check, permissions and record scoping the framework owns), `pact.HasAdminBulkActions` with `pact.AdminBulkAction`, `pact.AdminBulkActionInput` and `pact.AdminBulkActionResult` (named actions on the rows selected in a list, which receive records the framework loaded through the list scope, never ids; a `Detached` action runs outside the framework transaction), `pact.HasAdminRecordActions` with `pact.AdminRecordAction`, `pact.AdminRecordActionInput` and `pact.AdminRecordActionResult` (named actions on one record, each with an `Applies` rule for the record's state), `pact.HasAdminActionExtensions` with `pact.AdminActionExtension` (a plugin adds record actions to any admin controller by controller ID, one it does not own included; they are offered on that controller's preview screen after the owner's) and `pact.AdminFormExtension` (a plugin places fields and tabs in another controller's form, before or after the owner's, and loads and saves their values itself inside the record's save transaction), and `pact.AdminPartialData` (the curated view model a partial template renders).
- Plugin field types: `pact.HasFormFieldTypes` returns `pact.FormFieldType` entries, admin form field types any controller's `fields.yaml` uses by a short alias (`type: notes`). A type names its custom element, its scripts and styles, its own option keys and its Go funcs: `Decode` turns a submitted `pact.FormFieldValue` into a `pact.FormFieldDecoded` (the value to store plus optional `pact.FormFieldNotice` messages for the administrator, such as what a sanitizer removed) or refuses it with a `pact.FormFieldError`; `Load` serves the stored value to the element, `ListValue` formats a list column, `Upload` stores a file from a `pact.FormFieldUpload` and answers a `pact.FormFieldUploadResult`, and `RequestOptions` adds options that change per request (a site setting the element follows) to the served form schema. The admin framework owns the routes, permissions, record scope, locale storage of a translatable type and the localization of notices.
@@ -144,9 +144,13 @@ func (p *BlogPlugin) Schedule() []pact.ScheduledCommand {
| `pact.AdminFormErrors` | A `Save` refusal: field name to messages (phrase keys or text). The save answers 422 with them on the fields and rolls back. |
| `pact.AdminFormZoneTabs` | The `zone:` value of the form's tab zone, the default and the only zone rendered so far; `pact.AdminFormZoneOutside` and `pact.AdminFormZoneSecondary` are reserved and stop the boot ("is not supported yet"). |
| `pact.HasAccountContributions` | Implemented by a plugin that adds sections to the admin's My account page. |
| `pact.AccountContribution` | One My account section: `Name` (an identifier unique across plugins), `Label`, `Description`, an optional pure-read `Status` func for the signed-in administrator and its `Actions`. A non-identifier or taken name, an empty label, a duplicate or non-identifier action name, a nil `Run` or an empty action label stops the boot. |
| `pact.AccountContribution` | One My account section: `Name` (an identifier unique across plugins), `Label`, `Description`, an optional pure-read `Status` func for the signed-in administrator and its `Actions`. `pact.AccountContribution.Items`, when set, is a pure read of the signed-in administrator's rows (`pact.AccountItem`), `pact.AccountContribution.ItemActions` are each row's buttons and `pact.AccountContribution.ItemsEmpty` is the line shown with no rows (empty means the admin's own); a nil `Items` leaves the section as it was. A non-identifier or taken name, an empty label, a duplicate or non-identifier action or item action name, a nil `Run`, an empty action label or item actions without `Items` stops the boot. |
| `pact.AccountAction` | One button of a section: name, label, optional `Confirm` text, `Danger`, extra `Permissions`, an optional pure-read `Applies` rule and the Go `Run` function, which acts for the signed-in administrator only. |
| `pact.AccountActionInput` | What an account action receives: `AdminID`, the signed-in administrator, and nothing else. |
| `pact.AccountItem` | One row of a section: `ID` (unique within the section; the item action route names it), `Title`, optional `Subtitle` and `Meta` lines, all shown as text. |
| `pact.AccountItemAction` | One button of every row: name, label, optional `Confirm` text (`:title` is filled with the row's title by the admin), `Danger`, extra `Permissions` and the Go `Run` function, which acts for the signed-in administrator on one row inside a transaction, and only for an item ID that administrator's own `Items` listed. |
| `pact.AccountItemActionInput` | What an item action receives: `AdminID` and `ItemID`. |
| `pact.ErrAccountItemNotFound` | What an item action's `Run` answers when its row is gone; the admin API answers 404. |
| `pact.AccountActionResult` | What an account action returns: a `Message` for the toast and an optional `URL` the admin opens in a new tab. |
| `pact.HasMCP` | Implemented by a plugin that declares MCP tools and prompts for the framework's MCP endpoint. |
| `pact.MCP` | The declaration: `Tools` and `Prompts` (resources are a later field of the same struct). |

View File

@@ -3,6 +3,7 @@ package pact
import (
"context"
"encoding/json"
"errors"
"io"
"io/fs"
"net/http"
@@ -607,18 +608,70 @@ type HasAccountContributions interface {
// signed-in administrator (an empty string shows none). Actions are the
// section's buttons.
//
// Items, when set, adds a list of rows under the status line: a pure read
// scoped to the signed-in administrator that answers that administrator's
// rows (connections, devices, keys). ItemActions are the buttons of each row;
// the framework runs one only for an item ID the administrator's own Items
// listed. ItemsEmpty (a phrase key or text) is the line shown when Items
// answers no rows; empty means the framework's own empty line. A nil Items
// keeps the section exactly as it is without these fields.
//
// The admin compiles contributions at boot, only when it is active. A name
// that is not an identifier, a name another plugin already contributed, an
// empty Label, an action whose name is not an identifier or repeats within
// the section, a nil Run or an empty action Label stops the boot.
// empty Label, an action or item action whose name is not an identifier or
// repeats within the section, a nil Run, an empty action Label or item
// actions without Items stops the boot.
type AccountContribution struct {
Name string
Label string
Description string
Status func(ctx context.Context, adminID uint) (string, error) `json:"-"`
Actions []AccountAction
Items func(ctx context.Context, adminID uint) ([]AccountItem, error) `json:"-"`
ItemActions []AccountItemAction
ItemsEmpty string
}
// AccountItem is one row of an AccountContribution's Items: an ID unique
// within the section (the item action route names it), a Title, an optional
// Subtitle and optional Meta entries (short lines such as dates). All are
// shown as text, never as markup.
type AccountItem struct {
ID string
Title string
Subtitle string
Meta []string
}
// AccountItemAction is one button of every row of an AccountContribution.
// Label and Confirm are phrase keys or text; Confirm may contain :title,
// which the admin fills with the item's Title, and Danger selects the
// confirm dialog's danger variant. Permissions are extra backend permission
// codes the administrator needs. Run acts for the signed-in administrator on
// one item, inside a transaction (cabana.TxFromContext reads it), and only
// after the framework found the item among the administrator's own Items;
// it answers ErrAccountItemNotFound when the item is gone meanwhile.
type AccountItemAction struct {
Name string
Label string
Confirm string
Danger bool
Permissions []string
Run func(ctx context.Context, in AccountItemActionInput) (AccountActionResult, error) `json:"-"`
}
// AccountItemActionInput is what the framework hands an AccountItemAction:
// the id of the signed-in administrator and the ID of the item, which that
// administrator's Items listed.
type AccountItemActionInput struct {
AdminID uint
ItemID string
}
// ErrAccountItemNotFound is what an AccountItemAction's Run answers when its
// item no longer exists; the admin API answers 404.
var ErrAccountItemNotFound = errors.New("pact: account item not found")
// AccountAction is one button of an AccountContribution. Confirm, when set,
// is the confirmation text the admin shows first (Danger selects its danger
// variant). Permissions are extra backend permission codes the administrator