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
16 changes: 13 additions & 3 deletions frontend/src/App/Login/LoginByTokenForm/index.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import React from 'react';
import React, { useState } from 'react';
import { useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';

import { Button, FormInput, SpaceBetween } from 'components';
import { Button, FormInput, SpaceBetween, TokenVisibilityButton } from 'components';

import { useAppDispatch } from 'hooks';
import { useCheckAuthTokenMutation } from 'services/user';
Expand All @@ -14,7 +14,9 @@ type FormValues = Pick<IUserWithCreds['creds'], 'token'>;

export const LoginByTokenForm: React.FC = () => {
const { t } = useTranslation();
const { handleSubmit, control, setError } = useForm<FormValues>();
const { handleSubmit, control, setError, watch } = useForm<FormValues>();
const token = watch('token');
const [isTokenVisible, setIsTokenVisible] = useState(false);
const dispatch = useAppDispatch();
const navigate = useNavigate();

Expand Down Expand Up @@ -45,6 +47,14 @@ export const LoginByTokenForm: React.FC = () => {
constraintText="Use your personal access token"
control={control}
name="token"
type={isTokenVisible ? 'text' : 'password'}
secondaryControl={
<TokenVisibilityButton
disabled={isLoading || !token}
visible={isTokenVisible}
onChange={setIsTokenVisible}
/>
}
disabled={isLoading}
rules={{ required: t('validation.required') }}
autoComplete="off"
Expand Down
21 changes: 21 additions & 0 deletions frontend/src/components/TokenVisibilityButton/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import React from 'react';
import { useTranslation } from 'react-i18next';

import { Button, IProps as ButtonProps } from '../Button';

export interface Props {
visible: boolean;
onChange: (visible: boolean) => void;
variant?: ButtonProps['variant'];
disabled?: boolean;
}

export const TokenVisibilityButton: React.FC<Props> = ({ visible, onChange, variant = 'normal', disabled }) => {
const { t } = useTranslation();

return (
<Button formAction="none" variant={variant} disabled={disabled} wrapText={false} onClick={() => onChange(!visible)}>
{visible ? t('common.hide_token') : t('common.show_token')}
</Button>
);
};
1 change: 1 addition & 0 deletions frontend/src/components/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,4 +104,5 @@ export { Button } from './Button';
export type { IProps as ButtonProps } from './Button';
export { Code } from './Code';
export { Hotspot } from './Hotspot';
export { TokenVisibilityButton } from './TokenVisibilityButton';
export type { IProps as TabsProps } from './Tabs';
2 changes: 2 additions & 0 deletions frontend/src/libs/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ export const copyToClipboard = (copyText: string, success?: () => void, failed?:
navigator.clipboard.writeText(copyText).then(success, failed);
};

export const TOKEN_MASK = '********';

export const MINUTE = 60000;

export const getDateAgoSting = (time: number): string => {
Expand Down
4 changes: 3 additions & 1 deletion frontend/src/locale/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,9 @@
"quickstart": "Quickstart",
"ask_ai": "Ask AI",
"new": "New",
"full_view": "Full view"
"full_view": "Full view",
"show_token": "Show token",
"hide_token": "Hide token"
},

"auth": {
Expand Down
28 changes: 20 additions & 8 deletions frontend/src/pages/Models/Details/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,11 @@ import {
NavigateLink,
SpaceBetween,
Tabs,
TokenVisibilityButton,
} from 'components';

import { useAppSelector, useBreadcrumbs, useNotifications } from 'hooks';
import { copyToClipboard, riseRouterException } from 'libs';
import { copyToClipboard, riseRouterException, TOKEN_MASK } from 'libs';
import { getExtendedModelFromRun } from 'libs/run';
import { ROUTES } from 'routes';
import { useGetRunQuery } from 'services/run';
Expand Down Expand Up @@ -60,6 +61,7 @@ export const ModelDetails: React.FC = () => {
const [messages, setMessages] = useState<Message[]>([]);
const [viewCodeVisible, setViewCodeVisible] = useState<boolean>(false);
const [codeTab, setCodeTab] = useState<CodeTab>(CodeTab.Python);
const [isTokenVisible, setIsTokenVisible] = useState<boolean>(false);
const [loading, setLoading] = useState<boolean>(false);
const params = useParams();
const paramProjectName = params.projectName ?? '';
Expand Down Expand Up @@ -90,6 +92,11 @@ export const ModelDetails: React.FC = () => {
},
]);

const closeViewCode = () => {
setViewCodeVisible(false);
setIsTokenVisible(false);
};

const scrollChatToBottom = () => {
if (!chatList.current) return;

Expand Down Expand Up @@ -284,16 +291,18 @@ export const ModelDetails: React.FC = () => {
}
};

const pythonCode = getPythonModelCode({ model: modelData, token });
const displayedToken = isTokenVisible ? token : TOKEN_MASK;

const pythonCode = getPythonModelCode({ model: modelData, token: displayedToken });

const curlCode = getCurlModelCode({ model: modelData, token });
const curlCode = getCurlModelCode({ model: modelData, token: displayedToken });

const onCopyCode = () => {
switch (codeTab) {
case CodeTab.Python:
return copyToClipboard(pythonCode);
return copyToClipboard(getPythonModelCode({ model: modelData, token }));
case CodeTab.Curl:
return copyToClipboard(curlCode);
return copyToClipboard(getCurlModelCode({ model: modelData, token }));
}
};

Expand Down Expand Up @@ -425,19 +434,22 @@ export const ModelDetails: React.FC = () => {
size="large"
footer={
<Box float="right">
<Button variant="normal" onClick={() => setViewCodeVisible(false)}>
<Button variant="normal" onClick={closeViewCode}>
{t('common.close')}
</Button>
</Box>
}
onDismiss={() => setViewCodeVisible(false)}
onDismiss={closeViewCode}
>
<SpaceBetween size="m" direction="vertical">
<Box>{t('models.details.view_code_description')}</Box>

<div className={css.viewCodeControls}>
<div className={css.copyButton}>
<Button iconName="copy" onClick={onCopyCode}></Button>
<SpaceBetween direction="horizontal" size="xs">
<TokenVisibilityButton visible={isTokenVisible} onChange={setIsTokenVisible} />
<Button iconName="copy" onClick={onCopyCode}></Button>
</SpaceBetween>
</div>

<Tabs
Expand Down
39 changes: 24 additions & 15 deletions frontend/src/pages/Project/Details/Settings/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
SelectCSD,
SpaceBetween,
StatusIndicator,
TokenVisibilityButton,
} from 'components';
import { HotspotIds } from 'layouts/AppLayout/TutorialPanel/constants';

Expand Down Expand Up @@ -72,7 +73,9 @@ export const ProjectSettings: React.FC = () => {
const location = useLocation();
const paramProjectName = params.projectName ?? '';
const [isExpandedCliSection, setIsExpandedCliSection] = React.useState(false);
const [configCliCommand, copyCliCommand] = useConfigProjectCliCommand({ projectName: paramProjectName });
const [configCliCommand, copyCliCommand, isTokenVisible, setIsTokenVisible] = useConfigProjectCliCommand({
projectName: paramProjectName,
});

const { isAvailableDeletingPermission, isProjectManager, isProjectAdmin, isAvailableProjectManaging } =
useCheckAvailableProjectPermission();
Expand Down Expand Up @@ -366,20 +369,26 @@ export const ProjectSettings: React.FC = () => {
<Code className={styles.code}>{configCliCommand}</Code>

<div className={styles.copy}>
<Popover
dismissButton={false}
position="top"
size="small"
triggerType="custom"
content={<StatusIndicator type="success">{t('common.copied')}</StatusIndicator>}
>
<Button
formAction="none"
iconName="copy"
variant="normal"
onClick={copyCliCommand}
/>
</Popover>
<SpaceBetween direction="horizontal" size="xs">
<TokenVisibilityButton visible={isTokenVisible} onChange={setIsTokenVisible} />

<Popover
dismissButton={false}
position="top"
size="small"
triggerType="custom"
content={
<StatusIndicator type="success">{t('common.copied')}</StatusIndicator>
}
>
<Button
formAction="none"
iconName="copy"
variant="normal"
onClick={copyCliCommand}
/>
</Popover>
</SpaceBetween>
</div>
</Hotspot>
</div>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/** @jest-environment node */
import React from 'react';
import { act, create, ReactTestRenderer } from 'react-test-renderer';

import { copyToClipboard, TOKEN_MASK } from 'libs';

import { useConfigProjectCliCommand } from './useConfigProjectCliComand';

jest.mock('libs', () => ({ ...jest.requireActual('libs'), copyToClipboard: jest.fn() }));
jest.mock('App/slice', () => ({ selectAuthToken: jest.fn() }));
jest.mock('hooks', () => ({ useAppSelector: () => 'secret-token' }));

let result: ReturnType<typeof useConfigProjectCliCommand>;
let renderer: ReactTestRenderer;

const Harness = () => {
result = useConfigProjectCliCommand({ projectName: 'main' });
return null;
};

beforeAll(() => {
Object.defineProperty(globalThis, 'location', { value: { origin: 'https://dstack.example' }, configurable: true });
});

beforeEach(() => {
jest.mocked(copyToClipboard).mockReset();
act(() => {
renderer = create(<Harness />);
});
});

afterEach(() => act(() => renderer.unmount()));

describe('useConfigProjectCliCommand', () => {
test('hides the token by default', () => {
const [cliCommand] = result;

expect(cliCommand).toContain(`--token ${TOKEN_MASK}`);
expect(cliCommand).not.toContain('secret-token');
});

test('shows the token when requested', () => {
act(() => result[3](true));

const [cliCommand, , isTokenVisible] = result;
expect(isTokenVisible).toBe(true);
expect(cliCommand).toContain('--token secret-token');
});

test('copies the command with the real token while it is hidden', () => {
const [, copyCliCommand] = result;

copyCliCommand();

expect(copyToClipboard).toHaveBeenCalledWith(expect.stringContaining('--token secret-token'));
});
});
14 changes: 10 additions & 4 deletions frontend/src/pages/Project/hooks/useConfigProjectCliComand.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { useState } from 'react';

import { useAppSelector } from 'hooks';
import { copyToClipboard } from 'libs';
import { copyToClipboard, TOKEN_MASK } from 'libs';

import { selectAuthToken } from 'App/slice';

Expand All @@ -8,12 +10,16 @@ type Args = {
};
export const useConfigProjectCliCommand = ({ projectName }: Args) => {
const currentUserToken = useAppSelector(selectAuthToken);
const [isTokenVisible, setIsTokenVisible] = useState(false);

const getCliCommand = (token?: string) =>
`dstack project add \\\n --url ${location.origin} \\\n --name ${projectName} \\\n --token ${token}`;

const cliCommand = `dstack project add \\\n --url ${location.origin} \\\n --name ${projectName} \\\n --token ${currentUserToken}`;
const cliCommand = getCliCommand(isTokenVisible ? currentUserToken : TOKEN_MASK);

const copyCliCommand = () => {
copyToClipboard(cliCommand);
copyToClipboard(getCliCommand(currentUserToken));
};

return [cliCommand, copyCliCommand] as const;
return [cliCommand, copyCliCommand, isTokenVisible, setIsTokenVisible] as const;
};
Original file line number Diff line number Diff line change
@@ -1,7 +1,19 @@
import React, { FC } from 'react';
import { useTranslation } from 'react-i18next';

import { Alert, Box, Button, Code, ExpandableSection, Popover, SpaceBetween, StatusIndicator, Tabs, Wizard } from 'components';
import {
Alert,
Box,
Button,
Code,
ExpandableSection,
Popover,
SpaceBetween,
StatusIndicator,
Tabs,
TokenVisibilityButton,
Wizard,
} from 'components';

import { copyToClipboard } from 'libs';

Expand Down Expand Up @@ -50,7 +62,9 @@ export const ConnectToRunWithDevEnvConfiguration: FC<{ run: IRun }> = ({ run })
const openInIDEUrl = run.jobs[0]?.job_connection_info?.attached_ide_url ?? undefined;
const ideDisplayName = hasIDE ? getIDEDisplayName(configuration.ide!) : undefined;

const [configCliCommand, copyCliCommand] = useConfigProjectCliCommand({ projectName: run.project_name });
const [configCliCommand, copyCliCommand, isTokenVisible, setIsTokenVisible] = useConfigProjectCliCommand({
projectName: run.project_name,
});

return (
<ExpandableSection
Expand Down Expand Up @@ -187,24 +201,31 @@ export const ConnectToRunWithDevEnvConfiguration: FC<{ run: IRun }> = ({ run })
<Code className={styles.code}>{configCliCommand}</Code>

<div className={styles.copy}>
<Popover
dismissButton={false}
position="top"
size="small"
triggerType="custom"
content={
<StatusIndicator type="success">
{t('common.copied')}
</StatusIndicator>
}
>
<Button
formAction="none"
iconName="copy"
variant="normal"
onClick={copyCliCommand}
<SpaceBetween direction="horizontal" size="xs">
<TokenVisibilityButton
visible={isTokenVisible}
onChange={setIsTokenVisible}
/>
</Popover>

<Popover
dismissButton={false}
position="top"
size="small"
triggerType="custom"
content={
<StatusIndicator type="success">
{t('common.copied')}
</StatusIndicator>
}
>
<Button
formAction="none"
iconName="copy"
variant="normal"
onClick={copyCliCommand}
/>
</Popover>
</SpaceBetween>
</div>
</div>
</SpaceBetween>
Expand Down
Loading
Loading