feat(cabana): mail preview and test send to yourself
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -470,6 +470,56 @@
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"cabana.AdminMailPreviewRequest": {
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "integer"
|
||||
},
|
||||
"mode": {
|
||||
"type": "string"
|
||||
},
|
||||
"values": {
|
||||
"additionalProperties": {},
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"mode",
|
||||
"values"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"cabana.AdminMailPreviewResult": {
|
||||
"properties": {
|
||||
"html": {
|
||||
"type": "string"
|
||||
},
|
||||
"subject": {
|
||||
"type": "string"
|
||||
},
|
||||
"text": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"html",
|
||||
"subject",
|
||||
"text"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"cabana.AdminMailTestSendResult": {
|
||||
"properties": {
|
||||
"email": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"email"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"cabana.AdminMarkdownPreviewRequest": {
|
||||
"properties": {
|
||||
"markdown": {
|
||||
@@ -1063,6 +1113,36 @@
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"cabana.Envelope-cabana_AdminMailPreviewResult": {
|
||||
"properties": {
|
||||
"data": {
|
||||
"$ref": "#/components/schemas/cabana.AdminMailPreviewResult"
|
||||
},
|
||||
"meta": {
|
||||
"$ref": "#/components/schemas/cabana.SuccessMeta"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"data",
|
||||
"meta"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"cabana.Envelope-cabana_AdminMailTestSendResult": {
|
||||
"properties": {
|
||||
"data": {
|
||||
"$ref": "#/components/schemas/cabana.AdminMailTestSendResult"
|
||||
},
|
||||
"meta": {
|
||||
"$ref": "#/components/schemas/cabana.SuccessMeta"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"data",
|
||||
"meta"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"cabana.Envelope-cabana_AdminMarkdownPreviewResult": {
|
||||
"properties": {
|
||||
"data": {
|
||||
@@ -4582,6 +4662,180 @@
|
||||
]
|
||||
}
|
||||
},
|
||||
"/mail/preview": {
|
||||
"post": {
|
||||
"description": "Renders an unsaved template, layout, partial or branding draft through postcard's Editor with sample values. Mode template needs system.manage_mail_templates; layout, partial and branding need system.manage_mail_layouts. A draft that does not render is 422 with details field, rule and message.",
|
||||
"requestBody": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/cabana.AdminMailPreviewRequest"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Draft mode, id and form values",
|
||||
"required": true
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/cabana.Envelope-cabana_AdminMailPreviewResult"
|
||||
}
|
||||
}
|
||||
},
|
||||
"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": "Preview a mail draft",
|
||||
"tags": [
|
||||
"admin"
|
||||
]
|
||||
}
|
||||
},
|
||||
"/mail/test-send": {
|
||||
"post": {
|
||||
"description": "Sends an unsaved template, layout or partial draft to the signed-in administrator's own email. Interactive sessions only; recipient fields in the body are refused. Limited to five sends per administrator per ten minutes (429 with Retry-After).",
|
||||
"requestBody": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/cabana.AdminMailPreviewRequest"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Draft mode, id and form values",
|
||||
"required": true
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/cabana.Envelope-cabana_AdminMailTestSendResult"
|
||||
}
|
||||
}
|
||||
},
|
||||
"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"
|
||||
},
|
||||
"429": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/cabana.ErrorEnvelope"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Too Many Requests"
|
||||
},
|
||||
"502": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/cabana.ErrorEnvelope"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Bad Gateway"
|
||||
}
|
||||
},
|
||||
"security": [
|
||||
{
|
||||
"BackendBearer": []
|
||||
}
|
||||
],
|
||||
"summary": "Send a mail draft to yourself",
|
||||
"tags": [
|
||||
"admin"
|
||||
]
|
||||
}
|
||||
},
|
||||
"/markdown/preview": {
|
||||
"post": {
|
||||
"description": "Renders the markdown source through cabana.RenderMarkdown (goldmark without unsafe HTML) and answers the sanitized HTML. Output the renderer's gate refuses is a 422 on markdown. Any backend session may call it.",
|
||||
|
||||
201
admin/src/api/schema.d.ts
vendored
201
admin/src/api/schema.d.ts
vendored
@@ -1292,6 +1292,184 @@ export interface paths {
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/mail/preview": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
get?: never;
|
||||
put?: never;
|
||||
/**
|
||||
* Preview a mail draft
|
||||
* @description Renders an unsaved template, layout, partial or branding draft through postcard's Editor with sample values. Mode template needs system.manage_mail_templates; layout, partial and branding need system.manage_mail_layouts. A draft that does not render is 422 with details field, rule and message.
|
||||
*/
|
||||
post: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
/** @description Draft mode, id and form values */
|
||||
requestBody: {
|
||||
content: {
|
||||
"application/json": components["schemas"]["cabana.AdminMailPreviewRequest"];
|
||||
};
|
||||
};
|
||||
responses: {
|
||||
/** @description OK */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["cabana.Envelope-cabana_AdminMailPreviewResult"];
|
||||
};
|
||||
};
|
||||
/** @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;
|
||||
};
|
||||
"/mail/test-send": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
get?: never;
|
||||
put?: never;
|
||||
/**
|
||||
* Send a mail draft to yourself
|
||||
* @description Sends an unsaved template, layout or partial draft to the signed-in administrator's own email. Interactive sessions only; recipient fields in the body are refused. Limited to five sends per administrator per ten minutes (429 with Retry-After).
|
||||
*/
|
||||
post: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
/** @description Draft mode, id and form values */
|
||||
requestBody: {
|
||||
content: {
|
||||
"application/json": components["schemas"]["cabana.AdminMailPreviewRequest"];
|
||||
};
|
||||
};
|
||||
responses: {
|
||||
/** @description OK */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["cabana.Envelope-cabana_AdminMailTestSendResult"];
|
||||
};
|
||||
};
|
||||
/** @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"];
|
||||
};
|
||||
};
|
||||
/** @description Too Many Requests */
|
||||
429: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["cabana.ErrorEnvelope"];
|
||||
};
|
||||
};
|
||||
/** @description Bad Gateway */
|
||||
502: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["cabana.ErrorEnvelope"];
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/markdown/preview": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
@@ -6009,6 +6187,21 @@ export interface components {
|
||||
data: components["schemas"]["cabana.AdminMailImage"][];
|
||||
meta: components["schemas"]["cabana.AdminMailImagesMeta"];
|
||||
};
|
||||
"cabana.AdminMailPreviewRequest": {
|
||||
id: number;
|
||||
mode: string;
|
||||
values: {
|
||||
[key: string]: unknown;
|
||||
};
|
||||
};
|
||||
"cabana.AdminMailPreviewResult": {
|
||||
html: string;
|
||||
subject: string;
|
||||
text: string;
|
||||
};
|
||||
"cabana.AdminMailTestSendResult": {
|
||||
email: string;
|
||||
};
|
||||
"cabana.AdminMarkdownPreviewRequest": {
|
||||
markdown: string;
|
||||
};
|
||||
@@ -6176,6 +6369,14 @@ export interface components {
|
||||
data: components["schemas"]["cabana.AdminMailImage"];
|
||||
meta: components["schemas"]["cabana.SuccessMeta"];
|
||||
};
|
||||
"cabana.Envelope-cabana_AdminMailPreviewResult": {
|
||||
data: components["schemas"]["cabana.AdminMailPreviewResult"];
|
||||
meta: components["schemas"]["cabana.SuccessMeta"];
|
||||
};
|
||||
"cabana.Envelope-cabana_AdminMailTestSendResult": {
|
||||
data: components["schemas"]["cabana.AdminMailTestSendResult"];
|
||||
meta: components["schemas"]["cabana.SuccessMeta"];
|
||||
};
|
||||
"cabana.Envelope-cabana_AdminMarkdownPreviewResult": {
|
||||
data: components["schemas"]["cabana.AdminMarkdownPreviewResult"];
|
||||
meta: components["schemas"]["cabana.SuccessMeta"];
|
||||
|
||||
@@ -186,6 +186,8 @@ On a customized template, file layout or partial, **Reset to file version** retu
|
||||
|
||||
When a plugin update changes a file you customized, your version is still sent, but the list marks the row Customized and File changed, the status filter's File changed choice finds it, and the form shows a notice. The File version tab shows the lines your version changed against the current file (lines starting with + are only in your version, lines starting with − only in the file) and the file itself. Saving your version again marks the change as reviewed; resetting takes the new file.
|
||||
|
||||
Each mail form has a live preview (`POST /mail/preview`) that renders the unsaved draft through `postcard.Editor` with the template's sample values (or sample content for layouts, partials and branding). **Send test to me** (`POST /mail/test-send`) delivers that draft only to the signed-in administrator's own email: the body never carries a recipient, personal API tokens are refused, and each administrator may send at most five tests per ten minutes (429 with `Retry-After` when the limit is hit).
|
||||
|
||||
## Drivers
|
||||
|
||||
`mail.driver` selects the driver:
|
||||
|
||||
@@ -52,7 +52,7 @@ url: redis://10.0.0.7:6379/0
|
||||
|
||||
Keep a URL that carries a password in the environment instead: `SUMMER_REDIS__URL=redis://:secret@10.0.0.7:6379/0`. `rediss://` connects over TLS and `unix://` through a socket.
|
||||
|
||||
When `serve` starts, it calls `cooler.Install`, which builds the Redis client and pings it, and publishes a `cooler.RateLimitStore` as the `surf.Store` before the router is built. Routes do not change: `throttle:60,1` and `throttle:<bucket>` count in Redis, with the same fixed-window rules as the memory store. Each attempt is one atomic Lua script, so two instances answering requests from the same client count one window together: with `throttle:2,1`, the third request in the minute gets a 429 whichever instance answers it.
|
||||
When `serve` starts, it calls `cooler.Install`, which builds the Redis client and pings it, and publishes a `cooler.RateLimitStore` as the `surf.Store` and as `cooler.Attempter` before the router is built. Routes do not change: `throttle:60,1` and `throttle:<bucket>` count in Redis, with the same fixed-window rules as the memory store. Each attempt is one atomic Lua script, so two instances answering requests from the same client count one window together: with `throttle:2,1`, the third request in the minute gets a 429 whichever instance answers it. Handlers outside `throttle` (for example the admin mail test-send limit) look up the same `cooler.Attempter` so they share the Redis counters when configured.
|
||||
|
||||
Keys are `<prefix>rl:<key>`. The prefix is `cache.prefix`, or by default `app.name` lower-cased with other characters than letters and digits replaced by `_`, followed by `:`, so several applications can share one Redis.
|
||||
|
||||
|
||||
@@ -59,7 +59,7 @@ Use cases:
|
||||
- Form fields on another plugin's controller: a `pact.AdminActionExtension` with `Form` set to a `pact.AdminFormExtension` places fields and tabs in any admin controller's form by its ID. Its fields document is the `fields.yaml` format plus `before:`/`after:` anchors, `zone:` (only the tab zone for now) and a `tabs:` list, compiled at boot with every `fields.yaml` check; extensions apply in plugin activation order and the form is sent in the compiled order, so the SPA adds no ordering. `Hide` removes owner fields, `Permissions` and `Visible` decide per request who sees the fields (schema, show and save alike), widget fields run the extension's `Actions` and partial fields render from its `Dir` through `PartialData`. Extension values leave the save body before any owner path reads them; `Save` runs in the record's save transaction after the owner row is written (`pact.AdminFormErrors` answers 422, its notices join `meta.notices`) and `Load` serves the values on show. A form no extension lays out compiles unchanged. Unknown anchors, duplicate names, anchor cycles, anchors outside `Requires()`, other zones, `fileupload` fields and clashing widget action or partial names stop the boot naming the plugin, the controller and the name.
|
||||
- Plugins screen: Settings → System → Plugins opens the admin SPA route `/system/plugins` (the settings entry carries `path` instead of a controller) for administrators holding `cabana.PermissionViewPlugins` (`backend.view_plugins`, granted to no role in code; superusers always pass). GET `/plugins` lists the plugins the application was built with from the `party.Installed` metadata `summer build` bakes (name, description, version, source, module and package), or only the IDs of `party.Activated` for an application built before that metadata existed, with the framework version and the state of the plugin registry (`plugins.registry_url`, read through `kiosk.RegistryURL`). With the registry configured, cabana (never the SPA) looks up each versioned plugin's releases through `kiosk.Client` and marks an update when `kiosk.NewestCompatible` finds a release newer than the installed version by `kiosk.Newer` (a `git describe` string or a pseudo-version compares by the tag it builds on), with the `summer plugin:update <id>` command; GET `/plugins/marketplace` searches the registry and adds installed and compatibility markers (compatible when `summer plugin:install` can install some release with the built framework, looking up the releases of a plugin whose newest one needs a newer framework; always compatible when the built framework version is not a release) and the `summer plugin:install <id>` command. Registry calls have a 4 second timeout, at most four run at once, and answers are cached in process (searches 5 minutes, at most 256 distinct searches with expired and then the oldest dropped first, releases 15 minutes, failures 1 minute); a failing registry gives `status` unavailable and never a non-200 answer.
|
||||
- Administrators screen: when some plugin registers admin controllers, `cabana.Activate` also compiles the admin's own screens, an internal plugin with ID `summercms.cabana`. Settings → System → Administrators (controller `cabana.AdministratorsControllerID`, permission `cabana.PermissionManageUsers`) lists backend administrators with their role and last sign-in, opens a preview of each, where record actions (the admin's own and contributed ones) are offered, and creates and edits administrators: login, email, names, a password (hashed at `admin.password.bcrypt_cost`, at least 4 characters and at most 72 bytes), the role and per-administrator permission overrides. The server enforces the privilege rules in the save transaction: only a superuser sees superusers or sends the superuser switch, an administrator can neither grant permissions or roles above their own grants nor change an administrator who holds more than they do, their own role, superuser flag, permissions and password are not changed here, and the last active superuser cannot be demoted. A password set for another administrator ends their sessions (personal API tokens stay valid, as with `admin:reset-password`). Administrators are activated, deactivated and restored by record and bulk actions and deleted softly through `deleted_at` (never hard-deleted); the list shows deleted and deactivated rows with their row states and filters deleted ones, and the preview shows a status hint. Deactivating or deleting an administrator ends their sessions and stops their personal API tokens; the last active superuser cannot be demoted, deactivated or deleted on any of these paths (a transaction-scoped advisory lock serializes the check). The permission codes `cabana.PermissionManageUsers` and `cabana.PermissionManageRoles` are registered with no role grant, so after an upgrade only superusers see the screens until an administrator grants them. An application without admin controllers still activates no admin.
|
||||
- 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 the templates of this process's catalog (rows of uninstalled plugins are hidden) with code, subject, description, locale (Default for a name without a locale suffix) 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_<rule>` (`:message`, `:name`). The index rows are written by `postcard.SyncIndex` through `lagoon.OnDatabase` at activation; a failed sync is logged and retried on the first mail list request of the process. 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) and templates a locale filter, and the forms carry the `info` and `file_version` partials: the file, the status, 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. 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, 13 `colorpicker` colours and a `mailimage` logo; 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`.
|
||||
- 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 the templates of this process's catalog (rows of uninstalled plugins are hidden) with code, subject, description, locale (Default for a name without a locale suffix) 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_<rule>` (`:message`, `:name`). The index rows are written by `postcard.SyncIndex` through `lagoon.OnDatabase` at activation; a failed sync is logged and retried on the first mail list request of the process. 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) and templates a locale filter, and the forms carry the `info` and `file_version` partials: the file, the status, 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. 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, 13 `colorpicker` colours and a `mailimage` logo; 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.
|
||||
|
||||
@@ -623,6 +623,42 @@ func AdminMailImagesShow() {}
|
||||
// @Router /mail/images [post]
|
||||
func AdminMailImagesUpload() {}
|
||||
|
||||
// AdminMailPreview documents POST /mail/preview.
|
||||
//
|
||||
// @Summary Preview a mail draft
|
||||
// @Description Renders an unsaved template, layout, partial or branding draft through postcard's Editor with sample values. Mode template needs system.manage_mail_templates; layout, partial and branding need system.manage_mail_layouts. A draft that does not render is 422 with details field, rule and message.
|
||||
// @Tags admin
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BackendBearer
|
||||
// @Param body body AdminMailPreviewRequest true "Draft mode, id and form values"
|
||||
// @Success 200 {object} Envelope[AdminMailPreviewResult]
|
||||
// @Failure 401 {object} ErrorEnvelope
|
||||
// @Failure 403 {object} ErrorEnvelope
|
||||
// @Failure 404 {object} ErrorEnvelope
|
||||
// @Failure 422 {object} ErrorEnvelope
|
||||
// @Router /mail/preview [post]
|
||||
func AdminMailPreview() {}
|
||||
|
||||
// AdminMailTestSend documents POST /mail/test-send.
|
||||
//
|
||||
// @Summary Send a mail draft to yourself
|
||||
// @Description Sends an unsaved template, layout or partial draft to the signed-in administrator's own email. Interactive sessions only; recipient fields in the body are refused. Limited to five sends per administrator per ten minutes (429 with Retry-After).
|
||||
// @Tags admin
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BackendBearer
|
||||
// @Param body body AdminMailPreviewRequest true "Draft mode, id and form values"
|
||||
// @Success 200 {object} Envelope[AdminMailTestSendResult]
|
||||
// @Failure 401 {object} ErrorEnvelope
|
||||
// @Failure 403 {object} ErrorEnvelope
|
||||
// @Failure 404 {object} ErrorEnvelope
|
||||
// @Failure 422 {object} ErrorEnvelope
|
||||
// @Failure 429 {object} ErrorEnvelope
|
||||
// @Failure 502 {object} ErrorEnvelope
|
||||
// @Router /mail/test-send [post]
|
||||
func AdminMailTestSend() {}
|
||||
|
||||
// AdminListSchema documents the list schema route.
|
||||
//
|
||||
// @Summary Admin list schema
|
||||
|
||||
@@ -69,3 +69,9 @@ fields:
|
||||
type: colorpicker
|
||||
span: left
|
||||
default: "#edeff2"
|
||||
_preview:
|
||||
label: backend::lang.mail.preview.label
|
||||
comment: backend::lang.mail.brand.preview_comment
|
||||
type: mailpreview
|
||||
mode: branding
|
||||
span: full
|
||||
|
||||
@@ -31,6 +31,12 @@ fields:
|
||||
mailImages: true
|
||||
span: full
|
||||
tab: backend::lang.mail.layout.tab_html
|
||||
_preview_html:
|
||||
label: backend::lang.mail.preview.label
|
||||
type: mailpreview
|
||||
mode: layout
|
||||
span: full
|
||||
tab: backend::lang.mail.layout.tab_html
|
||||
content_text:
|
||||
label: backend::lang.mail.layout.text
|
||||
comment: backend::lang.mail.layout.text_comment
|
||||
@@ -39,6 +45,12 @@ fields:
|
||||
size: huge
|
||||
span: full
|
||||
tab: backend::lang.mail.layout.tab_text
|
||||
_preview_text:
|
||||
label: backend::lang.mail.preview.label
|
||||
type: mailpreview
|
||||
mode: layout
|
||||
span: full
|
||||
tab: backend::lang.mail.layout.tab_text
|
||||
content_css:
|
||||
label: backend::lang.mail.layout.css
|
||||
comment: backend::lang.mail.layout.css_comment
|
||||
@@ -48,6 +60,12 @@ fields:
|
||||
mailImages: true
|
||||
span: full
|
||||
tab: backend::lang.mail.layout.tab_css
|
||||
_preview_css:
|
||||
label: backend::lang.mail.preview.label
|
||||
type: mailpreview
|
||||
mode: layout
|
||||
span: full
|
||||
tab: backend::lang.mail.layout.tab_css
|
||||
_file_version:
|
||||
type: partial
|
||||
path: file_version
|
||||
|
||||
@@ -13,6 +13,12 @@ fields:
|
||||
mailImages: true
|
||||
span: full
|
||||
tab: backend::lang.mail.partial.tab_html
|
||||
_preview_html:
|
||||
label: backend::lang.mail.preview.label
|
||||
type: mailpreview
|
||||
mode: partial
|
||||
span: full
|
||||
tab: backend::lang.mail.partial.tab_html
|
||||
content_text:
|
||||
label: backend::lang.mail.partial.text
|
||||
comment: backend::lang.mail.partial.text_comment
|
||||
@@ -21,6 +27,12 @@ fields:
|
||||
size: large
|
||||
span: full
|
||||
tab: backend::lang.mail.partial.tab_text
|
||||
_preview_text:
|
||||
label: backend::lang.mail.preview.label
|
||||
type: mailpreview
|
||||
mode: partial
|
||||
span: full
|
||||
tab: backend::lang.mail.partial.tab_text
|
||||
_file_version:
|
||||
type: partial
|
||||
path: file_version
|
||||
|
||||
@@ -27,6 +27,12 @@ fields:
|
||||
mailImages: true
|
||||
span: full
|
||||
tab: backend::lang.mail.template.tab_template
|
||||
_preview:
|
||||
label: backend::lang.mail.preview.label
|
||||
type: mailpreview
|
||||
mode: template
|
||||
span: full
|
||||
tab: backend::lang.mail.template.tab_template
|
||||
_file_version:
|
||||
type: partial
|
||||
path: file_version
|
||||
|
||||
@@ -354,11 +354,12 @@ func (s *service) mount(r pact.Router) {
|
||||
g.Get("/field-types", s.fieldTypesList)
|
||||
// Form previews render through RenderMarkdown; nothing is stored.
|
||||
g.Post("/markdown/preview", requireAjax(s.markdownPreview))
|
||||
// Mail image library (absolute public URLs); preview and test-send
|
||||
// join these in plan 35-02 Task 4.
|
||||
// Mail image library, preview and test-send (postcard Editor).
|
||||
g.Get("/mail/images", s.mailImagesList)
|
||||
g.Get("/mail/images/{id}", s.mailImagesShow)
|
||||
g.Post("/mail/images", requireAjax(s.mailImagesUpload))
|
||||
g.Post("/mail/preview", requireAjax(s.mailPreview))
|
||||
g.Post("/mail/test-send", interactiveOnly(requireAjax(s.mailTestSend)))
|
||||
g.Get("/settings", s.settingsList)
|
||||
// The read-only Plugins screen (backend.view_plugins).
|
||||
g.Get("/plugins", s.pluginsInstalled)
|
||||
|
||||
@@ -3,14 +3,19 @@ package cabana
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||
"git.golem15.com/golem15/summercms/modules/cooler"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
|
||||
"git.golem15.com/golem15/summercms/modules/postcard"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
@@ -291,3 +296,424 @@ func (s *service) mailMessage(ctx context.Context, key string) string {
|
||||
}
|
||||
return translateKey(ctx, tr, key)
|
||||
}
|
||||
|
||||
// AdminMailPreviewRequest is the body of POST /mail/preview and
|
||||
// POST /mail/test-send: the draft mode, optional record id and the form
|
||||
// values. Recipient fields are refused (decodeStrictBody); test-send always
|
||||
// uses the signed-in administrator's own email.
|
||||
type AdminMailPreviewRequest struct {
|
||||
Mode string `json:"mode"`
|
||||
ID uint64 `json:"id"`
|
||||
Values map[string]any `json:"values"`
|
||||
}
|
||||
|
||||
// AdminMailPreviewResult is the data of a successful preview render.
|
||||
type AdminMailPreviewResult struct {
|
||||
Subject string `json:"subject"`
|
||||
HTML string `json:"html"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
// AdminMailTestSendResult is the data of a successful test send: the address
|
||||
// the draft was delivered to (the administrator's own).
|
||||
type AdminMailTestSendResult struct {
|
||||
Email string `json:"email"`
|
||||
}
|
||||
|
||||
const (
|
||||
mailPreviewModeTemplate = "template"
|
||||
mailPreviewModeLayout = "layout"
|
||||
mailPreviewModePartial = "partial"
|
||||
mailPreviewModeBranding = "branding"
|
||||
|
||||
mailTestMax = 5
|
||||
mailTestDecay = 10 * time.Minute
|
||||
mailTestKeyFmt = "mail_test:%d"
|
||||
|
||||
msgMailPreviewFailed = "The draft could not be previewed."
|
||||
msgMailServerError = "An unexpected error occurred."
|
||||
)
|
||||
|
||||
// mailPreview serves POST /mail/preview: renders an unsaved draft through
|
||||
// postcard.Editor.Preview with sample values.
|
||||
func (s *service) mailPreview(w http.ResponseWriter, r *http.Request) {
|
||||
principal, ok := bouncer.User(r.Context())
|
||||
if !ok || principal == nil || !principal.Backend {
|
||||
WriteError(w, http.StatusUnauthorized, "unauthenticated", msgUnauthenticated)
|
||||
return
|
||||
}
|
||||
if !tokenRouteGate(principal, w) {
|
||||
return
|
||||
}
|
||||
var body AdminMailPreviewRequest
|
||||
if err := s.decodeStrictBody(w, r, &body); err != nil {
|
||||
writeCRUDError(w, err)
|
||||
return
|
||||
}
|
||||
if !s.mailModeAllowed(principal, body.Mode) {
|
||||
WriteError(w, http.StatusForbidden, "forbidden", msgForbidden)
|
||||
return
|
||||
}
|
||||
editor, ok := postcard.EditorFrom(s.app)
|
||||
if !ok || editor == nil {
|
||||
WriteError(w, http.StatusServiceUnavailable, "error", msgMailServerError)
|
||||
return
|
||||
}
|
||||
draft, err := s.mailDraftFromRequest(r.Context(), body)
|
||||
if err != nil {
|
||||
writeCRUDError(w, err)
|
||||
return
|
||||
}
|
||||
preview, err := editor.Preview(r.Context(), draft)
|
||||
if err != nil {
|
||||
s.writeMailDraftError(w, r, err)
|
||||
return
|
||||
}
|
||||
WriteData(w, http.StatusOK, AdminMailPreviewResult{
|
||||
Subject: preview.Subject, HTML: preview.HTML, Text: preview.Text,
|
||||
}, nil)
|
||||
}
|
||||
|
||||
// mailTestSend serves POST /mail/test-send: interactive sessions only, sends
|
||||
// the draft to the signed-in administrator's own email, limited to
|
||||
// mailTestMax per mailTestDecay per administrator.
|
||||
func (s *service) mailTestSend(w http.ResponseWriter, r *http.Request) {
|
||||
principal, ok := bouncer.User(r.Context())
|
||||
if !ok || principal == nil || !principal.Backend {
|
||||
WriteError(w, http.StatusUnauthorized, "unauthenticated", msgUnauthenticated)
|
||||
return
|
||||
}
|
||||
if !tokenRouteGate(principal, w) {
|
||||
return
|
||||
}
|
||||
var body AdminMailPreviewRequest
|
||||
if err := s.decodeStrictBody(w, r, &body); err != nil {
|
||||
writeCRUDError(w, err)
|
||||
return
|
||||
}
|
||||
switch body.Mode {
|
||||
case mailPreviewModeTemplate, mailPreviewModeLayout, mailPreviewModePartial:
|
||||
default:
|
||||
WriteError(w, http.StatusForbidden, "forbidden", msgForbidden)
|
||||
return
|
||||
}
|
||||
if !s.mailModeAllowed(principal, body.Mode) {
|
||||
WriteError(w, http.StatusForbidden, "forbidden", msgForbidden)
|
||||
return
|
||||
}
|
||||
db, err := s.db()
|
||||
if err != nil {
|
||||
WriteError(w, http.StatusInternalServerError, "error", msgServerError)
|
||||
return
|
||||
}
|
||||
var user BackendUser
|
||||
if err := db.WithContext(r.Context()).Select("id", "email").Where("id = ?", principal.ID).Take(&user).Error; err != nil {
|
||||
WriteError(w, http.StatusInternalServerError, "error", msgServerError)
|
||||
return
|
||||
}
|
||||
email := strings.TrimSpace(user.Email)
|
||||
if email == "" {
|
||||
WriteError(w, http.StatusInternalServerError, "error", msgServerError)
|
||||
return
|
||||
}
|
||||
allowed, retryAfter := s.mailTestAttempt(principal.ID)
|
||||
if !allowed {
|
||||
secs := int(retryAfter.Seconds())
|
||||
if secs < 1 {
|
||||
secs = 1
|
||||
}
|
||||
w.Header().Set("Retry-After", strconv.Itoa(secs))
|
||||
WriteError(w, http.StatusTooManyRequests, "rate_limited", s.mailMessage(r.Context(), mailLang+"preview.rate_limited"))
|
||||
return
|
||||
}
|
||||
editor, ok := postcard.EditorFrom(s.app)
|
||||
if !ok || editor == nil {
|
||||
WriteError(w, http.StatusServiceUnavailable, "error", msgMailServerError)
|
||||
return
|
||||
}
|
||||
draft, err := s.mailDraftFromRequest(r.Context(), body)
|
||||
if err != nil {
|
||||
writeCRUDError(w, err)
|
||||
return
|
||||
}
|
||||
if err := editor.SendDraft(r.Context(), draft, email); err != nil {
|
||||
var de *postcard.DraftError
|
||||
if errors.As(err, &de) {
|
||||
s.writeMailDraftError(w, r, err)
|
||||
return
|
||||
}
|
||||
WriteError(w, http.StatusBadGateway, "error", s.mailMessage(r.Context(), mailLang+"preview.test_failed"))
|
||||
return
|
||||
}
|
||||
WriteData(w, http.StatusOK, AdminMailTestSendResult{Email: email}, nil)
|
||||
}
|
||||
|
||||
func (s *service) mailModeAllowed(principal *bouncer.Principal, mode string) bool {
|
||||
switch mode {
|
||||
case mailPreviewModeTemplate:
|
||||
return Allows(principal, []string{PermissionManageMailTemplates})
|
||||
case mailPreviewModeLayout, mailPreviewModePartial, mailPreviewModeBranding:
|
||||
return Allows(principal, []string{PermissionManageMailLayouts})
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (s *service) writeMailDraftError(w http.ResponseWriter, r *http.Request, err error) {
|
||||
var de *postcard.DraftError
|
||||
if !errors.As(err, &de) || de == nil {
|
||||
WriteError(w, http.StatusInternalServerError, "error", msgMailPreviewFailed)
|
||||
return
|
||||
}
|
||||
msg := s.mailDraftMessage(r.Context(), de)
|
||||
WriteErrorDetails(w, http.StatusUnprocessableEntity, "validation_failed", msg, map[string]any{
|
||||
"field": de.Field,
|
||||
"rule": de.Rule,
|
||||
"message": de.Message,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *service) mailDraftMessage(ctx context.Context, de *postcard.DraftError) string {
|
||||
tr := s.translator()
|
||||
key := mailLang + "invalid_" + de.Rule
|
||||
if tr == nil || !tr.Has(key) {
|
||||
if de.Message != "" {
|
||||
return de.Message
|
||||
}
|
||||
return key
|
||||
}
|
||||
return tr.Get(ctx, key, map[string]string{"message": de.Message, "name": de.Name})
|
||||
}
|
||||
|
||||
func (s *service) mailDraftFromRequest(ctx context.Context, body AdminMailPreviewRequest) (postcard.Draft, error) {
|
||||
values := body.Values
|
||||
if values == nil {
|
||||
values = map[string]any{}
|
||||
}
|
||||
switch body.Mode {
|
||||
case mailPreviewModeTemplate:
|
||||
return s.mailTemplateDraft(ctx, body.ID, values)
|
||||
case mailPreviewModeLayout:
|
||||
return s.mailLayoutDraft(ctx, body.ID, values)
|
||||
case mailPreviewModePartial:
|
||||
return s.mailPartialDraft(ctx, body.ID, values)
|
||||
case mailPreviewModeBranding:
|
||||
return s.mailBrandDraft(ctx, values)
|
||||
default:
|
||||
return postcard.Draft{}, &ForbiddenError{Message: msgForbidden}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *service) mailTemplateDraft(ctx context.Context, id uint64, values map[string]any) (postcard.Draft, error) {
|
||||
name, err := s.mailRecordCode(ctx, postcard.TemplatesTable, id)
|
||||
if err != nil {
|
||||
return postcard.Draft{}, err
|
||||
}
|
||||
if editor, ok := postcard.EditorFrom(s.app); ok && editor != nil {
|
||||
if _, ok := editor.Catalog().Template(name); !ok {
|
||||
return postcard.Draft{}, recordNotFound{}
|
||||
}
|
||||
}
|
||||
layoutID, _ := asUint(values["layout"])
|
||||
layout := ""
|
||||
if layoutID > 0 {
|
||||
code, err := s.mailLayoutCodeByID(ctx, layoutID)
|
||||
if err != nil {
|
||||
return postcard.Draft{}, err
|
||||
}
|
||||
layout = code
|
||||
}
|
||||
return postcard.Draft{
|
||||
Kind: postcard.KindTemplate,
|
||||
Name: name,
|
||||
Subject: stringValue(values["subject"]),
|
||||
Body: stringValue(values["body"]),
|
||||
Layout: layout,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *service) mailLayoutDraft(ctx context.Context, id uint64, values map[string]any) (postcard.Draft, error) {
|
||||
name := stringValue(values["code"])
|
||||
if name == "" {
|
||||
name = stringValue(values["name"])
|
||||
}
|
||||
if id > 0 {
|
||||
code, err := s.mailRecordCode(ctx, postcard.LayoutsTable, id)
|
||||
if err != nil {
|
||||
return postcard.Draft{}, err
|
||||
}
|
||||
name = code
|
||||
}
|
||||
return postcard.Draft{
|
||||
Kind: postcard.KindLayout,
|
||||
Name: name,
|
||||
HTML: stringValue(values["content_html"]),
|
||||
Text: stringValue(values["content_text"]),
|
||||
CSS: stringValue(values["content_css"]),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *service) mailPartialDraft(ctx context.Context, id uint64, values map[string]any) (postcard.Draft, error) {
|
||||
name, err := s.mailRecordCode(ctx, postcard.PartialsTable, id)
|
||||
if err != nil {
|
||||
return postcard.Draft{}, err
|
||||
}
|
||||
if editor, ok := postcard.EditorFrom(s.app); ok && editor != nil {
|
||||
if _, ok := editor.Catalog().Partial(name); !ok {
|
||||
return postcard.Draft{}, recordNotFound{}
|
||||
}
|
||||
}
|
||||
return postcard.Draft{
|
||||
Kind: postcard.KindPartial,
|
||||
Name: name,
|
||||
HTML: stringValue(values["content_html"]),
|
||||
Text: stringValue(values["content_text"]),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *service) mailBrandDraft(ctx context.Context, values map[string]any) (postcard.Draft, error) {
|
||||
brand := postcard.Brand{
|
||||
BodyBg: stringValue(values["body_bg"]),
|
||||
ContentBg: stringValue(values["content_bg"]),
|
||||
HeaderColor: stringValue(values["header_color"]),
|
||||
FooterColor: stringValue(values["footer_color"]),
|
||||
HeadingColor: stringValue(values["heading_color"]),
|
||||
TextColor: stringValue(values["text_color"]),
|
||||
LinkColor: stringValue(values["link_color"]),
|
||||
ButtonTextColor: stringValue(values["button_text_color"]),
|
||||
ButtonPrimaryBg: stringValue(values["button_primary_bg"]),
|
||||
ButtonPositiveBg: stringValue(values["button_positive_bg"]),
|
||||
ButtonNegativeBg: stringValue(values["button_negative_bg"]),
|
||||
PanelBg: stringValue(values["panel_bg"]),
|
||||
TableBorderColor: stringValue(values["table_border_color"]),
|
||||
}
|
||||
if raw, ok := values["logo_file_id"]; ok && raw != nil {
|
||||
id, err := asUint(raw)
|
||||
if err == nil && id > 0 {
|
||||
url, err := s.mailLogoAbsoluteURL(ctx, id)
|
||||
if err != nil {
|
||||
return postcard.Draft{}, err
|
||||
}
|
||||
brand.LogoURL = url
|
||||
}
|
||||
}
|
||||
return postcard.Draft{Kind: postcard.KindBrand, Brand: &brand}, nil
|
||||
}
|
||||
|
||||
func (s *service) mailLogoAbsoluteURL(ctx context.Context, id uint) (string, error) {
|
||||
db, err := s.db()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
var f attach.File
|
||||
err = db.WithContext(ctx).
|
||||
Where("id = ? AND attachment_type = ? AND field = ?", id, mailImageLibraryMorph, "images").
|
||||
Take(&f).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return "", &ValidationError{Details: map[string]any{"logo_file_id": []string{"backend::lang.mailimage.missing"}}}
|
||||
}
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return attach.AbsolutePublicURL(s.config(), attach.BlobKey(f.DiskName))
|
||||
}
|
||||
|
||||
func (s *service) mailRecordCode(ctx context.Context, table string, id uint64) (string, error) {
|
||||
if id == 0 {
|
||||
return "", recordNotFound{}
|
||||
}
|
||||
db, err := s.db()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
var codes []string
|
||||
if err := db.WithContext(ctx).Table(table).Where("id = ?", id).Pluck("code", &codes).Error; err != nil {
|
||||
return "", err
|
||||
}
|
||||
if len(codes) == 0 {
|
||||
return "", recordNotFound{}
|
||||
}
|
||||
return codes[0], nil
|
||||
}
|
||||
|
||||
func (s *service) mailLayoutCodeByID(ctx context.Context, id uint) (string, error) {
|
||||
db, err := s.db()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
var codes []string
|
||||
if err := db.WithContext(ctx).Table(postcard.LayoutsTable).Where("id = ?", id).Pluck("code", &codes).Error; err != nil {
|
||||
return "", err
|
||||
}
|
||||
if len(codes) == 0 {
|
||||
return "", &ValidationError{Details: map[string]any{mailLayoutField: []string{s.mailMessage(ctx, mailLang+"invalid_layout")}}}
|
||||
}
|
||||
return codes[0], nil
|
||||
}
|
||||
|
||||
func stringValue(v any) string {
|
||||
if v == nil {
|
||||
return ""
|
||||
}
|
||||
switch s := v.(type) {
|
||||
case string:
|
||||
return s
|
||||
case fmt.Stringer:
|
||||
return s.String()
|
||||
default:
|
||||
return fmt.Sprint(s)
|
||||
}
|
||||
}
|
||||
|
||||
// mailTestAttempt admits one test-send for adminID through a published
|
||||
// cooler.Attempter when present, otherwise the process-local fixed window.
|
||||
func (s *service) mailTestAttempt(adminID uint) (allowed bool, retryAfter time.Duration) {
|
||||
key := fmt.Sprintf(mailTestKeyFmt, adminID)
|
||||
if s != nil && s.app != nil {
|
||||
if attempter, ok := s.app.Lookup[cooler.Attempter](); ok && attempter != nil {
|
||||
ok, _, retry := attempter.Attempt(key, mailTestMax, mailTestDecay)
|
||||
return ok, retry
|
||||
}
|
||||
}
|
||||
ok, _, retry := mailTestLocal.Attempt(key, mailTestMax, mailTestDecay)
|
||||
return ok, retry
|
||||
}
|
||||
|
||||
// mailTestLocal is the in-process fixed-window fallback for test-send when
|
||||
// surf has not published a cooler.Attempter (tests, memory store).
|
||||
var mailTestLocal = newMailTestWindow()
|
||||
|
||||
type mailTestWindow struct {
|
||||
mu sync.Mutex
|
||||
by map[string]mailTestBucket
|
||||
}
|
||||
|
||||
type mailTestBucket struct {
|
||||
count int
|
||||
start time.Time
|
||||
}
|
||||
|
||||
func newMailTestWindow() *mailTestWindow {
|
||||
return &mailTestWindow{by: map[string]mailTestBucket{}}
|
||||
}
|
||||
|
||||
func (w *mailTestWindow) Attempt(key string, max int, decay time.Duration) (bool, int, time.Duration) {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
now := time.Now()
|
||||
b, ok := w.by[key]
|
||||
if !ok || now.Sub(b.start) >= decay {
|
||||
w.by[key] = mailTestBucket{count: 1, start: now}
|
||||
return true, 1, decay
|
||||
}
|
||||
if b.count >= max {
|
||||
retry := decay - now.Sub(b.start)
|
||||
if retry < 0 {
|
||||
retry = 0
|
||||
}
|
||||
return false, b.count, retry
|
||||
}
|
||||
b.count++
|
||||
w.by[key] = b
|
||||
return true, b.count, decay - now.Sub(b.start)
|
||||
}
|
||||
|
||||
@@ -681,6 +681,190 @@ Hi **{{ .name }}**, thanks for joining the Acme blog.
|
||||
env.expect(t, http.StatusForbidden, http.MethodGet, "/summercms/cabana/mailimages/singleton", templatesTok, nil)
|
||||
env.expect(t, http.StatusOK, http.MethodGet, "/summercms/cabana/mailimages/singleton", layoutsTok, nil)
|
||||
})
|
||||
|
||||
t.Run("preview", func(t *testing.T) {
|
||||
user, rootToken := env.admin(t, "mail-preview", true, "")
|
||||
_ = user
|
||||
tmplID := env.mailRowID(t, postcard.TemplatesTable, blogWelcome)
|
||||
layoutID := env.mailRowID(t, postcard.LayoutsTable, blogLayout)
|
||||
got := env.expect(t, http.StatusOK, http.MethodPost, "/mail/preview", rootToken, map[string]any{
|
||||
"mode": "template",
|
||||
"id": tmplID,
|
||||
"values": map[string]any{
|
||||
"subject": "Preview subject",
|
||||
"body": "Hello **{{ .name }}**",
|
||||
"layout": layoutID,
|
||||
},
|
||||
})
|
||||
data, _ := got["data"].(map[string]any)
|
||||
if fmt.Sprint(data["subject"]) != "Preview subject" {
|
||||
t.Fatalf("subject = %#v", data["subject"])
|
||||
}
|
||||
html := fmt.Sprint(data["html"])
|
||||
if strings.Contains(strings.ToLower(html), "<script") {
|
||||
t.Fatalf("html carries a script: %s", html)
|
||||
}
|
||||
if !strings.Contains(html, "Ada") && !strings.Contains(html, "[name]") {
|
||||
t.Fatalf("html missing sample or placeholder: %s", html)
|
||||
}
|
||||
env.expect(t, http.StatusUnprocessableEntity, http.MethodPost, "/mail/preview", rootToken, map[string]any{
|
||||
"mode": "template",
|
||||
"id": tmplID,
|
||||
"values": map[string]any{
|
||||
"subject": "x",
|
||||
"body": `{{ partial "no.such.partial" }}`,
|
||||
"layout": layoutID,
|
||||
},
|
||||
})
|
||||
env.expect(t, http.StatusOK, http.MethodPost, "/mail/preview", rootToken, map[string]any{
|
||||
"mode": "layout",
|
||||
"id": 0,
|
||||
"values": map[string]any{
|
||||
"content_html": `<div class="preview-layout">{{ .Content }}</div>`,
|
||||
"content_text": "{{ .Content }}",
|
||||
"content_css": "",
|
||||
},
|
||||
})
|
||||
partialID := env.mailRowID(t, postcard.PartialsTable, blogCard)
|
||||
env.expect(t, http.StatusOK, http.MethodPost, "/mail/preview", rootToken, map[string]any{
|
||||
"mode": "partial",
|
||||
"id": partialID,
|
||||
"values": map[string]any{
|
||||
"content_html": `<div>{{ .title }}</div>`,
|
||||
"content_text": "{{ .title }}",
|
||||
},
|
||||
})
|
||||
env.expect(t, http.StatusOK, http.MethodPost, "/mail/preview", rootToken, map[string]any{
|
||||
"mode": "branding",
|
||||
"id": 0,
|
||||
"values": map[string]any{
|
||||
"button_primary_bg": "#112233",
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
t.Run("preview_permissions", func(t *testing.T) {
|
||||
_, templatesTok := env.admin(t, "mail-prev-tmpl", false, `{"system.manage_mail_templates":1}`)
|
||||
_, layoutsTok := env.admin(t, "mail-prev-lay", false, `{"system.manage_mail_layouts":1}`)
|
||||
tmplID := env.mailRowID(t, postcard.TemplatesTable, blogWelcome)
|
||||
layoutID := env.mailRowID(t, postcard.LayoutsTable, blogLayout)
|
||||
env.expect(t, http.StatusOK, http.MethodPost, "/mail/preview", templatesTok, map[string]any{
|
||||
"mode": "template", "id": tmplID,
|
||||
"values": map[string]any{"subject": "s", "body": "b", "layout": layoutID},
|
||||
})
|
||||
env.expect(t, http.StatusForbidden, http.MethodPost, "/mail/preview", templatesTok, map[string]any{
|
||||
"mode": "layout", "id": 0,
|
||||
"values": map[string]any{"content_html": "{{ .Content }}", "content_text": "{{ .Content }}"},
|
||||
})
|
||||
env.expect(t, http.StatusForbidden, http.MethodPost, "/mail/preview", templatesTok, map[string]any{
|
||||
"mode": "partial", "id": env.mailRowID(t, postcard.PartialsTable, blogCard),
|
||||
"values": map[string]any{"content_html": "x", "content_text": "x"},
|
||||
})
|
||||
env.expect(t, http.StatusForbidden, http.MethodPost, "/mail/preview", templatesTok, map[string]any{
|
||||
"mode": "branding", "id": 0, "values": map[string]any{},
|
||||
})
|
||||
env.expect(t, http.StatusForbidden, http.MethodPost, "/mail/preview", layoutsTok, map[string]any{
|
||||
"mode": "template", "id": tmplID,
|
||||
"values": map[string]any{"subject": "s", "body": "b", "layout": layoutID},
|
||||
})
|
||||
env.expect(t, http.StatusOK, http.MethodPost, "/mail/preview", layoutsTok, map[string]any{
|
||||
"mode": "layout", "id": 0,
|
||||
"values": map[string]any{"content_html": "{{ .Content }}", "content_text": "{{ .Content }}"},
|
||||
})
|
||||
})
|
||||
|
||||
t.Run("test_send", func(t *testing.T) {
|
||||
user, tok := env.admin(t, "mail-test-send", true, "")
|
||||
tmplID := env.mailRowID(t, postcard.TemplatesTable, blogWelcome)
|
||||
layoutID := env.mailRowID(t, postcard.LayoutsTable, blogLayout)
|
||||
before := len(env.driver.messages())
|
||||
got := env.expect(t, http.StatusOK, http.MethodPost, "/mail/test-send", tok, map[string]any{
|
||||
"mode": "template",
|
||||
"id": tmplID,
|
||||
"values": map[string]any{
|
||||
"subject": "Test subject",
|
||||
"body": "Hello {{ .name }}",
|
||||
"layout": layoutID,
|
||||
},
|
||||
})
|
||||
if fmt.Sprint(got["data"].(map[string]any)["email"]) != user.Email {
|
||||
t.Fatalf("email = %#v want %s", got["data"], user.Email)
|
||||
}
|
||||
msgs := env.driver.messages()
|
||||
if len(msgs) != before+1 {
|
||||
t.Fatalf("messages = %d want %d", len(msgs), before+1)
|
||||
}
|
||||
last := msgs[len(msgs)-1]
|
||||
if len(last.To) != 1 || last.To[0] != user.Email || len(last.Cc) != 0 || len(last.Bcc) != 0 {
|
||||
t.Fatalf("recipients To=%v Cc=%v Bcc=%v", last.To, last.Cc, last.Bcc)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("test_send_recipient", func(t *testing.T) {
|
||||
user, tok := env.admin(t, "mail-test-recip", true, "")
|
||||
tmplID := env.mailRowID(t, postcard.TemplatesTable, blogWelcome)
|
||||
layoutID := env.mailRowID(t, postcard.LayoutsTable, blogLayout)
|
||||
values := map[string]any{"subject": "s", "body": "b", "layout": layoutID}
|
||||
for _, key := range []string{"to", "email", "recipient"} {
|
||||
body := map[string]any{"mode": "template", "id": tmplID, "values": values, key: "other@example.test"}
|
||||
rec := env.call(t, http.MethodPost, "/mail/test-send", tok, body)
|
||||
if rec.Code != http.StatusUnprocessableEntity {
|
||||
t.Fatalf("%s key status=%d want 422 body=%s", key, rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
plain, err := cabana.IssueTestAPIToken(env.gdb, user.ID, []string{"*"}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := env.call(t, http.MethodPost, "/mail/test-send", plain, map[string]any{
|
||||
"mode": "template", "id": tmplID, "values": values,
|
||||
})
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("API token status=%d want 403 body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("test_send_limit", func(t *testing.T) {
|
||||
userA, tokA := env.admin(t, "mail-limit-a", true, "")
|
||||
userB, tokB := env.admin(t, "mail-limit-b", true, "")
|
||||
_ = userA
|
||||
tmplID := env.mailRowID(t, postcard.TemplatesTable, blogWelcome)
|
||||
layoutID := env.mailRowID(t, postcard.LayoutsTable, blogLayout)
|
||||
body := map[string]any{
|
||||
"mode": "template", "id": tmplID,
|
||||
"values": map[string]any{"subject": "s", "body": "b", "layout": layoutID},
|
||||
}
|
||||
for i := 0; i < 5; i++ {
|
||||
env.expect(t, http.StatusOK, http.MethodPost, "/mail/test-send", tokA, body)
|
||||
}
|
||||
rec := env.call(t, http.MethodPost, "/mail/test-send", tokA, body)
|
||||
if rec.Code != http.StatusTooManyRequests {
|
||||
t.Fatalf("sixth status=%d want 429 body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec.Header().Get("Retry-After") == "" {
|
||||
t.Fatal("missing Retry-After")
|
||||
}
|
||||
env.expect(t, http.StatusOK, http.MethodPost, "/mail/test-send", tokB, body)
|
||||
_ = userB
|
||||
})
|
||||
|
||||
t.Run("test_send_driver_failure", func(t *testing.T) {
|
||||
_, tok := env.admin(t, "mail-test-fail", true, "")
|
||||
tmplID := env.mailRowID(t, postcard.TemplatesTable, blogWelcome)
|
||||
layoutID := env.mailRowID(t, postcard.LayoutsTable, blogLayout)
|
||||
env.driver.fail.Store(true)
|
||||
t.Cleanup(func() { env.driver.fail.Store(false) })
|
||||
rec := env.call(t, http.MethodPost, "/mail/test-send", tok, map[string]any{
|
||||
"mode": "template", "id": tmplID,
|
||||
"values": map[string]any{"subject": "s", "body": "b", "layout": layoutID},
|
||||
})
|
||||
if rec.Code != http.StatusBadGateway {
|
||||
t.Fatalf("status=%d want 502 body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if strings.Contains(rec.Body.String(), "connection refused") {
|
||||
t.Fatalf("driver error leaked: %s", rec.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// mailUpload POSTs a multipart file to /mail/images.
|
||||
|
||||
@@ -32,6 +32,7 @@ import (
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"git.golem15.com/golem15/summercms/modules/party"
|
||||
"git.golem15.com/golem15/summercms/modules/phrasebook"
|
||||
"git.golem15.com/golem15/summercms/modules/postcard"
|
||||
"git.golem15.com/golem15/summercms/modules/signpost"
|
||||
"git.golem15.com/golem15/summercms/modules/surf"
|
||||
"gocloud.dev/blob"
|
||||
@@ -470,6 +471,26 @@ func conformCases() []conformCase {
|
||||
}
|
||||
return e.send(t, http.MethodGet, fmt.Sprintf("/mail/images/%d", e.mailImageID), nil, true)
|
||||
}, into[cabana.Envelope[cabana.AdminMailImage]](), nil},
|
||||
{"POST /mail/preview", 200, "cabana.Envelope-cabana_AdminMailPreviewResult", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder {
|
||||
return e.send(t, http.MethodPost, "/mail/preview", map[string]any{
|
||||
"mode": "branding",
|
||||
"id": 0,
|
||||
"values": map[string]any{
|
||||
"button_primary_bg": "#112233",
|
||||
},
|
||||
}, true)
|
||||
}, into[cabana.Envelope[cabana.AdminMailPreviewResult]](), nil},
|
||||
{"POST /mail/test-send", 200, "cabana.Envelope-cabana_AdminMailTestSendResult", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder {
|
||||
return e.send(t, http.MethodPost, "/mail/test-send", map[string]any{
|
||||
"mode": "layout",
|
||||
"id": 0,
|
||||
"values": map[string]any{
|
||||
"content_html": "{{ .Content }}",
|
||||
"content_text": "{{ .Content }}",
|
||||
"content_css": "",
|
||||
},
|
||||
}, true)
|
||||
}, into[cabana.Envelope[cabana.AdminMailTestSendResult]](), nil},
|
||||
{"GET /{vendor}/{plugin}/{controller}/schema/list", 200, "cabana.Envelope-cabana_ListSchema", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder {
|
||||
rec := e.send(t, http.MethodGet, "/acme/conform/gadgets/schema/list", nil, true)
|
||||
var body cabana.Envelope[cabana.ListSchema]
|
||||
@@ -1087,7 +1108,7 @@ func newConformEnv(t *testing.T) *conformEnv {
|
||||
// plugins.registry_url "" keeps GET /plugins from calling a registry.
|
||||
for key, value := range map[string]any{
|
||||
"http.body_limits.default_bytes": 1048576,
|
||||
"http.body_limits.upload_bytes": 1048576,
|
||||
"http.body_limits.upload_bytes": 8388608,
|
||||
"plugins.registry_url": "",
|
||||
"app.url": "https://conform.example.test",
|
||||
} {
|
||||
@@ -1107,6 +1128,12 @@ func newConformEnv(t *testing.T) *conformEnv {
|
||||
if err := attach.Publish(app, bucket); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mailer := postcard.NewMailer(nil, postcard.NewMemoryDriver(), postcard.Options{
|
||||
From: "noreply@example.test", Overrides: postcard.NewDBSource(app),
|
||||
})
|
||||
if err := app.Publish[postcard.Mailer](mailer); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The acme.companions fixture serves the Phase 17 routes (dependent
|
||||
// options) next to the gadgets.
|
||||
plugins := []party.Plugin{conformPlugin{stamp: stamp}, companionsPlugin{app: app}}
|
||||
|
||||
@@ -100,6 +100,8 @@ func TestPhase10Coverage(t *testing.T) {
|
||||
"POST /auth/logout",
|
||||
"POST /auth/refresh",
|
||||
"POST /mail/images",
|
||||
"POST /mail/preview",
|
||||
"POST /mail/test-send",
|
||||
"POST /markdown/preview",
|
||||
"POST /{vendor}/{plugin}/{controller}",
|
||||
"POST /{vendor}/{plugin}/{controller}/bulk-delete",
|
||||
|
||||
@@ -73,9 +73,9 @@ 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
|
||||
if unsafe != 36 {
|
||||
t.Fatalf("walked %d state-changing routes, want 36: %v", unsafe, router.order)
|
||||
// mail image upload, mail preview, mail test-send
|
||||
if unsafe != 38 {
|
||||
t.Fatalf("walked %d state-changing routes, want 38: %v", unsafe, router.order)
|
||||
}
|
||||
|
||||
loginHandler := router.handlers[login]
|
||||
|
||||
@@ -62,6 +62,8 @@ var phase09Routes = []adminRoute{
|
||||
{key: "GET /mail/images"},
|
||||
{key: "GET /mail/images/{id}"},
|
||||
{key: "POST /mail/images"},
|
||||
{key: "POST /mail/preview"},
|
||||
{key: "POST /mail/test-send"},
|
||||
{key: "GET /{vendor}/{plugin}/{controller}/schema/list"},
|
||||
{key: "GET /{vendor}/{plugin}/{controller}/schema/form"},
|
||||
{key: "GET /{vendor}/{plugin}/{controller}/schema/relation/{name}"},
|
||||
|
||||
@@ -58,6 +58,8 @@ var tokenRouteClasses = map[string]tokenRouteClass{
|
||||
"GET /mail/images": classExplicitGate,
|
||||
"GET /mail/images/{id}": classExplicitGate,
|
||||
"POST /mail/images": classExplicitGate,
|
||||
"POST /mail/preview": classExplicitGate,
|
||||
"POST /mail/test-send": classInteractive,
|
||||
|
||||
"GET /{vendor}/{plugin}/{controller}/schema/list": classAllowsProtect,
|
||||
"GET /{vendor}/{plugin}/{controller}/schema/form": classAllowsProtect,
|
||||
@@ -180,6 +182,7 @@ func TestTokenRouteGates(t *testing.T) {
|
||||
"POST /account/avatar", "DELETE /account/avatar",
|
||||
"GET /account/tokens", "POST /account/tokens", "GET /account/tokens/scopes",
|
||||
"DELETE /account/tokens/{id}", "POST /auth/refresh", "POST /auth/logout",
|
||||
"POST /mail/test-send",
|
||||
}
|
||||
for _, key := range interactivePaths {
|
||||
if tokenRouteClasses[key] != classInteractive {
|
||||
|
||||
@@ -717,9 +717,24 @@ mail:
|
||||
no_public_url: "Mail images need an absolute address. Set storage.uploads.public_url or app.url in the configuration."
|
||||
preview:
|
||||
label: "Preview"
|
||||
test_send: "Send test to myself"
|
||||
test_sent: "Test sent to :email."
|
||||
test_failed: "The test could not be sent. Try again later."
|
||||
html: "HTML"
|
||||
text: "Plain text"
|
||||
subject: "Subject"
|
||||
frame_title: "Preview of the HTML message"
|
||||
rendering: "Rendering preview…"
|
||||
empty: "Nothing to preview yet. Write the message first."
|
||||
failed: "The draft cannot be rendered: :message The preview shows the last version that rendered."
|
||||
failed_first: "The draft cannot be rendered: :message"
|
||||
unavailable: "Preview unavailable. It updates again with your next edit."
|
||||
sample_note: "Variables are filled with sample values. A variable without a sample shows as [name]."
|
||||
sample_content_note: "Previewed with sample content."
|
||||
test_send: "Send test to me"
|
||||
test_sending: "Sending…"
|
||||
test_hint: "Sends the current draft, unsaved changes included, to :email."
|
||||
test_sent: "Test message sent to :email."
|
||||
test_limited: "You have sent too many test messages. Try again in :seconds s."
|
||||
test_invalid: "Fix the draft before sending a test: :message"
|
||||
test_failed: "The test message could not be sent. Check the mail settings and the application log."
|
||||
rate_limited: "You have sent too many test messages. Try again in a few minutes."
|
||||
picker:
|
||||
insert_button: "Insert image"
|
||||
|
||||
@@ -755,9 +755,24 @@ mail:
|
||||
no_public_url: "Obrazy w wiadomościach wymagają pełnego adresu. Ustaw storage.uploads.public_url lub app.url w konfiguracji."
|
||||
preview:
|
||||
label: "Podgląd"
|
||||
test_send: "Wyślij test do siebie"
|
||||
test_sent: "Test wysłano na :email."
|
||||
test_failed: "Nie udało się wysłać testu. Spróbuj ponownie później."
|
||||
html: "HTML"
|
||||
text: "Zwykły tekst"
|
||||
subject: "Temat"
|
||||
frame_title: "Podgląd wiadomości HTML"
|
||||
rendering: "Renderowanie podglądu…"
|
||||
empty: "Nie ma jeszcze czego podglądać. Najpierw napisz treść wiadomości."
|
||||
failed: "Nie można wyrenderować wersji roboczej: :message Podgląd pokazuje ostatnią wersję, która się wyrenderowała."
|
||||
failed_first: "Nie można wyrenderować wersji roboczej: :message"
|
||||
unavailable: "Podgląd niedostępny. Odświeży się przy następnej zmianie."
|
||||
sample_note: "Zmienne są wypełnione przykładowymi wartościami. Zmienna bez przykładu jest pokazana jako [nazwa]."
|
||||
sample_content_note: "Podgląd z przykładową treścią."
|
||||
test_send: "Wyślij test do mnie"
|
||||
test_sending: "Wysyłanie…"
|
||||
test_hint: "Wysyła bieżącą wersję roboczą, razem z niezapisanymi zmianami, na adres :email."
|
||||
test_sent: "Wysłano wiadomość testową na adres :email."
|
||||
test_limited: "Wysłano zbyt wiele wiadomości testowych. Spróbuj ponownie za :seconds s."
|
||||
test_invalid: "Popraw wersję roboczą przed wysłaniem testu: :message"
|
||||
test_failed: "Nie udało się wysłać wiadomości testowej. Sprawdź ustawienia poczty i log aplikacji."
|
||||
rate_limited: "Wysłano zbyt wiele wiadomości testowych. Spróbuj ponownie za kilka minut."
|
||||
picker:
|
||||
insert_button: "Wstaw obraz"
|
||||
|
||||
@@ -196,7 +196,7 @@ http:
|
||||
supports_credentials: true
|
||||
```
|
||||
|
||||
The `serve` command also opens the database through [lagoon](../lagoon/README.md) and the uploads bucket through `attach.OpenBucket`, so their settings must be present as well. It then installs [cooler](../cooler/README.md) (`cooler.Install`) before it builds the router: with `http.rate_limit.store: redis` it publishes cooler's Redis-backed store as the `surf.Store`, falling back to a per-instance `surf.MemoryStore` while Redis does not answer. A Redis that is down at start-up is a warning, not a boot failure; a missing or malformed `redis.url` is. It starts the background job worker of [conga](../conga/README.md) in the same process unless `queue.work_in_serve` is `false` (default `true`); set it to `false` when a separate `queue:work` process runs the jobs. The other `queue.*` keys are documented in the conga README.
|
||||
The `serve` command also opens the database through [lagoon](../lagoon/README.md) and the uploads bucket through `attach.OpenBucket`, so their settings must be present as well. It then installs [cooler](../cooler/README.md) (`cooler.Install`) before it builds the router: with `http.rate_limit.store: redis` it publishes cooler's Redis-backed store as the `surf.Store` and as `cooler.Attempter` (for fixed-window admission outside `throttle`, such as the admin mail test-send limit), falling back to a per-instance `surf.MemoryStore` while Redis does not answer. A Redis that is down at start-up is a warning, not a boot failure; a missing or malformed `redis.url` is. It starts the background job worker of [conga](../conga/README.md) in the same process unless `queue.work_in_serve` is `false` (default `true`); set it to `false` when a separate `queue:work` process runs the jobs. The other `queue.*` keys are documented in the conga README.
|
||||
|
||||
## CLI commands
|
||||
|
||||
|
||||
@@ -234,7 +234,14 @@ func installCooler(ctx context.Context, app *backpack.App) (*cooler.Handle, erro
|
||||
}
|
||||
if h.RateLimitRedis() {
|
||||
// longest bucket decay is 1 minute; sweep at 2x (as BuildRouter)
|
||||
if err := app.Publish[Store](h.RateLimitStore(NewMemoryStore(2 * time.Minute))); err != nil {
|
||||
store := h.RateLimitStore(NewMemoryStore(2 * time.Minute))
|
||||
if err := app.Publish[Store](store); err != nil {
|
||||
_ = h.Close()
|
||||
return nil, fmt.Errorf("surf: %w", err)
|
||||
}
|
||||
// cabana looks this up for the mail test-send limit (and any other
|
||||
// fixed-window admission outside BuildRouter's throttle middleware).
|
||||
if err := app.Publish[cooler.Attempter](store); err != nil {
|
||||
_ = h.Close()
|
||||
return nil, fmt.Errorf("surf: %w", err)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user