diff --git a/admin/openapi/admin.json b/admin/openapi/admin.json index 4e0bcf57..5a959b39 100644 --- a/admin/openapi/admin.json +++ b/admin/openapi/admin.json @@ -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).", diff --git a/admin/src/api/schema.d.ts b/admin/src/api/schema.d.ts index 2620db81..ce139770 100644 --- a/admin/src/api/schema.d.ts +++ b/admin/src/api/schema.d.ts @@ -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; diff --git a/docs/backend/users-and-permissions.md b/docs/backend/users-and-permissions.md index c7c97616..4be9d848 100644 --- a/docs/backend/users-and-permissions.md +++ b/docs/backend/users-and-permissions.md @@ -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 /api/v1/account/contributions` and runs a button through `POST /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 /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 diff --git a/docs/plugins/registration.md b/docs/plugins/registration.md index 4b86d4e5..58b617ab 100644 --- a/docs/plugins/registration.md +++ b/docs/plugins/registration.md @@ -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. | diff --git a/modules/cabana/README.md b/modules/cabana/README.md index e428839f..10b8517b 100644 --- a/modules/cabana/README.md +++ b/modules/cabana/README.md @@ -62,7 +62,7 @@ Use cases: - Mail screens (Settings → Mail): when the application publishes postcard's Mailer (`postcard.EditorFrom` succeeds; `party.Activate` runs `postcard.Activate`), the internal plugin also registers the mail screens over postcard's tables, the permission codes `cabana.PermissionManageMailTemplates` (`system.manage_mail_templates`) and `cabana.PermissionManageMailLayouts` (`system.manage_mail_layouts`), both granted to no role in code, and their Settings entries in category `backend::lang.settings.category_mail`. Mail templates (controller `cabana.MailTemplatesControllerID`, model `cabana.MailTemplate`) lists one row per template of this process's catalog (rows of uninstalled plugins are hidden; the row is the template's own, or the lowest locale variant when only variants ship) with code, subject, description, customized locales (`cabana.MailTemplate.CustomizedLocales`: Default and the locale codes of the customized versions, at most three then +N) and layout, and edits the subject, the Markdown body and the layout (a `relation` over `cabana.MailLayout` rows: every database-only layout and the catalog's file layouts). There is no create and no delete. A save marks the row customized, stamps `base_hash` with the file's current hash and `customized_at`, and validates the result through `postcard.Editor.Validate` inside the save's transaction; a `postcard.DraftError` is a 422 on its field with `backend::lang.mail.invalid_` (`:message`, `:name`). The index rows are written by `postcard.SyncIndex` and `postcard.EnsureLocaleRows` through `lagoon.OnDatabase` at activation; a failed sync is logged and retried on the first mail list request of the process, and a list request syncs again when the mail locales changed. The mail locales are the locales the translator's catalog holds plus, when a `cabana.TranslationWriter` is published, its enabled locales; the default locale is the writer's default locale, else the translator's. A template is one record per locale version: its own row (Default), a row per locale variant file (`welcome-en`) and a row per other mail locale that ships no file (`welcome-de`, created by `postcard.EnsureLocaleRows`, showing and sending the default version until it is customized). The update form's locale switcher lists them (`meta.localeVariants`); the record title is the template's base code, and the show response first ensures the template's missing locale rows, so a newly enabled locale can be opened without a restart. A save of a locale without a file stamps `base_hash` with the base file's hash; until it is customized, its form shows the base template's current version (its customization when there is one), and reset returns it to the base file. Mail layouts (`cabana.MailLayoutsControllerID`, model `cabana.MailLayout`) lists postcard's default layout first, then the file layouts and the custom (database-only, `source` NULL, shown as Custom) layouts by name; it creates custom layouts (code `^[a-z0-9-]+$`, free, create-only) and deletes them, refusing one that template rows still reference with a `cabana.ForbiddenError` whose message names the layout and the count (CLDR plural). Mail partials (`cabana.MailPartialsControllerID`, model `cabana.MailPartial`) edits the partials' HTML and text sections. Both need `cabana.PermissionManageMailLayouts`; saves are stamped and validated as templates are. On all three, the record action `reset` (danger, offered on a customized file-backed row) calls `postcard.ResetOverride` in the action's transaction; rows from files are never deleted. The list row states are `customized` (an override) and `outdated` (an override whose `base_hash` differs from the file's `file_hash`), the lists have a status filter (customized, not customized, outdated); on the templates list both apply to the whole template, any of its locale versions. The forms carry the `info` and `file_version` partials: the file (the base template's for a locale without a file), the status, on a template with locale versions the Default line or the line of a locale without a file (`backend::lang.mail.info_locale_default`, `info_locale_fallback`), the sample variables or the partial's call, the drift callout, and a 3-line-context LCS line diff of the serialized override (`postcard.FormatTemplate`, `FormatLayout`, `FormatPartial`) against the file, skipped above 2000 lines per side. The mail controllers declare `recordActions` without a preview block: the admin offers them in the update form's footer, a boot rule only these internal controllers are exempt from. The layout form's CSS tab has the `disable_auto_inline_css` switch (`cabana.MailLayout.DisableAutoInlineCSS`, off for a new custom layout): on, postcard keeps the layout's CSS in its style block instead of also copying it onto the elements; the preview and the save validation render with the switch's value. Layout and partial content fields use the built-in `codeeditor` type (`language: html|css|text`, optional `mailImages`); Branding is the settings form `mail_brand` on `cabana.MailBrandSetting` (postcard's brand row, a `mailimage` logo, the `site_name` text field shown by the built-in layouts' header and footer (trimmed, at most 255 characters, empty falls back to the display name of `mail.from`; a name `postcard.UnsafeText` refuses is a 422 on `site_name` with `backend::lang.mail.brand.site_name_unsafe`) and 13 `colorpicker` colours; the first save switches mail from `mail.brandCss` to the compiled colours). Mail images is the singleton controller `cabana.MailImagesControllerID` (`cabana.MailImageLibrary`) with a public attachMany `images` fileupload; GET/POST `/mail/images` and GET `/mail/images/{id}` return absolute public URLs (`attach.AbsolutePublicURL`) and refuse with `mail.images.no_public_url` when neither `storage.uploads.public_url` nor `app.url` is set. Listing answers either mail permission; upload and the singleton form need `system.manage_mail_layouts`. POST `/mail/preview` renders an unsaved draft (`cabana.AdminMailPreviewRequest`: `mode`, `id`, `values`) through `postcard.Editor.Preview` and answers `cabana.AdminMailPreviewResult` (subject, html, text); mode `template` needs `system.manage_mail_templates`, modes `layout`, `partial` and `branding` need `system.manage_mail_layouts`. POST `/mail/test-send` (interactive sessions only) sends a template, layout or partial draft to the signed-in administrator's own email (`cabana.AdminMailTestSendResult`), refuses recipient keys in the body, and is limited to five sends per administrator per ten minutes through a published `cooler.Attempter` when `serve` has one, otherwise an in-process fixed window (429 with `Retry-After`). Forms carry `mailpreview` fields (`mode` matching the screen). - Danger record actions: `pact.AdminRecordAction.Danger` is served as `danger` on the record response's `cabana.RecordAction` (absent when false, so existing payloads are unchanged); the admin's confirm dialog then uses its danger variant. - Prompted record actions: a `pact.AdminRecordAction` with a `Prompt` (`pact.AdminActionPrompt`) asks the administrator for one text value in its confirm dialog. The record response serves it as `prompt` on the action's `cabana.RecordAction` (absent for every other action, so existing payloads are unchanged), and the action route accepts the body key `payload`, a JSON string, only for such an action: trimmed, not empty and at most `max_length` runes (422 on `payload` with `backend::lang.form.action_prompt_required` or `action_prompt_too_long`, `backend::lang.form.action_prompt_invalid` for another JSON type), then handed to `Run` as `pact.AdminRecordActionInput.Value`. Every other record action keeps refusing `record_id`, `values` and `payload`. A prompt without a label fails boot, owned or contributed. -- My account contributions: a plugin implementing `pact.HasAccountContributions` adds sections (`pact.AccountContribution`) to the administrator's own account page, each with a status line and buttons (`pact.AccountAction`). GET `/account/contributions` lists them for the signed-in administrator and POST `/account/contributions/{name}/actions/{action}` runs one for that administrator only, behind the interactive-only guard, the action's permissions and its `Applies` rule, inside a transaction; the answer may carry a URL the admin opens in a new tab. That URL is kept only when it is an absolute `http`/`https` URL with a host or a same-origin path (one leading `/`); anything else, `javascript:` and `data:` included, is dropped and logged without the URL. A section whose `Status` fails is listed with an empty status and `error: true`, and an action whose `Applies` fails is left out and marks its section `error: true` as well; both are logged and the other sections are answered as usual. A status is translated only when it is a phrase key. Names are generic: cabana never names the contributing plugin. The existing `/account*` and `/auth/me` payloads are unchanged. A non-identifier or duplicate section name, an empty label, a duplicate or non-identifier action name, a nil `Run` or an empty action label stops the boot. +- My account contributions: a plugin implementing `pact.HasAccountContributions` adds sections (`pact.AccountContribution`) to the administrator's own account page, each with a status line and buttons (`pact.AccountAction`). GET `/account/contributions` lists them for the signed-in administrator and POST `/account/contributions/{name}/actions/{action}` runs one for that administrator only, behind the interactive-only guard, the action's permissions and its `Applies` rule, inside a transaction; the answer may carry a URL the admin opens in a new tab. That URL is kept only when it is an absolute `http`/`https` URL with a host or a same-origin path (one leading `/`); anything else, `javascript:` and `data:` included, is dropped and logged without the URL. A section whose `Status` fails is listed with an empty status and `error: true`, and an action whose `Applies` fails is left out and marks its section `error: true` as well; both are logged and the other sections are answered as usual. A status is translated only when it is a phrase key. Names are generic: cabana never names the contributing plugin. A section may also list the administrator's own rows (`pact.AccountContribution.Items`) with per-row buttons (`pact.AccountItemAction`), run through POST `/account/contribution-items/{name}/{item}/actions/{action}` only for an item that administrator's `Items` listed; a section without `Items` sends `items` null and renders as before. The existing `/account*` and `/auth/me` payloads are unchanged. A non-identifier or duplicate section name, an empty label, a duplicate or non-identifier action name, a nil `Run` or an empty action label stops the boot. - Record events: every admin create and update fires `pact.RecordSaved` on the application's event bus after the commit, with the controller ID, the record's morph type, its id, the request locale, `Created` and the changed attributes with old and new values (column changes, then translated values per locale, read before the save writes them); a save that changed nothing fires with no changes. Delete and every row of a bulk delete fire `pact.RecordDeleted`; a tree reorder fires `pact.RecordSaved` for each moved record (parent and sort columns); relation-manager child writes fire both for the child, naming the controller that edits the child's model; a hasMany link or unlink, and the attach of a child created in an unsaved parent's form session, fire `pact.RecordSaved` for the child with its foreign key change, and a session-created child that is unlinked again fires `pact.RecordDeleted`. A rolled-back write fires nothing and a listener's error is logged, never returned. The same changes reach a form extension's `Save` in `pact.AdminFormSave.Changes`. Plugin code that writes records directly fires the same events with `cabana.EmitRecordSaved` and `cabana.EmitRecordDeleted`. - Backend subject events: a save on the Administrators screen that changed an administrator's role, permission overrides or superuser flag, a Roles save that changed a role's grants (one event per administrator holding it), a deactivation or deletion (record and bulk forms) and a revoked personal API token fire `pact.MCPSubjectChanged` on the application's event bus with guard `backend`, so a module acting on behalf of an administrator elsewhere (the MCP endpoint) re-lists what they may do or ends their sessions. A revoked token's event carries its `TokenID`, so only the sessions opened with that token end; the administrator's other sessions stay open. Only the My account revoke fires it: `admin:token:revoke` runs in its own process, where no MCP endpoint listens, so that token's sessions end when the token is next verified (the session's next request or its stream's periodic bearer re-check). A listener's error is logged and never fails the save. - Singleton settings screens declared with `pact.HasSettings`, read and saved by `cabana.SettingsService`. A `type: password` field on a settings form is a write-only secret on a `lagoon.Encrypted` column (any other column type fails boot naming the field): the GET omits it from `data` and reports `stored`, `env` or `empty` per field in `meta.secrets` (`cabana.SettingsMeta`; `env` when the column is empty and the model's `cabana.SecretFallbacks` config key resolves to a non-empty value); on PUT an absent key or an empty string keeps the stored value, JSON null clears it, a non-string is a 422 on the field, and the answer carries the new states, never a value. A `type: richeditor` on a settings form is sanitized on save exactly like a controller save, with the removals in `meta.notices`; `repeater` and `dependsOn` stay refused. Settings fields keep their `tab`. A `type: dropdown` whose `options` names a method takes its choices from the settings model, which must implement `pact.DropdownOptionsProvider` (boot fails naming the field otherwise); the settings schema serves them localized. A settings entry whose `Controller` field is set links to that admin controller instead: start-up fails when it also declares a model, form or model factory, or names an unknown controller; `GET /settings` lists it, with its `controller`, only to administrators who pass its permissions and may open the controller; and the singleton settings endpoints answer 404 for its code. @@ -94,6 +94,7 @@ Guarded routes run surf's `locale.from-principal` after the backend guard: an in | GET `/account/contributions` | The sections plugins contribute to My account (`cabana.AccountContributionView`): translated label, description and status for the signed-in administrator, and the actions (`cabana.AccountContributionActionView`) they hold the permissions for and whose `Applies` reports true. A section whose status or one of whose actions' `Applies` failed carries `error: true`. An empty list when no plugin contributes. Interactive session only. | | GET `/mcp/consent/{request}` | A pending MCP authorization request of an administrator-only grant (`cabana.MCPConsentView`), resolved by the published `pact.MCPAdminConsent` for the signed-in administrator: the client (`cabana.MCPConsentClientView`, with the redirect URI's host), the administrator (`cabana.MCPConsentAdminView`: login, name, email), the requested scopes the administrator can grant in catalog order (`cabana.AdminAPITokenScope`; scopes outside the catalog or without an owned permission are hidden, as in the token picker), `offline_access` (requested), `consent_required` and `expires_at`. 404 `request_not_found` when no provider is published or the request is unknown. Interactive session only. | | POST `/mcp/consent/{request}` | Allow or deny that request (`cabana.MCPConsentDecisionRequest`: `decision` `allow` or `deny`, `scopes`, `offline_access`; at most 16 KiB, unknown fields 400). An allow keeps the submitted scopes that were requested and can be granted (others are dropped), normalises them like token creation (`*` collapses to `["*"]`), answers 422 `no_grantable_scopes` when nothing is left and grants offline access only when it was requested and asked for; the answer is `cabana.MCPConsentDecisionView` (`redirect_uri`). cabana opens no transaction: the provider owns it. Interactive session only, AJAX header required. | +| POST `/account/contribution-items/{name}/{item}/actions/{action}` | Run one item action of a contributed section on one row: 404 for an unknown section or item action, 403 without its permissions, 404 when the section's `Items` does not list `{item}` for the signed-in administrator (so another administrator's row is never reachable) or when `Run` answers `pact.ErrAccountItemNotFound`; `Run` gets the administrator and item ids inside a transaction and answers `cabana.AccountActionResultView`. The path is not under `/account/contributions/` because a nine-segment POST there would overlap the controller routes. Interactive session only, AJAX header required. | | POST `/account/contributions/{name}/actions/{action}` | Run one contributed action for the signed-in administrator: 404 for an unknown section or action, 403 without the action's permissions, 409 when it no longer applies; `Run` gets the administrator's id inside a transaction and answers `cabana.AccountActionResultView` (translated `message`, optional `url`, only an `http`/`https` or same-origin URL). Interactive session only, AJAX header required. | | GET `/navigation`, GET `/settings` | Navigation and settings entries the administrator may open and, for a navigation entry with a `Visible` func, that it answers true for the request; a settings entry's `controller` names the admin controller a link entry opens and is empty for a singleton form, and `path` (only on the admin's own Plugins entry) names the SPA route it opens. | | GET `/plugins` | The Plugins screen (`cabana.PluginsOverview`): the framework version the application was built with, the registry state (`cabana.RegistryState`: `enabled`, `status` ok, disabled or unavailable) and every activated plugin in summer.yaml order (`cabana.InstalledPlugin`) with, for a plugin the registry lists, `latest`, `updateAvailable`, `updateCommand` and `latestFramework`. 403 without `cabana.PermissionViewPlugins`. | @@ -286,6 +287,7 @@ func (p *BlogPlugin) AdminFS() fs.FS { return os.DirFS("testdata/docs") } | `cabana.MCPConsentView` / `cabana.MCPConsentClientView` / `cabana.MCPConsentAdminView` / `cabana.MCPConsentDecisionRequest` / `cabana.MCPConsentDecisionView` | JSON shapes of the MCP consent routes. `cabana.AdminMCPConsentShow` and `cabana.AdminMCPConsentDecide` carry their swag annotations. | | `cabana.BackendPrincipal` | Loads an admin principal by id through the backend users provider (grants, superuser flag, backend kind set); nil, nil for a missing or deactivated admin. | | `cabana.AdminAPIToken` / `cabana.AdminAPITokenScope` / `cabana.AdminAPITokenCreated` / `cabana.AdminAPITokenRequest` | JSON shapes of the account token API. | +| `cabana.AccountItemView` | One row of a contributed section on `cabana.AccountContributionView.Items` (null for a section without `Items`, next to `cabana.AccountContributionView.ItemActions` and `cabana.AccountContributionView.ItemsEmpty`). `cabana.AdminAccountContributionItemAction` carries the item action route's swag annotation. | | `cabana.AccountContributionView` / `cabana.AccountContributionActionView` / `cabana.AccountActionResultView` | JSON shapes of the My account contribution routes: a contributed section with its status and offered actions, one action, and an action's answer (message and optional URL). | | `cabana.CompileList` / `cabana.CompileForm` | Compile a controller's list and form YAML into cached schemas. | | `cabana.CompileFormWithTypes` | `cabana.CompileForm` that also accepts the plugin field types of one plugin (`[]pact.FormFieldType`), with the boot checks of their aliases, option keys and `CheckOptions`. | @@ -460,6 +462,8 @@ The Phase 18.1 pieces (the taglist field and the flat reorder) are covered by Do `ClearOnChange` is covered by `clear_on_change_field_test.go` (TestClearOnChangeFieldBoot, Docker-free, and TestClearOnChangeBelongsTo on Postgres: a changed, emptied, kept or co-submitted belongsTo key) and `clear_on_change_test.go` (TestClearOnChangeRelationBoot and, on Postgres, TestClearOnChangeHasMany: link, unlink and a deferred link committed by the parent's first save). +Per-item rows of My account sections are covered by the Postgres test TestAccountItemsSmoke in `account_items_smoke_test.go`: items null without `Items`, the rows and permitted item actions, a run inside a transaction with the administrator and item ids, 404 for another administrator's item id without `Run`, 404 for `pact.ErrAccountItemNotFound`, 403 without the permission and the boot refusals. + The MCP consent routes are covered by the Postgres test TestMCPAdminConsentSmoke in `mcp_consent_smoke_test.go`, over a fake `pact.MCPAdminConsent`: hidden scopes, a dropped `*` that was not requested, a requested `*` collapsing the grant, offline access, deny, 400 for a bad body, 401 anonymous, 403 `interactive_only` for a `g15_` token and 404 without a provider or for an unknown request. TestTokenScopeNamesAndLabels covers the exported catalog names and labels. The toolbar and widget action run log is covered by the Postgres test TestAdminActionRunLog in `action_run_log_test.go`: who ran the action, its kind, the field and record id of a widget run, no posted or returned content, and no line for refused, invalid or failed runs. diff --git a/modules/cabana/account_contributions.go b/modules/cabana/account_contributions.go index 9cc4dd65..36a84484 100644 --- a/modules/cabana/account_contributions.go +++ b/modules/cabana/account_contributions.go @@ -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 diff --git a/modules/cabana/account_items_smoke_test.go b/modules/cabana/account_items_smoke_test.go new file mode 100644 index 00000000..13b9b3f4 --- /dev/null +++ b/modules/cabana/account_items_smoke_test.go @@ -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) + } + } +} diff --git a/modules/cabana/admin_openapi.go b/modules/cabana/admin_openapi.go index 53bdced1..f80a4b74 100644 --- a/modules/cabana/admin_openapi.go +++ b/modules/cabana/admin_openapi.go @@ -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 diff --git a/modules/cabana/http.go b/modules/cabana/http.go index 48d068ba..6e5cab4a 100644 --- a/modules/cabana/http.go +++ b/modules/cabana/http.go @@ -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)) diff --git a/modules/cabana/openapi_conformance_test.go b/modules/cabana/openapi_conformance_test.go index 6660c380..6dab3640 100644 --- a/modules/cabana/openapi_conformance_test.go +++ b/modules/cabana/openapi_conformance_test.go @@ -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.", }} } diff --git a/modules/cabana/phase10_coverage_test.go b/modules/cabana/phase10_coverage_test.go index c8afc53f..389a3b34 100644 --- a/modules/cabana/phase10_coverage_test.go +++ b/modules/cabana/phase10_coverage_test.go @@ -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", diff --git a/modules/cabana/phase10_csrf_test.go b/modules/cabana/phase10_csrf_test.go index f566e343..c3849d16 100644 --- a/modules/cabana/phase10_csrf_test.go +++ b/modules/cabana/phase10_csrf_test.go @@ -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] diff --git a/modules/cabana/security_coverage_test.go b/modules/cabana/security_coverage_test.go index 48662eef..d6101d28 100644 --- a/modules/cabana/security_coverage_test.go +++ b/modules/cabana/security_coverage_test.go @@ -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"}, diff --git a/modules/cabana/token_routes_test.go b/modules/cabana/token_routes_test.go index e6a68c93..122debf3 100644 --- a/modules/cabana/token_routes_test.go +++ b/modules/cabana/token_routes_test.go @@ -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, diff --git a/modules/pact/README.md b/modules/pact/README.md index ec2ab7cc..7c470349 100644 --- a/modules/pact/README.md +++ b/modules/pact/README.md @@ -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). | diff --git a/modules/pact/capabilities.go b/modules/pact/capabilities.go index 0342981b..0f8792ce 100644 --- a/modules/pact/capabilities.go +++ b/modules/pact/capabilities.go @@ -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