File size: 9,475 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
import { Badge } from '@automattic/ui';
import { useQuery, useMutation } from '@tanstack/react-query';
import {
	__experimentalHStack as HStack,
	__experimentalVStack as VStack,
	__experimentalText as Text,
	BaseControl,
	Button,
	Card,
	CardBody,
	ExternalLink,
	SelectControl,
	ToggleControl,
} from '@wordpress/components';
import { useDispatch } from '@wordpress/data';
import { DataForm } from '@wordpress/dataviews';
import { createInterpolateElement } from '@wordpress/element';
import { sprintf, __ } from '@wordpress/i18n';
import { trash } from '@wordpress/icons';
import { store as noticesStore } from '@wordpress/notices';
import { useMemo, useState } from 'react';
import { useAuth } from '../../app/auth';
import {
	siteSshAccessEnableMutation,
	siteSshAccessDisableMutation,
	siteSshKeysQuery,
	siteSshKeysAttachMutation,
	siteSshKeysDetachMutation,
} from '../../app/queries/site-ssh';
import { sshKeysQuery } from '../../app/queries/ssh';
import ClipboardInputControl from '../../components/clipboard-input-control';
import InlineSupportLink from '../../components/inline-support-link';
import { SectionHeader } from '../../components/section-header';
import type { SftpUser, SiteSshKey, UserSshKey } from '../../data/types';
import type { DataFormControlProps, Field } from '@wordpress/dataviews';

type SshCardFormData = {
	connection_command: string;
	ssh_key: string;
};

const SshKeyCard = ( {
	siteSshKey,
	userLocale,
	isBusy,
	onDetach,
}: {
	siteSshKey: SiteSshKey;
	userLocale: string;
	isBusy: boolean;
	onDetach: ( siteSshKey: SiteSshKey ) => void;
} ) => {
	return (
		<Card size="small">
			<CardBody>
				<HStack spacing={ 4 } justify="space-between" alignment="flex-start">
					<VStack spacing={ 3 } alignment="flex-start">
						<VStack spacing={ 1 }>
							<Text>{ `${ siteSshKey.user_login }-${ siteSshKey.name }` }</Text>
							<Text variant="muted">{ siteSshKey.sha256 }</Text>
						</VStack>
						<Badge intent="info" style={ { height: '24px' } }>
							{ sprintf(
								/* translators: %s is when the SSH key was attached. */
								__( 'Attached on %s' ),
								new Intl.DateTimeFormat( userLocale, {
									dateStyle: 'long',
									timeStyle: 'medium',
								} ).format( new Date( siteSshKey.attached_at ) )
							) }
						</Badge>
					</VStack>
					<Button
						icon={ trash }
						label={ __( 'Detach' ) }
						isBusy={ isBusy }
						style={ { margin: '-6px' } }
						onClick={ () => onDetach( siteSshKey ) }
					/>
				</HStack>
			</CardBody>
		</Card>
	);
};

export default function SshCard( {
	siteId,
	sftpUsers,
	sshEnabled,
}: {
	siteId: number;
	sftpUsers: SftpUser[];
	sshEnabled: boolean;
} ) {
	const { user } = useAuth();
	const { data: siteSshKeys } = useQuery( siteSshKeysQuery( siteId ) );
	const { data: userSshKeys, error: userSshKeysError } = useQuery< UserSshKey[], { code: string } >(
		{
			...sshKeysQuery(),
			enabled: sshEnabled,
		}
	);
	const toggleSshAccessMutation = useMutation(
		! sshEnabled ? siteSshAccessEnableMutation( siteId ) : siteSshAccessDisableMutation( siteId )
	);
	const attachSshKeyMutation = useMutation( siteSshKeysAttachMutation( siteId ) );
	const detachSshKeyMutation = useMutation( siteSshKeysDetachMutation( siteId ) );
	const { createSuccessNotice, createErrorNotice } = useDispatch( noticesStore );
	const userLocale = user.locale_variant || user.language || 'en';
	const hasUserSshKeys = userSshKeys && userSshKeys.length > 0;
	const [ formData, setFormData ] = useState< SshCardFormData >( {
		connection_command: `ssh ${ sftpUsers[ 0 ]?.username }@ssh.wp.com`,
		ssh_key: 'default',
	} );

	const userKeyIsAttached = useMemo( () => {
		if ( ! siteSshKeys ) {
			return false;
		}
		return !! siteSshKeys.find( ( { user_login }: SiteSshKey ) => user_login === user.username );
	}, [ siteSshKeys, user.username ] );

	const handleCopy = ( label?: React.ReactNode ) => {
		if ( ! label ) {
			return;
		}

		createSuccessNotice(
			sprintf(
				/* translators: %s is the copied field */
				__( 'Copied %s to clipboard.' ),
				label
			),
			{
				type: 'snackbar',
			}
		);
	};

	const handleToggleSshAccess = () => {
		toggleSshAccessMutation.mutate( undefined, {
			onSuccess: () => {
				createSuccessNotice(
					sshEnabled
						? __( 'SSH access has been successfully disabled for this site.' )
						: __( 'SSH access has been successfully enabled for this site.' ),
					{
						type: 'snackbar',
					}
				);
			},
			onError: () => {
				createErrorNotice(
					sshEnabled
						? __(
								'Sorry, we had a problem disabling SSH access for this site. Please refresh the page and try again.'
						  )
						: __(
								'Sorry, we had a problem enabling SSH access for this site. Please refresh the page and try again.'
						  ),
					{
						type: 'snackbar',
					}
				);
			},
		} );
	};

	const handleAttachSshKey = () => {
		attachSshKeyMutation.mutate( formData.ssh_key, {
			onError: () => {
				createErrorNotice(
					__(
						'Sorry, we had a problem attaching SSH key to this site. Please refresh the page and try again.'
					),
					{
						type: 'snackbar',
					}
				);
			},
		} );
	};

	const handleDetachSshKey = ( siteSshKey: SiteSshKey ) => {
		detachSshKeyMutation.mutate( siteSshKey, {
			onError: () => {
				createErrorNotice(
					__(
						'Sorry, we had a problem detaching SSH key from this site. Please refresh the page and try again.'
					),
					{
						type: 'snackbar',
					}
				);
			},
		} );
	};

	const SshKeysControl = < Item, >( { field }: DataFormControlProps< Item > ) => (
		<BaseControl label={ field.label } __nextHasNoMarginBottom>
			<VStack>
				{ siteSshKeys?.map( ( siteSshKey: SiteSshKey ) => (
					<SshKeyCard
						key={ siteSshKey.sha256 }
						siteSshKey={ siteSshKey }
						userLocale={ userLocale }
						isBusy={ detachSshKeyMutation.isPending }
						onDetach={ handleDetachSshKey }
					/>
				) ) }
			</VStack>
		</BaseControl>
	);

	const fields: Field< SshCardFormData >[] = [
		{
			id: 'connection_command',
			label: __( 'connection command' ),
			Edit: ( { field, data } ) => {
				return (
					<ClipboardInputControl
						label={ field.label }
						value={ field.getValue( { item: data } ) }
						readOnly
						__next40pxDefaultSize
						onCopy={ handleCopy }
					/>
				);
			},
		},
		{
			id: 'ssh_key',
			label: __( 'SSH key' ),
			Edit: ( { data, field, onChange, hideLabelFromVision } ) => {
				if ( siteSshKeys && siteSshKeys.length > 0 ) {
					return (
						<SshKeysControl
							data={ data }
							field={ field }
							onChange={ onChange }
							hideLabelFromVision={ hideLabelFromVision }
						/>
					);
				}

				return (
					<SelectControl
						label={ field.label }
						value={ field.getValue( { item: data } ) ?? '' }
						help={ field.description }
						options={ field.elements }
						disabled={ ! hasUserSshKeys }
						onChange={ ( newValue: any ) =>
							onChange( {
								[ field.id ]: newValue,
							} )
						}
						__next40pxDefaultSize
						__nextHasNoMarginBottom
						hideLabelFromVision={ hideLabelFromVision }
					/>
				);
			},
			elements: hasUserSshKeys
				? userSshKeys.map( ( userSshKey: UserSshKey ) => ( {
						label: `${ user.username }-${ userSshKey.name }`,
						value: userSshKey.name,
				  } ) )
				: [
						{
							label: __( 'No SSH keys available' ),
							value: '',
						},
				  ],
		},
	];

	const form = {
		type: 'regular' as const,
		fields: [ 'connection_command', 'ssh_key' ],
	};

	if ( userSshKeysError?.code === 'reauthorization_required' ) {
		const currentPath = window.location.pathname;
		const loginUrl = `/me/reauth-required?redirect_to=${ encodeURIComponent( currentPath ) }`;
		window.location.href = loginUrl;
		return null;
	}

	return (
		<Card>
			<CardBody>
				<VStack spacing={ 4 }>
					<SectionHeader
						title={ __( 'SSH' ) }
						description={ createInterpolateElement(
							__(
								'SSH lets you access your sites backend via a terminal, so you can manage files and use <wpCliLink>WP-CLI</wpCliLink> for quick changes and troubleshooting. <learnMoreLink>Learn more</learnMoreLink>.'
							),
							{
								wpCliLink: <ExternalLink href="https://wp-cli.org/" children={ null } />,
								learnMoreLink: <InlineSupportLink supportContext="hosting-connect-to-ssh" />,
							}
						) }
						level={ 3 }
					/>
					<ToggleControl
						label={ __( 'Enable SSH access for this site' ) }
						checked={ sshEnabled }
						disabled={ toggleSshAccessMutation.isPending }
						onChange={ handleToggleSshAccess }
						__nextHasNoMarginBottom
					/>
					{ sshEnabled && (
						<DataForm< SshCardFormData >
							data={ formData }
							fields={ fields }
							form={ form }
							onChange={ ( edits: Partial< SshCardFormData > ) => {
								setFormData( ( data ) => ( { ...data, ...edits } ) );
							} }
						/>
					) }
					{ sshEnabled && ! userKeyIsAttached && (
						<HStack justify="flex-start">
							<Button
								variant="primary"
								isBusy={ attachSshKeyMutation.isPending }
								disabled={ ! hasUserSshKeys }
								onClick={ handleAttachSshKey }
							>
								{ __( 'Attach SSH key to site' ) }
							</Button>
							<Button
								variant="secondary"
								target="_blank"
								href="/me/security/ssh-key"
								rel="noreferrer"
							>
								{ __( 'Add new SSH key ↗' ) }
							</Button>
						</HStack>
					) }
				</VStack>
			</CardBody>
		</Card>
	);
}