Files
platform/src/apps/officer-web/Screens/Dashboard/Settings/ProfileSettings/ApiKeys.tsx
T
pastilhas ad8ed88519 profile settings keyed (425 -> 352)
ProfileSettings reaches zero: api keys, profile, voice, dock, languages and the
model defaults.

Language names now come from Intl.DisplayNames rather than the catalog. The runtime
already knows "German" in English and "alemao" in Portuguese, so 28 names would have
been 56 hand-written entries that Intl gets right for free -- including for locales
not shipped yet. Same reasoning D7 gives for dates and numbers. The tag LIST stays
hardcoded: which languages you may claim to speak is a product choice.

ApiKeys had toLocaleDateString(undefined, ...), which followed the BROWSER locale --
the exact contradiction D7 describes. It uses useFormat().date now. Its revoked-key
toggle hand-rolled a plural with a ternary on n === 1; that is a real plural entry now.

Scanner: an Authorization header value like "Bearer <token>" is not a sentence.
Excluded by auth-scheme prefix; verified the delta is exactly the four such
credentials across both remaining areas.
2026-08-23 04:57:48 +00:00

267 lines
11 KiB
TypeScript

import type { FormEvent } from 'react';
import { useState } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import { useFormat } from 'i18n';
import { useTranslation } from '@/lib/i18n';
import { Copy, Ban, Plus, KeyRound, Loader2, Trash2 } from 'lucide-react';
import { useClient } from 'hooks/useClient';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Button } from '@/components/ui/button';
import { copyToClipboard } from 'helpers/clipboard';
// Your own API keys: one per app or device, so a phone holds a credential you can revoke on its own
// instead of a session everything shares.
//
// The key is returned by POST and never again — the column holds a SHA-256, so there is nothing to read
// back. That drives the whole screen: the new key sits in a panel that stays put until dismissed, because
// the moment it disappears the only remedy is to revoke and mint another. Same reasoning as the DAV app
// passwords beside this.
//
// A key carries your full account authority. It is not more than you already had — it is what your
// password could already do — but it does mean a leaked key is a leaked account, so revoke is one click
// and "last used" is on every row: a key that has never been used is the tell that something was set up
// wrong, and one used from somewhere you did not expect is the tell that matters more.
type ApiKey = {
id: number;
name: string;
prefix: string;
lastUsedAt: string | null;
expiresAt: string | null;
revokedAt: string | null;
createdAt: string;
};
type Minted = { key: string; name: string };
const API_KEYS_QUERY_KEY = ['API_KEYS'];
// `toLocaleDateString(undefined, …)` followed the BROWSER's locale, so a Portuguese UI showed the
// browser's dates. `useFormat` binds it to the locale the rest of the app is in (D7).
export const ApiKeys = () => {
const { t } = useTranslation();
const { date: formatDate } = useFormat();
const copy = async (text: string) => {
try {
await copyToClipboard(text);
toast.success(t('settings.profile.apiKeys.copied'));
} catch {
toast.error(t('settings.profile.apiKeys.copyFailed'));
}
};
const client = useClient();
const queryClient = useQueryClient();
const [name, setName] = useState('');
const [isCreating, setIsCreating] = useState(false);
const [showRevoked, setShowRevoked] = useState(false);
const [minted, setMinted] = useState<Minted | null>(null);
const { data, isLoading } = useQuery<{ keys: ApiKey[] }>({
queryKey: API_KEYS_QUERY_KEY,
queryFn: () => client.get<{ keys: ApiKey[] }>('/api-keys'),
});
const refresh = () => queryClient.invalidateQueries({ queryKey: API_KEYS_QUERY_KEY });
const create = async (ev?: FormEvent) => {
ev?.preventDefault();
const trimmed = name.trim();
if (!trimmed || isCreating) return;
setIsCreating(true);
try {
const res = await client.post<{ key: string }>('/api-keys', { name: trimmed });
setMinted({ key: res.key, name: trimmed });
setName('');
await refresh();
} catch (ex) {
toast.error(ex instanceof Error ? ex.message : t('settings.profile.apiKeys.createFailed'));
} finally {
setIsCreating(false);
}
};
const forget = async (id: number) => {
try {
await client.delete(`/api-keys/${id}/record`);
await refresh();
} catch {
toast.error(t('settings.profile.apiKeys.forgetFailed'));
}
};
const revoke = async (id: number) => {
try {
await client.delete(`/api-keys/${id}`);
toast.success(t('settings.profile.apiKeys.revokeDone'));
await refresh();
} catch {
toast.error(t('settings.profile.apiKeys.revokeFailed'));
}
};
const allKeys = data?.keys ?? [];
// Dead means revoked OR past its expiry — the same test the row rendering uses, lifted here so the
// count in the toggle and the rows it reveals can never disagree.
const isDead = (entry: ApiKey) =>
!!entry.revokedAt || (!!entry.expiresAt && new Date(entry.expiresAt).getTime() <= Date.now());
// Dead keys are HIDDEN by default rather than merely dimmed. Revoking is the normal end of a key's
// life, so on any account that has been used for a while the dead ones outnumber the live ones and the
// screen stops answering the question it exists for — which of my keys still work. The rows are kept
// and reachable; they are just not the first thing shown.
const deadKeys = allKeys.filter(isDead);
const keys = showRevoked ? allKeys : allKeys.filter((entry) => !isDead(entry));
if (isLoading) {
return (
<div className="flex items-center gap-2 p-6 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" /> {t('settings.profile.apiKeys.loading')}
</div>
);
}
return (
<div className="grid gap-5">
<p className="text-sm text-duck-dark/70 dark:text-foreground/70">
{t('settings.profile.apiKeys.intro')} <code className="font-mono text-xs">Authorization: Bearer …</code>.
</p>
{minted && (
<div className="grid gap-3 rounded-lg border-2 border-duck-teal/40 bg-duck-teal/5 p-4">
<div className="text-sm font-medium text-duck-dark dark:text-foreground">
{t('settings.profile.apiKeys.mintedTitle', { name: minted.name })}
</div>
<p className="text-xs text-duck-dark/60 dark:text-foreground/60">
This is the only time it is displayed. It's stored hashed, so it can't be shown again — if you lose it,
revoke this entry and make another.
</p>
<div className="flex items-center gap-2">
<code className="min-w-0 flex-1 truncate rounded bg-background/70 px-2 py-1.5 font-mono text-xs">
{minted.key}
</code>
<Button
variant="ghost"
size="sm"
onClick={() => copy(minted.key)}
title={t('settings.profile.apiKeys.copyKey')}
>
<Copy className="h-3.5 w-3.5" />
</Button>
</div>
<Button variant="outline" size="sm" className="justify-self-start" onClick={() => setMinted(null)}>
{t('settings.profile.apiKeys.savedIt')}
</Button>
</div>
)}
<form onSubmit={create} className="flex items-end gap-2">
<Label className="grid flex-1 gap-2">
<span className="text-duck-dark/70 dark:text-foreground/70">{t('settings.profile.apiKeys.newKey')}</span>
<Input
className="h-11 bg-background/60 border-duck-dark/20"
value={name}
onChange={(ev) => setName(ev.target.value)}
placeholder={t('settings.profile.apiKeys.namePlaceholder')}
/>
</Label>
<Button type="submit" disabled={!name.trim() || isCreating} className="h-11">
<Plus className="me-1.5 h-4 w-4" />
{t('settings.profile.apiKeys.create')}
</Button>
</form>
{keys.length === 0 ? (
<div className="rounded-lg border border-dashed border-duck-dark/15 dark:border-foreground/15 p-6 text-center text-sm text-duck-dark/40 dark:text-foreground/40">
{/* "No keys yet" would be false on an account whose keys are all revoked, and it is the sentence
that would send somebody looking for a bug in the list. */}
{allKeys.length === 0 ? t('settings.profile.apiKeys.noneYet') : t('settings.profile.apiKeys.noneInUse')}
</div>
) : (
<div className="grid gap-2">
{keys.map((entry) => {
const expired = !!entry.expiresAt && new Date(entry.expiresAt).getTime() <= Date.now();
const dead = !!entry.revokedAt || expired;
const lastUsed = entry.lastUsedAt
? formatDate(entry.lastUsedAt, { month: 'short', day: 'numeric', year: 'numeric' })
: null;
return (
<div
key={entry.id}
className={`flex items-center gap-3 rounded-lg border p-3 ${
dead
? 'border-duck-dark/10 dark:border-foreground/10 opacity-50'
: 'border-duck-dark/15 dark:border-foreground/15'
}`}
>
<KeyRound className="h-4 w-4 shrink-0 text-duck-teal/70" />
<div className="min-w-0 flex-1">
<div className="truncate text-sm text-duck-dark dark:text-foreground">
{entry.name}
{entry.revokedAt && (
<span className="ms-2 text-xs text-red-500">{t('settings.profile.apiKeys.revoked')}</span>
)}
{!entry.revokedAt && expired && (
<span className="ms-2 text-xs text-red-500">{t('settings.profile.apiKeys.expired')}</span>
)}
</div>
<div className="text-xs text-duck-dark/40 dark:text-foreground/40">
<code className="font-mono">{entry.prefix}…</code>
{' · '}
{/* "never used" is the tell that an app was configured wrong, so it earns its own wording. */}
{lastUsed
? t('settings.profile.apiKeys.lastUsed', { date: lastUsed })
: t('settings.profile.apiKeys.neverUsed')}
</div>
</div>
{dead ? (
// Only offered once the key is already dead — the server refuses it otherwise, and the
// button matching that rule is what keeps the two from drifting.
<Button
variant="ghost"
size="sm"
onClick={() => void forget(entry.id)}
title={t('settings.profile.apiKeys.forget')}
className="hover:text-red-500"
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
) : (
<Button
variant="ghost"
size="sm"
onClick={() => void revoke(entry.id)}
title={t('settings.profile.apiKeys.revoke')}
className="hover:text-red-500"
>
<Ban className="h-3.5 w-3.5" />
</Button>
)}
</div>
);
})}
</div>
)}
{deadKeys.length > 0 && (
<button
type="button"
onClick={() => setShowRevoked((v) => !v)}
className="mt-3 cursor-pointer text-xs text-duck-dark/40 underline underline-offset-2 transition-colors hover:text-duck-dark/70 dark:text-foreground/40 dark:hover:text-foreground/70"
>
{showRevoked
? t('settings.profile.apiKeys.hideDead')
: t('settings.profile.apiKeys.showDead', { count: deadKeys.length })}
</button>
)}
</div>
);
};