From a40ae60abb3b3f69dcee057e8c62b3ab7f8fa377 Mon Sep 17 00:00:00 2001 From: Maurice Date: Sat, 14 Nov 2026 11:19:06 +0100 Subject: [PATCH] feat(mobile): API keys in the phone's settings - MApiKeysSection: the keys with what each may read, creating one in a sheet (name, the areas as chips, the key shown once with a copy button), deleting behind a confirm sheet, and the endpoint to copy. - The list and every action move from ApiKeysSection into useApiKeys, shared by both views; the calls go through a small online-only apiKeysRepo, so no view reaches the API (offline baseline loses ApiKeysSection and AdminSettingsTab). - The phone's Integrations tab is always there now, as on the desktop: the keys in it need no addon. - A test title no longer breaks on its apostrophe. --- client/scripts/feature-pairs.json | 6 + client/scripts/offline-baseline.json | 2 - .../components/Settings/ApiKeysSection.tsx | 212 ++------------- client/src/components/Settings/useApiKeys.ts | 203 +++++++++++++++ .../Settings/useIntegrationGates.ts | 4 +- .../screens/settings/MApiKeysSection.tsx | 244 ++++++++++++++++++ .../src/mobile/screens/settings/MSettings.tsx | 9 +- .../settings/MSettingsIntegrations.tsx | 11 + client/src/repo/apiKeysRepo.ts | 12 + .../unit/mobile/admin/MAdminSheets.test.tsx | 2 +- .../mobile/settings/MApiKeysSection.test.tsx | 122 +++++++++ 11 files changed, 633 insertions(+), 194 deletions(-) create mode 100644 client/src/components/Settings/useApiKeys.ts create mode 100644 client/src/mobile/screens/settings/MApiKeysSection.tsx create mode 100644 client/src/repo/apiKeysRepo.ts create mode 100644 client/tests/unit/mobile/settings/MApiKeysSection.test.tsx diff --git a/client/scripts/feature-pairs.json b/client/scripts/feature-pairs.json index ce7770fc5..a28ce59ab 100644 --- a/client/scripts/feature-pairs.json +++ b/client/scripts/feature-pairs.json @@ -57,6 +57,12 @@ "desktop": ["src/pages/admin/AdminSettingsTab.tsx"], "mobile": ["src/mobile/screens/admin/MAdminSettingsSection.tsx"] }, + { + "feature": "API keys", + "hooks": ["src/components/Settings/useApiKeys.ts"], + "desktop": ["src/components/Settings/ApiKeysSection.tsx"], + "mobile": ["src/mobile/screens/settings/MApiKeysSection.tsx"] + }, { "feature": "Wanderer connection", "hooks": ["src/components/Settings/useWandererConnection.ts"], diff --git a/client/scripts/offline-baseline.json b/client/scripts/offline-baseline.json index 87a35b30d..ad9ce83dc 100644 --- a/client/scripts/offline-baseline.json +++ b/client/scripts/offline-baseline.json @@ -97,7 +97,6 @@ "src/components/Roadtrip/useDayBoundaries.ts", "src/components/Roadtrip/useRefuelSearch.ts", "src/components/Roadtrip/useRoadtripVias.ts", - "src/components/Settings/ApiKeysSection.tsx", "src/components/Settings/useAccountSettings.ts", "src/components/Settings/useAirTrailSettings.ts", "src/components/Settings/useMcpIntegration.ts", @@ -129,7 +128,6 @@ "src/mobile/screens/trip/tabs/MCollabNotes.tsx", "src/pages/JourneyDetailPage.tsx", "src/pages/OAuthAuthorizePage.tsx", - "src/pages/admin/AdminSettingsTab.tsx", "src/pages/admin/useAdmin.ts", "src/pages/admin/useNotificationDefaults.ts", "src/pages/atlas/useAtlas.ts", diff --git a/client/src/components/Settings/ApiKeysSection.tsx b/client/src/components/Settings/ApiKeysSection.tsx index 6c9984640..d6b0004df 100644 --- a/client/src/components/Settings/ApiKeysSection.tsx +++ b/client/src/components/Settings/ApiKeysSection.tsx @@ -1,9 +1,6 @@ -import React, { useEffect, useId, useRef, useState } from 'react' -import { - KeyRound, Plus, Trash2, Copy, Check, AlertTriangle, Briefcase, CalendarDays, MapPin, - StickyNote, Ticket, Hotel, Users, Star, BarChart3, type LucideIcon, -} from 'lucide-react' -import { PUBLIC_API_SCOPES, type PublicApiScope } from '@trek/shared' +import React, { useId } from 'react' +import { KeyRound, Plus, Trash2, Copy, Check, AlertTriangle, type LucideIcon } from 'lucide-react' +import { PUBLIC_API_SCOPES } from '@trek/shared' import Section from './Section' import ConfirmDialog from '../shared/ConfirmDialog' import { Tooltip } from '../shared/Tooltip' @@ -12,56 +9,7 @@ import { EditorField, GRID_2, INPUT, LABEL } from '../shared/dialogParts' import { SETTINGS_BUTTON_PRIMARY, SETTINGS_ICON_BUTTON, SettingsHint, StatusPill } from './settingsKit' import { useTranslation } from '../../i18n' import { useDateFormat } from '../../hooks/useDateFormat' -import { formatDisplayDate } from '../../utils/dateFormat' -import { useToast } from '../shared/Toast' -import { authApi } from '../../api/client' - -/** - * Keys for the public API — the credential a user hands to other software that - * should read their trips. - * - * Its own section rather than a third tab under MCP: an API key is not an MCP - * credential, it does not need the MCP addon, and burying it under a heading - * about AI assistants is how people end up minting the wrong kind. The two look - * alike deliberately (name, prefix, shown once) because they are the same - * gesture; what differs is which door they open. - * - * State lives here rather than in the tab's shared hook so the section works on - * an instance with MCP switched off. - */ -interface ApiKey { - id: number - name: string - token_prefix: string - created_at: string - last_used_at: string | null - /** 'all' for every key minted before scopes existed, and for any key created without narrowing. */ - scope_mode?: 'all' | 'limited' - scopes?: PublicApiScope[] -} - -/** The server refuses an eleventh key (`TokenService.createToken`). */ -const MAX_KEYS = 10 - -/** The glyph each area already wears elsewhere in the app, so the list reads like the planner. */ -const SCOPE_ICONS: Record = { - trips: Briefcase, - days: CalendarDays, - places: MapPin, - notes: StickyNote, - reservations: Ticket, - accommodations: Hotel, - travellers: Users, - 'bucket-list': Star, - stats: BarChart3, -} - -/** SQLite hands out "YYYY-MM-DD HH:MM:SS" in UTC, which Safari will not parse as it stands. */ -function formatStamp(ts: string, locale: string, dateFormat: string): string { - const iso = ts.includes('T') ? ts : ts.replace(' ', 'T') - const d = new Date(/(Z|[+-]\d{2}:?\d{2})$/.test(iso) ? iso : `${iso}Z`) - return Number.isNaN(d.getTime()) ? ts : formatDisplayDate(d, locale, {}, dateFormat) -} +import { API_SCOPE_ICONS, MAX_API_KEYS, formatApiKeyStamp, useApiKeys, type ApiKey } from './useApiKeys' /** * The usage hint with its header names and path set as code. @@ -81,131 +29,27 @@ function withCode(text: string): React.ReactNode[] { }) } +/** + * Keys for the public API — the credential a user hands to other software that + * should read their trips. + * + * Its own section rather than a third tab under MCP: an API key is not an MCP + * credential, it does not need the MCP addon, and burying it under a heading + * about AI assistants is how people end up minting the wrong kind. The two look + * alike deliberately (name, prefix, shown once) because they are the same + * gesture; what differs is which door they open. + * + * The list and every action live in useApiKeys, shared with the phone's + * MApiKeysSection; this file is the desktop markup. + */ export default function ApiKeysSection(): React.ReactElement { const { t, locale } = useTranslation() - const toast = useToast() const dialogLabelId = useId() - const [keys, setKeys] = useState([]) - /** A failed load must not read as "you have no keys": that sends people off minting duplicates. */ - const [loadState, setLoadState] = useState<'loading' | 'ready' | 'failed'>('loading') - const [modalOpen, setModalOpen] = useState(false) - const [newName, setNewName] = useState('') - const [creating, setCreating] = useState(false) - /** The raw key, held only until the modal closes — the server keeps a hash. */ - const [created, setCreated] = useState(null) - const [deleteId, setDeleteId] = useState(null) - const [copied, setCopied] = useState<'key' | 'endpoint' | null>(null) - const copiedTimer = useRef | undefined>(undefined) - /** - * What the new key may read. Starts as everything, because that is what a key - * did before this existed and what most integrations want — narrowing is a - * deliberate act, and the dialog should not make the common case work harder. - */ - const [newScopes, setNewScopes] = useState>(new Set(PUBLIC_API_SCOPES)) - - const endpoint = `${window.location.origin}/api/v1` - const atLimit = keys.length >= MAX_KEYS - const allSelected = newScopes.size === PUBLIC_API_SCOPES.length - const canCreate = !!newName.trim() && !creating && newScopes.size > 0 - - useEffect(() => { - let cancelled = false - authApi.apiKeys.list() - .then(d => { - if (cancelled) return - setKeys(d.tokens || []) - setLoadState('ready') - }) - .catch(() => { if (!cancelled) setLoadState('failed') }) - return () => { - cancelled = true - clearTimeout(copiedTimer.current) - } - }, []) - - const handleCreate = async () => { - // Enter in the name field arrives here past the button's disabled state, and - // an empty selection must not fall through to the "no narrowing" branch - // below, which would mint a key that reads everything. - if (!canCreate) return - setCreating(true) - try { - // All of them selected means "no narrowing", which is what the server - // stores as `all` — sending the full list would record it as a limited key - // that happens to allow everything, and a section added in a later version - // would then be refused for a key nobody meant to restrict. - const narrowed = allSelected ? undefined : [...newScopes] - const d = await authApi.apiKeys.create(newName.trim(), narrowed) - setCreated(d.token.raw_token) - setKeys(prev => [ - { - id: d.token.id, - name: d.token.name, - token_prefix: d.token.token_prefix, - created_at: d.token.created_at, - last_used_at: null, - scope_mode: d.token.scope_mode, - scopes: d.token.scopes, - }, - ...prev, - ]) - setNewName('') - } catch { - toast.error(t('settings.apiKeys.createFailed')) - } finally { - setCreating(false) - } - } - - const handleDelete = async (id: number) => { - try { - await authApi.apiKeys.delete(id) - setKeys(prev => prev.filter(k => k.id !== id)) - toast.success(t('settings.apiKeys.deleted')) - } catch { - toast.error(t('settings.apiKeys.deleteFailed')) - } - } - - const handleCopy = async (text: string, what: 'key' | 'endpoint') => { - try { - // Absent on a plain-http origin, which is exactly where a self-run - // instance on the LAN tends to live. - if (!navigator.clipboard) throw new Error('clipboard unavailable') - await navigator.clipboard.writeText(text) - setCopied(what) - clearTimeout(copiedTimer.current) - copiedTimer.current = setTimeout(() => setCopied(null), 2000) - } catch { - toast.error(t('settings.apiKeys.copyFailed')) - } - } - - const resetForm = () => { - setCreated(null) - setCopied(null) - setNewName('') - setNewScopes(new Set(PUBLIC_API_SCOPES)) - } - - const openModal = () => { - resetForm() - setModalOpen(true) - } - - const closeModal = () => { - setModalOpen(false) - resetForm() - } - - const toggleScope = (scope: PublicApiScope) => { - setNewScopes(prev => { - const next = new Set(prev) - if (next.has(scope)) next.delete(scope) - else next.add(scope) - return next - }) - } + const { + keys, loadState, modalOpen, newName, setNewName, creating, created, deleteId, setDeleteId, copied, + newScopes, setNewScopes, endpoint, atLimit, allSelected, canCreate, + handleCreate, handleDelete, handleCopy, openModal, closeModal, toggleScope, + } = useApiKeys() const header = ( 0 ? {keys.length}/{MAX_KEYS} : undefined} + badge={keys.length > 0 ? {keys.length}/{MAX_API_KEYS} : undefined} action={( + + ); +} + +/** + * Phone twin of components/Settings/ApiKeysSection: keys for the public API. + * The list, minting (the key is shown once, then only its prefix), deleting and + * copying all live in useApiKeys; this is the phone's markup and its sheets. + */ +export default function MApiKeysSection() { + const { t, locale } = useTranslation(); + const K = useApiKeys(); + + return ( + <> + 0 ? ( + + {K.keys.length}/{MAX_API_KEYS} + + ) : undefined + } + > + {t('settings.apiKeys.description')} + + {K.atLimit && ( +

+ {t('settings.apiKeys.limitReached', { count: MAX_API_KEYS })} +

+ )} + {K.loadState === 'failed' && ( +

+ {t('settings.apiKeys.loadFailed')} +

+ )} + {K.loadState === 'ready' && K.keys.length === 0 && ( +

{t('settings.apiKeys.empty')}

+ )} + {K.keys.length > 0 && ( +
    + {K.keys.map((key) => ( + K.setDeleteId(key.id)} /> + ))} +
+ )} + +
+ + {t('settings.apiKeys.create')} + +
+ +
+ {t('settings.apiKeys.endpoint')} +
+ + {K.endpoint} + + +
+ {t('settings.apiKeys.docsHint')} +
+
+ + {/* Once the key is on screen, Done is the only way out: a stray swipe would + throw away the one copy there will ever be. */} + {} : K.closeModal} + ariaLabel={K.created ? t('settings.apiKeys.modal.createdTitle') : t('settings.apiKeys.modal.createTitle')} + > + } + onClose={K.closeModal} + footer={ + K.created ? ( + {t('settings.apiKeys.modal.done')} + ) : ( + <> + + {t('common.cancel')} + + void K.handleCreate()}> + {K.creating ? t('settings.apiKeys.modal.creating') : t('settings.apiKeys.modal.create')} + + + ) + } + > + {K.created ? ( +
+

+ + {t('settings.apiKeys.modal.createdWarning')} +

+ + {K.created} + + void K.handleCopy(K.created ?? '', 'key')}> + {K.copied === 'key' ? : } + {K.copied === 'key' ? t('common.copied') : t('settings.apiKeys.copy')} + +
+ ) : ( +
+
+ {t('settings.apiKeys.modal.name')} + K.setNewName(e.target.value)} + onKeyDown={(e) => { + if (e.key === 'Enter') void K.handleCreate(); + }} + /> + {t('settings.apiKeys.modal.nameHint')} +
+
+
+ {t('settings.apiScopes.title')} + +
+ {t('settings.apiScopes.hint')} +
+ {PUBLIC_API_SCOPES.map((scope) => { + const Icon = API_SCOPE_ICONS[scope]; + const on = K.newScopes.has(scope); + return ( + + ); + })} +
+ {K.newScopes.size === 0 && ( +

+ {t('settings.apiScopes.noneSelected')} +

+ )} +
+
+ )} +
+
+ + K.setDeleteId(null)} + title={t('settings.apiKeys.deleteTitle')} + message={t('settings.apiKeys.deleteMessage')} + confirmLabel={t('settings.apiKeys.deleteTitle')} + cancelLabel={t('common.cancel')} + danger + onConfirm={() => { + const id = K.deleteId; + K.setDeleteId(null); + if (id !== null) void K.handleDelete(id); + }} + /> + + ); +} diff --git a/client/src/mobile/screens/settings/MSettings.tsx b/client/src/mobile/screens/settings/MSettings.tsx index b99b1374c..41ea9588a 100644 --- a/client/src/mobile/screens/settings/MSettings.tsx +++ b/client/src/mobile/screens/settings/MSettings.tsx @@ -42,7 +42,7 @@ import MSectionNav, { MSectionList, SECTION_SCREEN, type MSection } from '../../ export default function MSettings() { const { t } = useTranslation() const navigate = useNavigate() - const { hasIntegrations, hasPlugins, appVersion, activeTab, setActiveTab, managed } = useSettings() + const { hasPlugins, appVersion, activeTab, setActiveTab, managed } = useSettings() const [dropOpen, setDropOpen] = useState(false) // With room for two panes the sections stand in a list of their own beside // the page, the way Settings on an iPad does, instead of behind a dropdown. @@ -59,9 +59,8 @@ export default function MSettings() { { id: 'appearance', label: t('settings.tabs.appearance'), icon: Palette, group: accountGroup }, { id: 'map', label: t('settings.tabs.map'), icon: Map, group: accountGroup }, { id: 'notifications', label: t('settings.tabs.notifications'), icon: Bell, group: accountGroup }, - ...(hasIntegrations - ? [{ id: 'integrations', label: t('settings.tabs.integrations'), icon: Plug, group: accountGroup }] - : []), + // Always there, as on the desktop: API keys sit in this tab and need no addon. + { id: 'integrations', label: t('settings.tabs.integrations'), icon: Plug, group: accountGroup }, ...(hasPlugins && !managed ? [{ id: 'plugins', label: t('settings.tabs.plugins'), icon: Puzzle, group: accountGroup }] : []), @@ -136,7 +135,7 @@ export default function MSettings() { {active.id === 'appearance' && } {active.id === 'map' && } {active.id === 'notifications' && } - {active.id === 'integrations' && hasIntegrations && } + {active.id === 'integrations' && } {/* Per-plugin settings still reuse the existing responsive tab. */} {active.id === 'plugins' && hasPlugins && !managed && } {/* Each card hides itself where it has nothing to offer; their own margins give way to one gap. */} diff --git a/client/src/mobile/screens/settings/MSettingsIntegrations.tsx b/client/src/mobile/screens/settings/MSettingsIntegrations.tsx index 5923948f3..c32e10014 100644 --- a/client/src/mobile/screens/settings/MSettingsIntegrations.tsx +++ b/client/src/mobile/screens/settings/MSettingsIntegrations.tsx @@ -6,6 +6,10 @@ import MWandererConnectionSection from './MWandererConnectionSection' import MLlmConnectionSection from './MLlmConnectionSection' import MAiConnectionSection from './MAiConnectionSection' import MSettingsMcp from './MSettingsMcp' +import MApiKeysSection from './MApiKeysSection' +import DemoLock from '../../../components/Demo/DemoLock' +import { useDemoAccountLock } from '../../../components/Demo/useDemoLock' +import { useTranslation } from '../../../i18n' import { useIntegrationGates } from '../../../components/Settings/useIntegrationGates' /** @@ -17,6 +21,9 @@ import { useIntegrationGates } from '../../../components/Settings/useIntegration export default function MSettingsIntegrations() { const { mcpEnabled, airtrailEnabled, llmEnabled, aiAssistantEnabled, aiConnectionEnabled, ownParsing, dawarichEnabled, wandererEnabled, managed } = useIntegrationGates({ reloadAddons: true }) + const { t } = useTranslation() + const demoLocked = useDemoAccountLock() + return ( <> {/* Forwarded booking mails: hides itself where this server or plan has no import. */} @@ -33,6 +40,10 @@ export default function MSettingsIntegrations() { a managed install. The per-user fallback exists for people who supply their own key, and there nobody does. */} {llmEnabled && ownParsing && !managed && } + {/* An API key needs no addon, so it comes ahead of MCP, as on the desktop. */} + + + {mcpEnabled && } ) diff --git a/client/src/repo/apiKeysRepo.ts b/client/src/repo/apiKeysRepo.ts new file mode 100644 index 000000000..ab64306df --- /dev/null +++ b/client/src/repo/apiKeysRepo.ts @@ -0,0 +1,12 @@ +import { authApi } from '../api/client'; + +/** + * Public API keys, deliberately online-only: a key is minted by the server and + * its secret is shown exactly once, so there is nothing a device could hold or + * replay offline. The settings views reach them through here, never the API. + */ +export const apiKeysRepo = { + list: authApi.apiKeys.list, + create: authApi.apiKeys.create, + delete: authApi.apiKeys.delete, +}; diff --git a/client/tests/unit/mobile/admin/MAdminSheets.test.tsx b/client/tests/unit/mobile/admin/MAdminSheets.test.tsx index 4d52385ad..5fa85d34f 100644 --- a/client/tests/unit/mobile/admin/MAdminSheets.test.tsx +++ b/client/tests/unit/mobile/admin/MAdminSheets.test.tsx @@ -217,7 +217,7 @@ describe('MAdminSheets', () => { expect(hitId).toBe('2'); }); - it('FE-MOB-ASHEET-027: unlinking single sign-on confirms first, then forgets that user's SSO identity', async () => { + it('FE-MOB-ASHEET-027: unlinking single sign-on confirms first, then forgets the SSO identity of that user', async () => { const user = userEvent.setup(); let hitId = ''; server.use( diff --git a/client/tests/unit/mobile/settings/MApiKeysSection.test.tsx b/client/tests/unit/mobile/settings/MApiKeysSection.test.tsx new file mode 100644 index 000000000..f375bffd1 --- /dev/null +++ b/client/tests/unit/mobile/settings/MApiKeysSection.test.tsx @@ -0,0 +1,122 @@ +// FE-MOB-APIKEY-001 to FE-MOB-APIKEY-005 +import userEvent from '@testing-library/user-event'; +import { http, HttpResponse } from 'msw'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import MApiKeysSection from '../../../../src/mobile/screens/settings/MApiKeysSection'; +import { server } from '../../../helpers/msw/server'; +import { render, screen, waitFor, within } from '../../../helpers/render'; +import { resetAllStores } from '../../../helpers/store'; + +const KEY = { + id: 7, + name: 'Dawarich', + token_prefix: 'trek_abc', + created_at: '2026-08-27 10:00:00', + last_used_at: null, + scope_mode: 'limited', + scopes: ['trips', 'places'], +}; + +beforeEach(() => { + resetAllStores(); + server.use(http.get('/api/auth/api-tokens', () => HttpResponse.json({ tokens: [] }))); +}); + +describe('MApiKeysSection', () => { + it('FE-MOB-APIKEY-001: no keys yet says so and offers the endpoint', async () => { + render(); + expect(await screen.findByText(/No keys yet/)).toBeInTheDocument(); + expect(screen.getByText(/\/api\/v1$/)).toBeInTheDocument(); + }); + + it('FE-MOB-APIKEY-002: a key shows its name, prefix and the areas it may read', async () => { + server.use(http.get('/api/auth/api-tokens', () => HttpResponse.json({ tokens: [KEY] }))); + render(); + expect(await screen.findByText('Dawarich')).toBeInTheDocument(); + expect(screen.getByText('trek_abc…')).toBeInTheDocument(); + expect(screen.getByText('1/10')).toBeInTheDocument(); + }); + + it('FE-MOB-APIKEY-003: creating a key sends its name and shows the key once', async () => { + const user = userEvent.setup(); + let body: Record | null = null; + server.use( + http.post('/api/auth/api-tokens', async ({ request }) => { + body = (await request.json()) as Record; + return HttpResponse.json({ + token: { + id: 1, + name: 'Home', + raw_token: 'trek_thefullsecret', + token_prefix: 'trek_thefull', + created_at: '2026-08-27T10:00:00Z', + }, + }); + }) + ); + render(); + await screen.findByText(/No keys yet/); + + await user.click(screen.getByRole('button', { name: /Create key/ })); + const sheet = await screen.findByRole('dialog'); + await user.type(within(sheet).getByLabelText('Name'), 'Home'); + await user.click(within(sheet).getByRole('button', { name: 'Create' })); + + expect(await screen.findByText('trek_thefullsecret')).toBeInTheDocument(); + // Every area selected means no narrowing: the server stores the key as reading everything. + expect(body).toEqual({ name: 'Home' }); + }); + + it('FE-MOB-APIKEY-004: switching an area off narrows the new key', async () => { + const user = userEvent.setup(); + let body: Record | null = null; + server.use( + http.post('/api/auth/api-tokens', async ({ request }) => { + body = (await request.json()) as Record; + return HttpResponse.json({ + token: { + id: 1, + name: 'Home', + raw_token: 'trek_x', + token_prefix: 'trek_x', + created_at: '2026-08-27T10:00:00Z', + }, + }); + }) + ); + render(); + await screen.findByText(/No keys yet/); + await user.click(screen.getByRole('button', { name: /Create key/ })); + const sheet = await screen.findByRole('dialog'); + await user.type(within(sheet).getByLabelText('Name'), 'Home'); + const pressed = within(sheet).getAllByRole('button', { pressed: true }); + await user.click(pressed[0]); + await user.click(within(sheet).getByRole('button', { name: 'Create' })); + await waitFor(() => expect(body).not.toBeNull()); + expect(Array.isArray((body as unknown as { scopes: unknown }).scopes)).toBe(true); + }); + + it('FE-MOB-APIKEY-005: deleting a key asks first, then removes it', async () => { + const user = userEvent.setup(); + let deleted = false; + server.use( + http.get('/api/auth/api-tokens', () => HttpResponse.json({ tokens: [KEY] })), + http.delete('/api/auth/api-tokens/:id', () => { + deleted = true; + return HttpResponse.json({ success: true }); + }) + ); + render(); + await screen.findByText('Dawarich'); + await user.click(screen.getByRole('button', { name: 'Delete key' })); + const confirm = await screen.findByRole('dialog', { name: 'Delete key' }); + await user.click(within(confirm).getByRole('button', { name: 'Delete key' })); + await waitFor(() => expect(deleted).toBe(true)); + await waitFor(() => expect(screen.queryByText('Dawarich')).not.toBeInTheDocument()); + }); +}); + +vi.mock('../../../../src/components/shared/Toast', async (importOriginal) => ({ + ...(await importOriginal()), + useToast: () => ({ success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() }), +}));