From 624d040bd896e52287971888a335dc7e57f20c13 Mon Sep 17 00:00:00 2001 From: EinfacheSache <69739334+EinfacheSache@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:02:06 +0100 Subject: [PATCH] feat(ui): render message action buttons (client::action) Render the HTTP action buttons defined in extras["client::action"].buttons as proposed in #494. Clicking a button sends the configured request via fetch (method, url, headers, body). Only http(s) URLs are accepted, invalid buttons are skipped and reported in a warning. Cookies are not sent (credentials: omit) and the result is reported via a snackbar. --- ui/package.json | 3 +- ui/src/message/Message.tsx | 2 + ui/src/message/MessageActions.tsx | 124 +++++++++++++++++++++++++++ ui/src/message/extras.test.ts | 102 ++++++++++++++++++++++ ui/src/message/extras.ts | 66 ++++++++++---- ui/src/tests/message-actions.test.ts | 106 +++++++++++++++++++++++ ui/yarn.lock | 5 ++ 7 files changed, 392 insertions(+), 16 deletions(-) create mode 100644 ui/src/message/MessageActions.tsx create mode 100644 ui/src/message/extras.test.ts create mode 100644 ui/src/tests/message-actions.test.ts diff --git a/ui/package.json b/ui/package.json index 7b9260259..1e12c0fa4 100644 --- a/ui/package.json +++ b/ui/package.json @@ -33,7 +33,8 @@ "remove-markdown": "^0.8.0", "tss-react": "^4.9.19", "vite": "^8.0.8", - "vitest": "^5.0.0" + "vitest": "^5.0.0", + "zod": "^4.6.7" }, "scripts": { "start": "vite", diff --git a/ui/src/message/Message.tsx b/ui/src/message/Message.tsx index 9ea99f5a3..d5aa6cc46 100644 --- a/ui/src/message/Message.tsx +++ b/ui/src/message/Message.tsx @@ -11,6 +11,7 @@ import {Markdown} from '../common/Markdown'; import * as config from '../config'; import {IMessageExtras} from '../types'; import {contentType, RenderMode} from './extras'; +import {MessageActions} from './MessageActions'; import {TimeAgoFormatter} from '../common/TimeAgoFormatter'; const PREVIEW_LENGTH = 500; @@ -212,6 +213,7 @@ const Message = ({ {expanded ? 'Read Less' : 'Read More'} )} + ); diff --git a/ui/src/message/MessageActions.tsx b/ui/src/message/MessageActions.tsx new file mode 100644 index 000000000..530f43a43 --- /dev/null +++ b/ui/src/message/MessageActions.tsx @@ -0,0 +1,124 @@ +import Alert from '@mui/material/Alert'; +import Button from '@mui/material/Button'; +import CircularProgress from '@mui/material/CircularProgress'; +import Tooltip from '@mui/material/Tooltip'; +import React from 'react'; +import {makeStyles} from 'tss-react/mui'; +import {useStores} from '../stores'; +import {IMessageExtras} from '../types'; +import {actionButtons, IActionButton} from './extras'; + +const useStyles = makeStyles()((theme) => ({ + actions: { + width: '100%', + display: 'flex', + flexWrap: 'wrap', + gap: theme.spacing(1), + marginTop: theme.spacing(1.5), + }, + error: { + width: '100%', + marginTop: theme.spacing(1.5), + }, + errorDetails: { + whiteSpace: 'pre-wrap', + margin: 0, + marginTop: theme.spacing(1), + }, +})); + +const executeAction = ({http}: IActionButton): Promise => + fetch(http.url, { + method: http.method, + headers: http.headers, + body: http.body, + credentials: 'omit', + referrerPolicy: 'no-referrer', + }); + +const describeTarget = ({http}: IActionButton) => { + const url = new URL(http.url); + return `${http.method} ${url.host}${url.pathname}`; +}; + +const ActionButton = ({button}: {button: IActionButton}) => { + const {snackManager} = useStores(); + const [running, setRunning] = React.useState(false); + + const onClick = async () => { + setRunning(true); + try { + const response = await executeAction(button); + if (response.ok) { + snackManager.snack(`Action '${button.label}' succeeded.`); + } else { + snackManager.snack( + `Action '${button.label}' failed: ${response.status} ${response.statusText}`.trim() + ); + } + } catch { + snackManager.snack( + `Action '${button.label}': no readable response (network error or CORS). The request may still have been processed.` + ); + } finally { + setRunning(false); + } + }; + + return ( + + + : undefined}> + {button.label} + + + + ); +}; + +const ActionError = ({error}: {error: string}) => { + const {classes} = useStyles(); + const [showDetails, setShowDetails] = React.useState(false); + return ( + setShowDetails((show) => !show)}> + {showDetails ? 'Hide details' : 'Details'} + + }> + This message contains invalid action buttons. + {showDetails && ( + {error} + )} + + ); +}; + +export const MessageActions = ({extras}: {extras?: IMessageExtras}) => { + const {classes} = useStyles(); + const {buttons, error} = React.useMemo(() => actionButtons(extras), [extras]); + return ( + <> + {buttons.length > 0 && ( + + {buttons.map((button, index) => ( + + ))} + + )} + {error && } + > + ); +}; diff --git a/ui/src/message/extras.test.ts b/ui/src/message/extras.test.ts new file mode 100644 index 000000000..eabde4c7a --- /dev/null +++ b/ui/src/message/extras.test.ts @@ -0,0 +1,102 @@ +import {describe, expect, it} from 'vitest'; +import {actionButtons} from './extras'; + +const button = (http: object) => ({ + label: 'test', + http: {method: 'POST', url: 'https://x.y/', ...http}, +}); +const parse = (...buttons: unknown[]) => actionButtons({'client::action': {buttons}}); + +describe('actionButtons', () => { + it('returns nothing without client::action', () => { + expect(actionButtons(undefined)).toEqual({buttons: []}); + expect(actionButtons({})).toEqual({buttons: []}); + expect(actionButtons({'client::action': null})).toEqual({buttons: []}); + }); + + it.each([{}, {buttons: 'nope'}])('reports a malformed client::action %j', (action) => { + const result = actionButtons({'client::action': action}); + expect(result.buttons).toEqual([]); + expect(result.error).toContain('→ at ["client::action"].buttons'); + }); + + it('parses the format from gotify/server#494', () => { + const result = parse( + { + label: 'Power off', + http: { + method: 'post', + url: 'https://example.com/power_off?id=5', + headers: {Authorization: 'bearer token'}, + }, + }, + {label: 'Dismiss', http: {method: 'get', url: 'http://example.com/dismiss'}} + ); + expect(result).toEqual({ + buttons: [ + { + label: 'Power off', + http: { + method: 'POST', + url: 'https://example.com/power_off?id=5', + headers: {Authorization: 'bearer token'}, + }, + }, + { + label: 'Dismiss', + http: {method: 'GET', url: 'http://example.com/dismiss', headers: {}}, + }, + ], + }); + }); + + it('reports every invalid button and keeps the valid ones', () => { + const result = parse( + button({url: 'ftp://x.y/'}), + {label: 'ok', http: {method: 'POST', url: 'https://x.y/'}}, + button({method: 1}) + ); + expect(result.buttons.map((b) => b.label)).toEqual(['ok']); + expect(result.error).toContain('→ at ["client::action"].buttons[0].http.url'); + expect(result.error).toContain('→ at ["client::action"].buttons[2].http.method'); + }); + + it('reports requests fetch cannot send', () => { + const result = parse( + button({method: 'get', body: 'a'}), + button({method: 'trace'}), + button({method: 'post', body: 'a'}) + ); + expect(result.buttons.map((b) => b.http.method)).toEqual(['POST']); + expect(result.error).toContain( + 'GET and HEAD requests cannot have a body\n → at ["client::action"].buttons[0].http.body' + ); + expect(result.error).toContain( + 'Unsupported method\n → at ["client::action"].buttons[1].http.method' + ); + }); + + it.each([ + ['null', null], + ['a string', 'string'], + ['an empty label', {label: '', http: {method: 'POST', url: 'https://x.y/'}}], + ['a blank label', {label: ' ', http: {method: 'POST', url: 'https://x.y/'}}], + ['a missing http', {label: 'no http'}], + ['a missing url', button({url: undefined})], + ['a missing method', button({method: undefined})], + ['an invalid url', button({url: 'not a url'})], + ['a javascript url', button({url: 'javascript:alert(1)'})], + ['a data url', button({url: 'data:text/plain,hi'})], + ['a non-string header', button({headers: {A: 'b', C: 1}})], + ['a non-string body', button({body: {a: 1}})], + ['a GET body', button({method: 'get', body: 'a'})], + ['a HEAD body', button({method: 'HEAD', body: ''})], + ['the CONNECT method', button({method: 'connect'})], + ['the TRACE method', button({method: 'TRACE'})], + ['the TRACK method', button({method: 'track'})], + ])('rejects a button with %s', (_, invalid) => { + const result = parse(invalid); + expect(result.buttons).toEqual([]); + expect(result.error).toContain('→ at ["client::action"].buttons[0]'); + }); +}); diff --git a/ui/src/message/extras.ts b/ui/src/message/extras.ts index 976d57580..2b396d3a4 100644 --- a/ui/src/message/extras.ts +++ b/ui/src/message/extras.ts @@ -1,3 +1,4 @@ +import {z} from 'zod/mini'; import {IMessageExtras} from '../types'; export enum RenderMode { @@ -5,25 +6,60 @@ export enum RenderMode { Plain = 'text/plain', } +const displayExtras = z.object({ + 'client::display': z.object({contentType: z.enum(RenderMode)}), +}); + export const contentType = (extras?: IMessageExtras): RenderMode => { - const type = extract(extras, 'client::display', 'contentType'); - const valid = Object.values(RenderMode).includes(type); - return valid ? type : RenderMode.Plain; + const result = displayExtras.safeParse(extras); + return result.success ? result.data['client::display'].contentType : RenderMode.Plain; }; -// eslint-disable-next-line @typescript-eslint/no-explicit-any -const extract = (extras: IMessageExtras | undefined, key: string, path: string): any => { - if (!extras) { - return null; - } +// fetch rejects these methods and a body on GET/HEAD requests without sending anything. +const forbiddenMethods = ['CONNECT', 'TRACE', 'TRACK']; +const bodylessMethods = ['GET', 'HEAD']; + +const httpAction = z + .object({ + method: z.string().check( + z.toUpperCase(), + z.refine((method) => !forbiddenMethods.includes(method), 'Unsupported method') + ), + url: z.url({protocol: /^https?$/}), + headers: z._default(z.record(z.string(), z.string()), {}), + body: z.optional(z.string()), + }) + .check( + z.refine(({method, body}) => body === undefined || !bodylessMethods.includes(method), { + message: 'GET and HEAD requests cannot have a body', + path: ['body'], + }) + ); + +const actionButton = z.object({ + label: z.string().check(z.trim(), z.minLength(1)), + http: httpAction, +}); + +export type IActionButton = z.infer; - if (!extras[key]) { - return null; - } +const actionExtras = z.optional( + z.object({ + 'client::action': z.nullish(z.object({buttons: z.array(actionButton)})), + }) +); - if (!extras[key][path]) { - return null; - } +const validButtons = (rawButtons: unknown): IActionButton[] => + Array.isArray(rawButtons) + ? rawButtons.flatMap((rawButton) => actionButton.safeParse(rawButton).data ?? []) + : []; - return extras[key][path]; +export const actionButtons = ( + extras?: IMessageExtras +): {buttons: IActionButton[]; error?: string} => { + const {error} = actionExtras.safeParse(extras); + return { + buttons: validButtons(extras?.['client::action']?.buttons), + error: error && z.prettifyError(error), + }; }; diff --git a/ui/src/tests/message-actions.test.ts b/ui/src/tests/message-actions.test.ts new file mode 100644 index 000000000..86df57e79 --- /dev/null +++ b/ui/src/tests/message-actions.test.ts @@ -0,0 +1,106 @@ +import {Page} from 'puppeteer'; +import {newTest, GotifyTest} from './setup'; +import {clickByText, waitForExists} from './utils'; +import {afterAll, beforeAll, describe, expect, it} from 'vitest'; +import * as auth from './authentication'; +import {IApplication} from '../types'; + +let page: Page; +let gotify: GotifyTest; +let app: IApplication; + +const adminHeaders = {Authorization: `Basic ${btoa('admin:admin')}`}; + +beforeAll(async () => { + gotify = await newTest(); + page = gotify.page; +}); + +afterAll(async () => await gotify.close()); + +describe('Message actions', () => { + it('creates an app', async () => { + app = await fetch(`${gotify.url}/application`, { + method: 'POST', + headers: {...adminHeaders, 'Content-Type': 'application/json'}, + body: JSON.stringify({name: 'Heater'}), + }).then((resp) => resp.json()); + }); + + it('does login', async () => await auth.login(page)); + + it('creates a message with action buttons', async () => { + await fetch(`${gotify.url}/message`, { + method: 'POST', + headers: {'X-Gotify-Key': app.token, 'Content-Type': 'application/json'}, + body: JSON.stringify({ + title: 'Heater', + message: 'The heater is still powered on.', + extras: { + 'client::action': { + buttons: [ + { + label: 'Power off', + http: { + method: 'post', + url: `${gotify.url}/message`, + headers: { + 'X-Gotify-Key': app.token, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + title: 'Powered off', + message: 'The heater is off.', + }), + }, + }, + {label: 'Invalid', http: {method: 'post', url: 'javascript:alert(1)'}}, + {label: 'Broken', http: {method: 'post', url: `${gotify.url}/message`}}, + ], + }, + }, + }), + }); + }); + + it('shows the valid action buttons of a message', async () => { + await waitForExists(page, '.message .title', 'Heater'); + const labels = await page.$$eval('.message .actions .action', (els) => + els.map((e) => e.textContent) + ); + expect(labels).toEqual(['Power off', 'Broken']); + }); + + it('shows the parsing error of invalid buttons', async () => { + await clickByText(page, '.message .action-error-toggle', 'Details'); + const details = await page.waitForSelector('.message .action-error-details'); + expect(await details?.evaluate((e) => e.textContent)).toContain( + '→ at ["client::action"].buttons[1].http.url' + ); + }); + + it('sends the request on click', async () => { + await clickByText(page, '.message .actions .action', 'Power off'); + await waitForExists(page, '#notistack-snackbar', "Action 'Power off' succeeded."); + await waitForExists(page, '.message .title', 'Powered off'); + }); + + it('reports failed requests', async () => { + await clickByText(page, '.message .actions .action', 'Broken'); + await waitForExists( + page, + '#notistack-snackbar', + "Action 'Broken' failed: 401 Unauthorized" + ); + }); + + it('does logout', () => auth.logout(page)); + + it('deletes the app', async () => { + const resp = await fetch(`${gotify.url}/application/${app.id}`, { + method: 'DELETE', + headers: adminHeaders, + }); + expect(resp.ok).toBe(true); + }); +}); diff --git a/ui/yarn.lock b/ui/yarn.lock index c1f89e237..0f53c10f5 100644 --- a/ui/yarn.lock +++ b/ui/yarn.lock @@ -3598,6 +3598,11 @@ zod@^4.6.5: resolved "https://registry.yarnpkg.com/zod/-/zod-4.6.7.tgz#e806cf64a7f4e37635ce9f2f52c04c3766f75e5b" integrity sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg== +zod@^4.6.7: + version "4.6.7" + resolved "https://registry.yarnpkg.com/zod/-/zod-4.6.7.tgz#e806cf64a7f4e37635ce9f2f52c04c3766f75e5b" + integrity sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg== + zwitch@^2.0.0: version "2.0.4" resolved "https://registry.yarnpkg.com/zwitch/-/zwitch-2.0.4.tgz#c827d4b0acb76fc3e685a4c6ec2902d51070e9d7"
{error}