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..50ab74d4e 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;
@@ -199,6 +200,7 @@ const Message = ({
}`}>
{renderContent()}
+
{isOverflowing && (
+
+
+ );
+};
+
+const OpenActionButton = ({label, url}: {label: string; url: string}) => (
+
+ }>
+ {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(({label, http, open}, index) =>
+ http ? (
+
+ ) : (
+ open &&
+ )
+ )}
+
+ )}
+ {error && }
+ >
+ );
+};
diff --git a/ui/src/message/extras.test.ts b/ui/src/message/extras.test.ts
new file mode 100644
index 000000000..d2e10b71d
--- /dev/null
+++ b/ui/src/message/extras.test.ts
@@ -0,0 +1,135 @@
+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('parses buttons that open a url', () => {
+ const result = parse(
+ {label: 'Status page', open: {url: 'https://status.example.com/'}},
+ {label: 'Power off', http: {method: 'post', url: 'https://x.y/'}}
+ );
+ expect(result).toEqual({
+ buttons: [
+ {label: 'Status page', open: {url: 'https://status.example.com/'}},
+ {label: 'Power off', http: {method: 'POST', url: 'https://x.y/', headers: {}}},
+ ],
+ });
+ });
+
+ it('reports buttons with both or neither http and open', () => {
+ const result = parse(
+ {
+ label: 'both',
+ http: {method: 'GET', url: 'https://x.y/'},
+ open: {url: 'https://x.y/'},
+ },
+ {label: 'neither'}
+ );
+ expect(result.buttons).toEqual([]);
+ expect(result.error).toContain(
+ 'A button needs either http or open\n → at ["client::action"].buttons[0]'
+ );
+ expect(result.error).toContain(
+ 'A button needs either http or open\n → at ["client::action"].buttons[1]'
+ );
+ });
+
+ 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}})],
+ ['an open without url', {label: 'a', open: {}}],
+ ['an open javascript url', {label: 'a', open: {url: 'javascript:alert(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..c0db17680 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,74 @@ 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 openAction = z.object({
+ url: z.url({protocol: /^https?$/}),
+});
+
+// A button either sends a request (http) or opens a page (open).
+const actionButton = z
+ .object({
+ label: z.string().check(z.trim(), z.minLength(1)),
+ http: z.optional(httpAction),
+ open: z.optional(openAction),
+ })
+ .check(
+ z.refine(
+ ({http, open}) => (http === undefined) !== (open === undefined),
+ 'A button needs either http or open'
+ )
+ );
+
+export type IActionButton = z.infer;
+export type IHttpAction = 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..271ca515b
--- /dev/null
+++ b/ui/src/tests/message-actions.test.ts
@@ -0,0 +1,116 @@
+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`}},
+ {label: 'Version', open: {url: `${gotify.url}/version`}},
+ ],
+ },
+ },
+ }),
+ });
+ });
+
+ 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', 'Version']);
+ });
+
+ 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('opens the url of an open button in a new tab', async () => {
+ const url = `${gotify.url}/version`;
+ await clickByText(page, '.message .actions .action', 'Version');
+ const target = await gotify.browser.waitForTarget((t) => t.url() === url);
+ const tab = await target.page();
+ expect(await tab?.evaluate(() => window.opener)).toBeNull();
+ await tab?.close();
+ });
+
+ 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"