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.
This commit is contained in:
Maurice
2026-11-14 11:19:06 +01:00
parent 5caa890523
commit a40ae60abb
11 changed files with 633 additions and 194 deletions
+6
View File
@@ -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"],
-2
View File
@@ -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",
+28 -184
View File
@@ -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<PublicApiScope, LucideIcon> = {
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<ApiKey[]>([])
/** 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<string | null>(null)
const [deleteId, setDeleteId] = useState<number | null>(null)
const [copied, setCopied] = useState<'key' | 'endpoint' | null>(null)
const copiedTimer = useRef<ReturnType<typeof setTimeout> | 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<Set<PublicApiScope>>(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 = (
<DialogHeader
@@ -241,7 +85,7 @@ export default function ApiKeysSection(): React.ReactElement {
id="api-keys"
title={t('settings.apiKeys.title')}
icon={KeyRound}
badge={keys.length > 0 ? <StatusPill>{keys.length}/{MAX_KEYS}</StatusPill> : undefined}
badge={keys.length > 0 ? <StatusPill>{keys.length}/{MAX_API_KEYS}</StatusPill> : undefined}
action={(
<button type="button" onClick={openModal} disabled={atLimit} className={SETTINGS_BUTTON_PRIMARY}>
<Plus size={14} /> {t('settings.apiKeys.create')}
@@ -253,7 +97,7 @@ export default function ApiKeysSection(): React.ReactElement {
{atLimit && (
<div className="flex gap-2.5 rounded-[12px] bg-warning-soft px-3.5 py-2.5 text-content" style={fs(12.5, 'body')}>
<AlertTriangle size={15} className="mt-px flex-none text-warning" />
<p className="m-0 leading-snug">{t('settings.apiKeys.limitReached', { count: MAX_KEYS })}</p>
<p className="m-0 leading-snug">{t('settings.apiKeys.limitReached', { count: MAX_API_KEYS })}</p>
</div>
)}
@@ -357,7 +201,7 @@ export default function ApiKeysSection(): React.ReactElement {
<SettingsHint className="mb-3">{t('settings.apiScopes.hint')}</SettingsHint>
<div className={GRID_2}>
{PUBLIC_API_SCOPES.map(scope => (
<ScopeOption key={scope} icon={SCOPE_ICONS[scope]} label={t(`settings.apiScopes.${scope}`)}
<ScopeOption key={scope} icon={API_SCOPE_ICONS[scope]} label={t(`settings.apiScopes.${scope}`)}
checked={newScopes.has(scope)} onToggle={() => toggleScope(scope)} />
))}
</div>
@@ -398,10 +242,10 @@ function ApiKeyRow({ apiKey, locale, onDelete }: { apiKey: ApiKey; locale: strin
</code>
</div>
<p className="m-0 mt-0.5 tabular-nums text-content-faint first-letter:uppercase" style={fs(11.5)}>
{t('settings.apiKeys.createdAt')} {formatStamp(apiKey.created_at, locale, dateFormat)}
{t('settings.apiKeys.createdAt')} {formatApiKeyStamp(apiKey.created_at, locale, dateFormat)}
{', '}
{apiKey.last_used_at
? `${t('settings.apiKeys.usedAt')} ${formatStamp(apiKey.last_used_at, locale, dateFormat)}`
? `${t('settings.apiKeys.usedAt')} ${formatApiKeyStamp(apiKey.last_used_at, locale, dateFormat)}`
: t('settings.apiKeys.neverUsed')}
</p>
{/* What the key may read. Shown on the row rather than behind a detail
@@ -409,7 +253,7 @@ function ApiKeyRow({ apiKey, locale, onDelete }: { apiKey: ApiKey; locale: strin
that you did. */}
<div className="mt-2 flex flex-wrap gap-1">
{scopes ? scopes.map(scope => {
const Icon = SCOPE_ICONS[scope]
const Icon = API_SCOPE_ICONS[scope]
return (
<StatusPill key={scope} icon={Icon ? <Icon size={11} strokeWidth={2.2} /> : undefined}>
{t(`settings.apiScopes.${scope}`)}
@@ -0,0 +1,203 @@
import { PUBLIC_API_SCOPES, type PublicApiScope } from '@trek/shared';
import type { LucideIcon } from 'lucide-react';
import { BarChart3, Briefcase, CalendarDays, Hotel, MapPin, Star, StickyNote, Ticket, Users } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
import { useTranslation } from '../../i18n';
import { apiKeysRepo } from '../../repo/apiKeysRepo';
import { formatDisplayDate } from '../../utils/dateFormat';
import { useToast } from '../shared/Toast';
/**
* Keys for the public API, the credential a user hands to other software that
* should read their trips: the list, minting one (shown once, then only its
* prefix), deleting one, and copying the key or the endpoint. Shared by the
* desktop ApiKeysSection and the phone MApiKeysSection. Its own state rather
* than the MCP hook's, so it works on an instance with MCP switched off.
*/
export 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`). */
export const MAX_API_KEYS = 10;
/** The glyph each area already wears elsewhere in the app, so the list reads like the planner. */
export const API_SCOPE_ICONS: Record<PublicApiScope, LucideIcon> = {
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. */
export function formatApiKeyStamp(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);
}
export function useApiKeys() {
const { t } = useTranslation();
const toast = useToast();
const [keys, setKeys] = useState<ApiKey[]>([]);
/** 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 dialog closes: the server keeps a hash. */
const [created, setCreated] = useState<string | null>(null);
const [deleteId, setDeleteId] = useState<number | null>(null);
const [copied, setCopied] = useState<'key' | 'endpoint' | null>(null);
const copiedTimer = useRef<ReturnType<typeof setTimeout> | 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<Set<PublicApiScope>>(new Set(PUBLIC_API_SCOPES));
const endpoint = `${window.location.origin}/api/v1`;
const atLimit = keys.length >= MAX_API_KEYS;
const allSelected = newScopes.size === PUBLIC_API_SCOPES.length;
const canCreate = !!newName.trim() && !creating && newScopes.size > 0;
useEffect(() => {
let cancelled = false;
apiKeysRepo
.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 apiKeysRepo.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 apiKeysRepo.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;
});
};
return {
keys,
loadState,
modalOpen,
newName,
setNewName,
creating,
created,
deleteId,
setDeleteId,
copied,
newScopes,
setNewScopes,
endpoint,
atLimit,
allSelected,
canCreate,
handleCreate,
handleDelete,
handleCopy,
openModal,
closeModal,
toggleScope,
};
}
@@ -6,8 +6,8 @@ import { useSettingsStore } from '../../store/settingsStore';
/**
* Which integrations the settings shells offer: the addon flags behind each
* integration section, whether any of them is on, and whether this is a managed
* install. The desktop Integrations tab shows regardless, since its API keys need
* no addon; the mobile one has no API keys and only shows when `hasIntegrations`.
* install. The Integrations tab shows regardless on both shells, since the API
* keys in it need no addon; `hasIntegrations` says whether any addon section is on.
* With `reloadAddons` the addon list is fetched again on mount, as the
* integrations tab on both shells does.
*/
@@ -0,0 +1,244 @@
import { PUBLIC_API_SCOPES } from '@trek/shared';
import { AlertTriangle, Check, Copy, KeyRound, Plus, Trash2 } from 'lucide-react';
import {
API_SCOPE_ICONS,
MAX_API_KEYS,
formatApiKeyStamp,
useApiKeys,
type ApiKey,
} from '../../../components/Settings/useApiKeys';
import { useDateFormat } from '../../../hooks/useDateFormat';
import { useTranslation } from '../../../i18n';
import MSheet from '../../components/MSheet';
import { MAdminButton, MAdminSheetFrame } from '../admin/MAdminUi';
import MConfirmSheet from './MConfirmSheet';
import { MSetButton, MSetCard, MSetEyebrow, MSetHint, MSetInput } from './MSettingsUi';
const NOTE = 'font-geist text-[length:calc(10.5px*var(--fs-scale-caption,1))] leading-relaxed';
function MApiKeyRow({ apiKey, locale, onDelete }: { apiKey: ApiKey; locale: string; onDelete: () => void }) {
const { t } = useTranslation();
const dateFormat = useDateFormat();
const scopes = apiKey.scope_mode === 'limited' ? apiKey.scopes : undefined;
return (
<li className="flex items-start gap-[10px] border-t border-[color:var(--m-rowbr)] py-[10px] first:border-t-0">
<div className="min-w-0 flex-1">
<div className="flex min-w-0 items-center gap-[6px]">
<span className="min-w-0 truncate text-[length:calc(12.5px*var(--fs-scale-body,1))] font-bold text-m-ink">
{apiKey.name}
</span>
<code className={`flex-none text-m-faint ${NOTE}`}>{apiKey.token_prefix}…</code>
</div>
<p className={`mt-[1px] tabular-nums text-m-muted first-letter:uppercase ${NOTE}`}>
{t('settings.apiKeys.createdAt')} {formatApiKeyStamp(apiKey.created_at, locale, dateFormat)}
{', '}
{apiKey.last_used_at
? `${t('settings.apiKeys.usedAt')} ${formatApiKeyStamp(apiKey.last_used_at, locale, dateFormat)}`
: t('settings.apiKeys.neverUsed')}
</p>
{/* What the key may read, on the row: the reason to narrow a key is to see later that you did. */}
<p className={`mt-[2px] text-m-muted ${NOTE}`}>
{scopes ? scopes.map((scope) => t(`settings.apiScopes.${scope}`)).join(', ') : t('settings.apiScopes.all')}
</p>
</div>
<button
type="button"
onClick={onDelete}
aria-label={t('settings.apiKeys.deleteTitle')}
className="flex h-[32px] w-[32px] flex-none items-center justify-center rounded-full bg-[color:var(--m-ic)] text-[color:var(--m-st-danger)]"
>
<Trash2 size={14} />
</button>
</li>
);
}
/**
* 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 (
<>
<MSetCard
title={t('settings.apiKeys.title')}
icon={KeyRound}
className="mt-3"
badge={
K.keys.length > 0 ? (
<span className={`flex-none font-bold text-m-muted ${NOTE}`}>
{K.keys.length}/{MAX_API_KEYS}
</span>
) : undefined
}
>
<MSetHint className="mt-0">{t('settings.apiKeys.description')}</MSetHint>
{K.atLimit && (
<p className={`mt-2 font-bold text-[color:var(--m-st-pending)] ${NOTE}`}>
{t('settings.apiKeys.limitReached', { count: MAX_API_KEYS })}
</p>
)}
{K.loadState === 'failed' && (
<p role="alert" className={`mt-2 font-bold text-[color:var(--m-st-danger)] ${NOTE}`}>
{t('settings.apiKeys.loadFailed')}
</p>
)}
{K.loadState === 'ready' && K.keys.length === 0 && (
<p className={`mt-2 text-m-muted ${NOTE}`}>{t('settings.apiKeys.empty')}</p>
)}
{K.keys.length > 0 && (
<ul className="mt-2">
{K.keys.map((key) => (
<MApiKeyRow key={key.id} apiKey={key} locale={locale} onDelete={() => K.setDeleteId(key.id)} />
))}
</ul>
)}
<div className="mt-3">
<MSetButton disabled={K.atLimit} onClick={K.openModal}>
<Plus size={14} /> {t('settings.apiKeys.create')}
</MSetButton>
</div>
<div className="mt-4 border-t border-[color:var(--m-rowbr)] pt-3">
<MSetEyebrow className="mb-[5px]">{t('settings.apiKeys.endpoint')}</MSetEyebrow>
<div className="flex items-center gap-2">
<code className="block min-w-0 flex-1 truncate rounded-xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-sheet)] px-[13px] py-[10px] font-geist text-[length:calc(12px*var(--fs-scale-body,1))] text-m-ink">
{K.endpoint}
</code>
<button
type="button"
aria-label={t('common.copy')}
onClick={() => void K.handleCopy(K.endpoint, 'endpoint')}
className="flex h-[38px] w-[38px] flex-none items-center justify-center rounded-full bg-[color:var(--m-ic)] text-m-ink"
>
{K.copied === 'endpoint' ? <Check size={15} /> : <Copy size={15} />}
</button>
</div>
<MSetHint>{t('settings.apiKeys.docsHint')}</MSetHint>
</div>
</MSetCard>
{/* 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. */}
<MSheet
open={K.modalOpen}
onClose={K.created ? () => {} : K.closeModal}
ariaLabel={K.created ? t('settings.apiKeys.modal.createdTitle') : t('settings.apiKeys.modal.createTitle')}
>
<MAdminSheetFrame
title={K.created ? t('settings.apiKeys.modal.createdTitle') : t('settings.apiKeys.modal.createTitle')}
icon={<KeyRound size={18} />}
onClose={K.closeModal}
footer={
K.created ? (
<MAdminButton onClick={K.closeModal}>{t('settings.apiKeys.modal.done')}</MAdminButton>
) : (
<>
<MAdminButton variant="ghost" onClick={K.closeModal}>
{t('common.cancel')}
</MAdminButton>
<MAdminButton busy={K.creating} disabled={!K.canCreate} onClick={() => void K.handleCreate()}>
{K.creating ? t('settings.apiKeys.modal.creating') : t('settings.apiKeys.modal.create')}
</MAdminButton>
</>
)
}
>
{K.created ? (
<div className="space-y-3">
<p className={`flex items-start gap-2 text-m-ink ${NOTE}`}>
<AlertTriangle size={14} className="mt-[1px] flex-none text-[color:var(--m-st-pending)]" />
{t('settings.apiKeys.modal.createdWarning')}
</p>
<code className="block select-all break-all rounded-xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-sheet)] px-[13px] py-[11px] font-geist text-[length:calc(12px*var(--fs-scale-body,1))] text-m-ink">
{K.created}
</code>
<MSetButton variant="ghost" onClick={() => void K.handleCopy(K.created ?? '', 'key')}>
{K.copied === 'key' ? <Check size={14} /> : <Copy size={14} />}
{K.copied === 'key' ? t('common.copied') : t('settings.apiKeys.copy')}
</MSetButton>
</div>
) : (
<div className="space-y-4">
<div>
<MSetEyebrow className="mb-[5px]">{t('settings.apiKeys.modal.name')}</MSetEyebrow>
<MSetInput
aria-label={t('settings.apiKeys.modal.name')}
value={K.newName}
maxLength={100}
placeholder={t('settings.apiKeys.modal.namePlaceholder')}
onChange={(e) => K.setNewName(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') void K.handleCreate();
}}
/>
<MSetHint>{t('settings.apiKeys.modal.nameHint')}</MSetHint>
</div>
<section role="group" aria-label={t('settings.apiScopes.title')}>
<div className="mb-[5px] flex items-center gap-2">
<MSetEyebrow className="min-w-0 flex-1">{t('settings.apiScopes.title')}</MSetEyebrow>
<button
type="button"
onClick={() => K.setNewScopes(K.allSelected ? new Set() : new Set(PUBLIC_API_SCOPES))}
className={`flex-none font-bold text-m-muted ${NOTE}`}
>
{K.allSelected ? t('common.deselectAll') : t('common.selectAll')}
</button>
</div>
<MSetHint className="mb-2 mt-0">{t('settings.apiScopes.hint')}</MSetHint>
<div className="flex flex-wrap gap-[6px]">
{PUBLIC_API_SCOPES.map((scope) => {
const Icon = API_SCOPE_ICONS[scope];
const on = K.newScopes.has(scope);
return (
<button
key={scope}
type="button"
aria-pressed={on}
onClick={() => K.toggleScope(scope)}
className={`inline-flex h-[32px] items-center gap-[6px] whitespace-nowrap rounded-full border px-[11px] text-[length:calc(12px*var(--fs-scale-body,1))] font-bold ${
on
? 'border-transparent bg-m-act text-m-actfg'
: 'border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] text-m-muted'
}`}
>
<Icon size={13} strokeWidth={2.2} aria-hidden />
{t(`settings.apiScopes.${scope}`)}
</button>
);
})}
</div>
{K.newScopes.size === 0 && (
<p className={`mt-2 font-bold text-[color:var(--m-st-danger)] ${NOTE}`}>
{t('settings.apiScopes.noneSelected')}
</p>
)}
</section>
</div>
)}
</MAdminSheetFrame>
</MSheet>
<MConfirmSheet
open={K.deleteId !== null}
onClose={() => 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);
}}
/>
</>
);
}
@@ -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' && <MSettingsAppearance />}
{active.id === 'map' && <MSettingsMap />}
{active.id === 'notifications' && <MSettingsNotifications />}
{active.id === 'integrations' && hasIntegrations && <MSettingsIntegrations />}
{active.id === 'integrations' && <MSettingsIntegrations />}
{/* Per-plugin settings still reuse the existing responsive tab. */}
{active.id === 'plugins' && hasPlugins && !managed && <MSettingsPlugins />}
{/* Each card hides itself where it has nothing to offer; their own margins give way to one gap. */}
@@ -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 && <MLlmConnectionSection />}
{/* An API key needs no addon, so it comes ahead of MCP, as on the desktop. */}
<DemoLock locked={demoLocked} reason={t('demo.lock.apiKeys')}>
<MApiKeysSection />
</DemoLock>
{mcpEnabled && <MSettingsMcp />}
</>
)
+12
View File
@@ -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,
};
@@ -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(
@@ -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(<MApiKeysSection />);
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(<MApiKeysSection />);
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<string, unknown> | null = null;
server.use(
http.post('/api/auth/api-tokens', async ({ request }) => {
body = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({
token: {
id: 1,
name: 'Home',
raw_token: 'trek_thefullsecret',
token_prefix: 'trek_thefull',
created_at: '2026-08-27T10:00:00Z',
},
});
})
);
render(<MApiKeysSection />);
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<string, unknown> | null = null;
server.use(
http.post('/api/auth/api-tokens', async ({ request }) => {
body = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({
token: {
id: 1,
name: 'Home',
raw_token: 'trek_x',
token_prefix: 'trek_x',
created_at: '2026-08-27T10:00:00Z',
},
});
})
);
render(<MApiKeysSection />);
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(<MApiKeysSection />);
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<typeof import('../../../../src/components/shared/Toast')>()),
useToast: () => ({ success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() }),
}));