Skip to content
Open
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 @@ -199,6 +200,7 @@ const Message = ({
}`}>
{renderContent()}
</Typography>
<MessageActions extras={extras} />
</div>
{isOverflowing && (
<Button
Expand Down
142 changes: 142 additions & 0 deletions ui/src/message/MessageActions.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
import OpenInNew from '@mui/icons-material/OpenInNew';
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, IHttpAction} from './extras';

const useStyles = makeStyles()((theme) => ({
actions: {
display: 'flex',
flexWrap: 'wrap',
gap: theme.spacing(1),
marginTop: theme.spacing(1.5),
},
error: {
marginTop: theme.spacing(1.5),
},
errorDetails: {
whiteSpace: 'pre-wrap',
margin: 0,
marginTop: theme.spacing(1),
},
}));

const executeAction = (http: IHttpAction): Promise<Response> =>
fetch(http.url, {
method: http.method,
headers: http.headers,
body: http.body,
credentials: 'omit',
referrerPolicy: 'no-referrer',
});

const describeUrl = (url: string) => {
const {host, pathname} = new URL(url);
return `${host}${pathname}`;
};

const HttpActionButton = ({label, http}: {label: string; http: IHttpAction}) => {
const {snackManager} = useStores();
const [running, setRunning] = React.useState(false);

const onClick = async () => {
setRunning(true);
try {
const response = await executeAction(http);
if (response.ok) {
snackManager.snack(`Action '${label}' succeeded.`);
} else {
snackManager.snack(
`Action '${label}' failed: ${response.status} ${response.statusText}`.trim()
);
}
} catch {
snackManager.snack(
`Action '${label}': no readable response (network error or CORS). The request may still have been processed.`
);
} finally {
setRunning(false);
}
};

return (
<Tooltip title={`${http.method} ${describeUrl(http.url)}`}>
<span>
<Button
className="action"
variant="outlined"
size="small"
disabled={running}
onClick={onClick}
startIcon={running ? <CircularProgress size={16} /> : undefined}>
{label}
</Button>
</span>
</Tooltip>
);
};

const OpenActionButton = ({label, url}: {label: string; url: string}) => (
<Tooltip title={`Open ${describeUrl(url)}`}>
<Button
className="action"
variant="outlined"
size="small"
href={url}
target="_blank"
rel="noopener noreferrer"
endIcon={<OpenInNew />}>
{label}
</Button>
</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(({label, http, open}, index) =>
http ? (
<HttpActionButton key={index} label={label} http={http} />
) : (
open && <OpenActionButton key={index} label={label} url={open.url} />
)
)}
</div>
)}
{error && <ActionError error={error} />}
</>
);
};
135 changes: 135 additions & 0 deletions ui/src/message/extras.test.ts
Original file line number Diff line number Diff line change
@@ -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]');
});
});
80 changes: 65 additions & 15 deletions ui/src/message/extras.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,79 @@
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 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<typeof actionButton>;
export type IHttpAction = z.infer<typeof httpAction>;

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