Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion ui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
2 changes: 2 additions & 0 deletions ui/src/message/Message.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -212,6 +213,7 @@ const Message = ({
{expanded ? 'Read Less' : 'Read More'}
</Button>
)}
<MessageActions extras={extras} />
</Container>
</div>
);
Expand Down
124 changes: 124 additions & 0 deletions ui/src/message/MessageActions.tsx
Original file line number Diff line number Diff line change
@@ -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<Response> =>
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 (
<Tooltip title={describeTarget(button)}>
<span>
<Button
className="action"
variant="outlined"
size="small"
disabled={running}
onClick={onClick}
startIcon={running ? <CircularProgress size={16} /> : undefined}>
{button.label}
</Button>
</span>
</Tooltip>
);
};

const ActionError = ({error}: {error: string}) => {
const {classes} = useStyles();
const [showDetails, setShowDetails] = React.useState(false);
return (
<Alert
className={`${classes.error} action-error`}
severity="warning"
action={
<Button
className="action-error-toggle"
color="inherit"
size="small"
onClick={() => setShowDetails((show) => !show)}>
{showDetails ? 'Hide details' : 'Details'}
</Button>
}>
This message contains invalid action buttons.
{showDetails && (
<pre className={`${classes.errorDetails} action-error-details`}>{error}</pre>
)}
</Alert>
);
};

export const MessageActions = ({extras}: {extras?: IMessageExtras}) => {
const {classes} = useStyles();
const {buttons, error} = React.useMemo(() => actionButtons(extras), [extras]);
return (
<>
{buttons.length > 0 && (
<div className={`${classes.actions} actions`}>
{buttons.map((button, index) => (
<ActionButton key={index} button={button} />
))}
</div>
)}
{error && <ActionError error={error} />}
</>
);
};
102 changes: 102 additions & 0 deletions ui/src/message/extras.test.ts
Original file line number Diff line number Diff line change
@@ -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]');
});
});
66 changes: 51 additions & 15 deletions ui/src/message/extras.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,65 @@
import {z} from 'zod/mini';
import {IMessageExtras} from '../types';

export enum RenderMode {
Markdown = 'text/markdown',
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<typeof actionButton>;

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),
};
};
Loading