Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
feat: add API keys management UI in settings
Gabriel Steinc7c4b42110db
diff --git a/src/components/ApiKeysSection.tsx b/src/components/ApiKeysSection.tsxnew file mode 100644index 000000000..4743aff44--- /dev/null+++ b/src/components/ApiKeysSection.tsx@@ -0,0 +1,404 @@+import { useState, useEffect, useCallback } from "react";+import { useTranslation } from "react-i18next";+import { Key, Copy, Check, Trash2, Plus, Shield, AlertTriangle } from "lucide-react";+import { Button } from "./ui/button";+import { Input } from "./ui/input";+import { Badge } from "./ui/badge";+import { Skeleton } from "./ui/skeleton";+import { useToast } from "./ui/Toast";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogDescription,+ DialogFooter,+ ConfirmDialog,+} from "./ui/dialog";+import { SectionHeader, SettingsPanel, SettingsPanelRow } from "./ui/SettingsSection";+import { ApiKeysService } from "../services/ApiKeysService";+import type { ApiKey } from "../services/ApiKeysService";++const MAX_KEYS = 5;+const MAX_NAME_LENGTH = 100;++const ALL_SCOPES = ["notes:read", "notes:write", "transcriptions:read", "usage:read"] as const;++function formatRelativeTime(dateString: string): string {+ const seconds = Math.floor((Date.now() - new Date(dateString).getTime()) / 1000);+ if (seconds < 60) return "just now";+ const minutes = Math.floor(seconds / 60);+ if (minutes < 60) return `${minutes}m ago`;+ const hours = Math.floor(minutes / 60);+ if (hours < 24) return `${hours}h ago`;+ const days = Math.floor(hours / 24);+ if (days < 30) return `${days}d ago`;+ const months = Math.floor(days / 30);+ return `${months}mo ago`;+}++export default function ApiKeysSection() {+ const { t } = useTranslation();+ const { toast } = useToast();++ const [keys, setKeys] = useState<ApiKey[]>([]);+ const [isLoading, setIsLoading] = useState(true);+ const [createOpen, setCreateOpen] = useState(false);+ const [revokeTarget, setRevokeTarget] = useState<ApiKey | null>(null);++ const fetchKeys = useCallback(async () => {+ try {+ const { keys: fetched } = await ApiKeysService.list();+ setKeys(fetched);+ } catch {+ toast({+ title: t("apiKeysSection.errors.loadFailed"),+ variant: "destructive",+ });+ } finally {+ setIsLoading(false);+ }+ }, [t, toast]);++ useEffect(() => {+ fetchKeys();+ }, [fetchKeys]);++ const handleRevoke = async () => {+ if (!revokeTarget) return;+ try {+ await ApiKeysService.revoke(revokeTarget.id);+ toast({+ title: t("apiKeysSection.revoke.success"),+ variant: "success",+ });+ setRevokeTarget(null);+ await fetchKeys();+ } catch {+ toast({+ title: t("apiKeysSection.errors.revokeFailed"),+ variant: "destructive",+ });+ }+ };++ return (+ <div className="space-y-4">+ <div className="flex items-center justify-between">+ <SectionHeader+ title={t("apiKeysSection.title")}+ description={t("apiKeysSection.description")}+ />+ {!isLoading && keys.length > 0 && keys.length < MAX_KEYS && (+ <Button variant="outline" size="sm" onClick={() => setCreateOpen(true)}>+ <Plus className="h-3.5 w-3.5 mr-1.5" />+ {t("apiKeysSection.createButton")}+ </Button>+ )}+ </div>++ {isLoading ? (+ <SettingsPanel>+ {[0, 1].map((i) => (+ <SettingsPanelRow key={i}>+ <div className="flex items-center justify-between">+ <div className="space-y-2">+ <Skeleton className="h-3.5 w-32" />+ <Skeleton className="h-3 w-48" />+ </div>+ <Skeleton className="h-8 w-16" />+ </div>+ </SettingsPanelRow>+ ))}+ </SettingsPanel>+ ) : keys.length === 0 ? (+ <SettingsPanel>+ <SettingsPanelRow>+ <div className="flex flex-col items-center py-4 text-center">+ <Key className="h-5 w-5 text-muted-foreground/40 mb-2" />+ <p className="text-xs text-muted-foreground mb-3">{t("apiKeysSection.empty")}</p>+ <Button variant="outline" size="sm" onClick={() => setCreateOpen(true)}>+ <Plus className="h-3.5 w-3.5 mr-1.5" />+ {t("apiKeysSection.createButton")}+ </Button>+ </div>+ </SettingsPanelRow>+ </SettingsPanel>+ ) : (+ <SettingsPanel>+ {keys.map((apiKey) => (+ <SettingsPanelRow key={apiKey.id}>+ <div className="flex items-center justify-between gap-4">+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-2 mb-0.5">+ <span className="text-xs font-medium text-foreground truncate">+ {apiKey.name}+ </span>+ <code className="text-[10px] font-mono text-muted-foreground/60 shrink-0">+ {apiKey.key_prefix}...+ </code>+ </div>+ <div className="flex items-center gap-1.5 flex-wrap">+ {apiKey.scopes.map((scope) => (+ <Badge key={scope} variant="outline" className="text-[10px] px-1.5 py-0">+ {t(`apiKeysSection.scopes.${scope}`)}+ </Badge>+ ))}+ <span className="text-[10px] text-muted-foreground/50 ml-1">+ {apiKey.last_used_at+ ? t("apiKeysSection.lastUsed", {+ time: formatRelativeTime(apiKey.last_used_at),+ })+ : t("apiKeysSection.neverUsed")}+ </span>+ </div>+ </div>+ <Button+ variant="ghost"+ size="sm"+ className="shrink-0 text-muted-foreground hover:text-destructive"+ onClick={() => setRevokeTarget(apiKey)}+ >+ <Trash2 className="h-3.5 w-3.5" />+ </Button>+ </div>+ </SettingsPanelRow>+ ))}++ {keys.length >= MAX_KEYS && (+ <SettingsPanelRow>+ <p className="text-[10px] text-muted-foreground/50 text-center">+ {t("apiKeysSection.maxKeysReached", { max: MAX_KEYS })}+ </p>+ </SettingsPanelRow>+ )}+ </SettingsPanel>+ )}++ <CreateKeyDialog+ open={createOpen}+ onOpenChange={(open) => {+ setCreateOpen(open);+ }}+ onCreated={fetchKeys}+ />++ <ConfirmDialog+ open={!!revokeTarget}+ onOpenChange={(open) => {+ if (!open) setRevokeTarget(null);+ }}+ title={t("apiKeysSection.revoke.confirm")}+ confirmText={t("apiKeysSection.revoke.button")}+ cancelText={t("apiKeysSection.create.cancel")}+ onConfirm={handleRevoke}+ variant="destructive"+ />+ </div>+ );+}++function CreateKeyDialog({+ open,+ onOpenChange,+ onCreated,+}: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ onCreated: () => Promise<void>;+}) {+ const { t } = useTranslation();+ const { toast } = useToast();++ const [name, setName] = useState("");+ const [scopes, setScopes] = useState<Set<string>>(() => new Set(ALL_SCOPES));+ const [isSubmitting, setIsSubmitting] = useState(false);+ const [rawKey, setRawKey] = useState<string | null>(null);+ const [copied, setCopied] = useState(false);++ const resetForm = () => {+ setName("");+ setScopes(new Set(ALL_SCOPES));+ setIsSubmitting(false);+ setRawKey(null);+ setCopied(false);+ };++ const handleClose = (nextOpen: boolean) => {+ if (!nextOpen) {+ setRawKey(null);+ resetForm();+ }+ onOpenChange(nextOpen);+ };++ const handleSubmit = async () => {+ if (!name.trim() || scopes.size === 0) return;+ setIsSubmitting(true);+ try {+ const result = await ApiKeysService.create(name.trim(), Array.from(scopes));+ setRawKey(result.key);+ await onCreated();+ } catch {+ toast({+ title: t("apiKeysSection.errors.createFailed"),+ variant: "destructive",+ });+ setIsSubmitting(false);+ }+ };++ const handleCopy = async () => {+ if (!rawKey) return;+ try {+ await navigator.clipboard.writeText(rawKey);+ setCopied(true);+ toast({+ title: t("apiKeysSection.created.copied"),+ variant: "success",+ duration: 2000,+ });+ setTimeout(() => setCopied(false), 2000);+ } catch {+ // Clipboard write failed — user can still manually select+copy+ }+ };++ const toggleScope = (scope: string) => {+ setScopes((prev) => {+ const next = new Set(prev);+ if (next.has(scope)) {+ next.delete(scope);+ } else {+ next.add(scope);+ }+ return next;+ });+ };++ return (+ <Dialog open={open} onOpenChange={handleClose}>+ <DialogContent className="sm:max-w-md">+ {rawKey ? (+ <>+ <DialogHeader>+ <DialogTitle className="flex items-center gap-2">+ <Shield className="h-4 w-4 text-success" />+ {t("apiKeysSection.created.title")}+ </DialogTitle>+ <DialogDescription className="sr-only">+ {t("apiKeysSection.created.warning")}+ </DialogDescription>+ </DialogHeader>++ <div className="space-y-3">+ <div className="rounded-lg border border-border/50 bg-muted/30 dark:bg-surface-raised/30 p-3">+ <code className="text-xs font-mono text-foreground break-all select-all leading-relaxed">+ {rawKey}+ </code>+ </div>++ <Button variant="outline" size="sm" className="w-full" onClick={handleCopy}>+ {copied ? (+ <Check className="h-3.5 w-3.5 mr-1.5 text-success" />+ ) : (+ <Copy className="h-3.5 w-3.5 mr-1.5" />+ )}+ {copied+ ? t("apiKeysSection.created.copied")+ : t("apiKeysSection.created.copyButton")}+ </Button>++ <div className="flex items-start gap-2 rounded-lg border border-warning/20 bg-warning/5 dark:bg-warning/10 px-3 py-2">+ <AlertTriangle className="h-3.5 w-3.5 text-warning shrink-0 mt-0.5" />+ <p className="text-[11px] text-muted-foreground leading-relaxed">+ {t("apiKeysSection.created.warning")}+ </p>+ </div>+ </div>++ <DialogFooter>+ <Button variant="default" size="sm" onClick={() => handleClose(false)}>+ {t("apiKeysSection.created.done")}+ </Button>+ </DialogFooter>+ </>+ ) : (+ <>+ <DialogHeader>+ <DialogTitle>{t("apiKeysSection.create.title")}</DialogTitle>+ <DialogDescription className="sr-only">+ {t("apiKeysSection.description")}+ </DialogDescription>+ </DialogHeader>++ <div className="space-y-4">+ <div className="space-y-1.5">+ <label className="text-xs font-medium text-foreground">+ {t("apiKeysSection.create.nameLabel")}+ </label>+ <Input+ value={name}+ onChange={(e) => setName(e.target.value.slice(0, MAX_NAME_LENGTH))}+ placeholder={t("apiKeysSection.create.namePlaceholder")}+ className="h-9 text-xs"+ autoFocus+ onKeyDown={(e) => {+ if (e.key === "Enter" && name.trim() && scopes.size > 0) {+ handleSubmit();+ }+ }}+ />+ </div>++ <div className="space-y-1.5">+ <label className="text-xs font-medium text-foreground">+ {t("apiKeysSection.create.scopesLabel")}+ </label>+ <div className="space-y-1">+ {ALL_SCOPES.map((scope) => (+ <label+ key={scope}+ className="flex items-center gap-2.5 rounded-md px-2.5 py-1.5 cursor-pointer hover:bg-muted/50 dark:hover:bg-surface-raised/30 transition-colors"+ >+ <input+ type="checkbox"+ checked={scopes.has(scope)}+ onChange={() => toggleScope(scope)}+ className="h-3.5 w-3.5 rounded border-border accent-primary cursor-pointer"+ />+ <span className="text-xs text-foreground">+ {t(`apiKeysSection.scopes.${scope}`)}+ </span>+ </label>+ ))}+ </div>+ </div>+ </div>++ <DialogFooter>+ <Button variant="outline" size="sm" onClick={() => handleClose(false)}>+ {t("apiKeysSection.create.cancel")}+ </Button>+ <Button+ variant="default"+ size="sm"+ disabled={!name.trim() || scopes.size === 0 || isSubmitting}+ onClick={handleSubmit}+ >+ {isSubmitting ? (+ <span className="flex items-center gap-1.5">+ <span className="h-3 w-3 animate-spin rounded-full border-2 border-current border-t-transparent" />+ {t("apiKeysSection.create.submit")}+ </span>+ ) : (+ t("apiKeysSection.create.submit")+ )}+ </Button>+ </DialogFooter>+ </>+ )}+ </DialogContent>+ </Dialog>+ );+}diff --git a/src/components/SettingsModal.tsx b/src/components/SettingsModal.tsxindex 8bf26afc3..e57638af9 100644--- a/src/components/SettingsModal.tsx+++ b/src/components/SettingsModal.tsx@@ -8,6 +8,7 @@ import {Wrench,Keyboard,CreditCard,+ Key,Shield,MessageSquare,} from "lucide-react";@@ -51,6 +52,13 @@ export default function SettingsModal({ open, onOpenChange, initialSection }: Sedescription: t("settingsModal.sections.plansBilling.description"),group: t("settingsModal.groups.account"),},+ {+ id: "apiKeys",+ label: t("settingsModal.sections.apiKeys.label"),+ icon: Key,+ description: t("settingsModal.sections.apiKeys.description"),+ group: t("settingsModal.groups.account"),+ },{id: "general",label: t("settingsModal.sections.general.label"),diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsxindex 4a06bb1f9..3f6c225a3 100644--- a/src/components/SettingsPage.tsx+++ b/src/components/SettingsPage.tsx@@ -65,6 +65,7 @@ import { getDefaultHotkey, formatHotkeyLabel } from "../utils/hotkeys";import { ActivationModeSelector } from "./ui/ActivationModeSelector";import { Toggle } from "./ui/toggle";import DeveloperSection from "./DeveloperSection";+import ApiKeysSection from "./ApiKeysSection";import AgentModeSettings from "./settings/AgentModeSettings";import LanguageSelector from "./ui/LanguageSelector";import { Skeleton } from "./ui/skeleton";@@ -86,6 +87,7 @@ const formatAmount = (cents: number, currency: string) =>export type SettingsSectionType =| "account"| "plansBilling"+ | "apiKeys"| "general"| "hotkeys"| "transcription"@@ -2030,6 +2032,58 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPage</div>);+ case "apiKeys":+ return (+ <div className="space-y-5">+ {!NEON_AUTH_URL ? (+ <>+ <SectionHeader+ title={t("settingsPage.apiKeys.title")}+ description={t("settingsPage.account.notConfigured")}+ />+ <SettingsPanel>+ <SettingsPanelRow>+ <SettingsRow+ label={t("settingsPage.account.featuresDisabled")}+ description={t("settingsPage.account.featuresDisabledDescription")}+ >+ <Badge variant="warning">{t("settingsPage.account.disabled")}</Badge>+ </SettingsRow>+ </SettingsPanelRow>+ </SettingsPanel>+ </>+ ) : isLoaded && isSignedIn && user ? (+ <ApiKeysSection />+ ) : isLoaded ? (+ <>+ <SectionHeader title={t("settingsPage.apiKeys.title")} />+ <SettingsPanel>+ <SettingsPanelRow>+ <SettingsRow+ label={t("settingsPage.apiKeys.signInRequired")}+ description={t("settingsPage.apiKeys.signInRequiredDescription")}+ >+ <Badge variant="outline">{t("settingsPage.account.offline")}</Badge>+ </SettingsRow>+ </SettingsPanelRow>+ </SettingsPanel>+ </>+ ) : (+ <>+ <SectionHeader title={t("settingsPage.apiKeys.title")} />+ <SettingsPanel>+ <SettingsPanelRow>+ <div className="flex items-center justify-between">+ <Skeleton className="h-4 w-32" />+ <Skeleton className="h-5 w-16 rounded-full" />+ </div>+ </SettingsPanelRow>+ </SettingsPanel>+ </>+ )}+ </div>+ );+case "general":return (<div className="space-y-6">diff --git a/src/locales/de/translation.json b/src/locales/de/translation.jsonindex 9134726f4..e374a6d1b 100644--- a/src/locales/de/translation.json+++ b/src/locales/de/translation.json@@ -847,6 +847,10 @@"description": "Tarife, Nutzung & Abrechnung","label": "Tarife & Abrechnung"},+ "apiKeys": {+ "label": "API-Schlüssel",+ "description": "API-Zugriff verwalten"+ },"general": {"description": "Darstellung, Töne & Start","label": "Einstellungen"@@ -1076,6 +1080,11 @@"bulletPoints": "Hey {{agentName}}, wandle das in Stichpunkte um"}},+ "apiKeys": {+ "title": "API-Schlüssel",+ "signInRequired": "Anmeldung erforderlich",+ "signInRequiredDescription": "Melden Sie sich an, um Ihre API-Schlüssel zu verwalten."+ },"aiModels": {"customSetup": "Benutzerdefinierte Einrichtung","customSetupDescription": "Verwenden Sie Ihren eigenen Anbieter und API-Schlüssel.",@@ -2001,5 +2010,45 @@"title": "Berechtigungen erforderlich","description": "OpenWhispr benötigt einige Berechtigungen, um auf diesem Computer zu funktionieren.","continue": "Weiter"+ },+ "apiKeysSection": {+ "title": "API-Schlüssel",+ "description": "Erstellen Sie Schlüssel für den programmatischen Zugriff auf die OpenWhispr-API.",+ "empty": "Noch keine API-Schlüssel",+ "createButton": "API-Schlüssel erstellen",+ "create": {+ "title": "API-Schlüssel erstellen",+ "nameLabel": "Schlüsselname",+ "namePlaceholder": "z. B. Meine Integration",+ "scopesLabel": "Berechtigungen",+ "submit": "Erstellen",+ "cancel": "Abbrechen"+ },+ "created": {+ "title": "API-Schlüssel erstellt",+ "warning": "Kopieren Sie diesen Schlüssel jetzt. Er wird nicht erneut angezeigt.",+ "copied": "Kopiert!",+ "copyButton": "In die Zwischenablage kopieren",+ "done": "Fertig"+ },+ "scopes": {+ "notes:read": "Notizen lesen",+ "notes:write": "Notizen erstellen und bearbeiten",+ "transcriptions:read": "Transkriptionen lesen",+ "usage:read": "Nutzung anzeigen"+ },+ "revoke": {+ "button": "Widerrufen",+ "confirm": "Diesen Schlüssel widerrufen? Alle Integrationen, die ihn verwenden, funktionieren dann nicht mehr.",+ "success": "API-Schlüssel widerrufen"+ },+ "neverUsed": "Nie verwendet",+ "lastUsed": "Zuletzt verwendet {{time}}",+ "maxKeysReached": "Maximal {{max}} Schlüssel erlaubt",+ "errors": {+ "loadFailed": "API-Schlüssel konnten nicht geladen werden",+ "createFailed": "API-Schlüssel konnte nicht erstellt werden",+ "revokeFailed": "API-Schlüssel konnte nicht widerrufen werden"+ }}}diff --git a/src/locales/en/translation.json b/src/locales/en/translation.jsonindex ec47cd742..e6154e070 100644--- a/src/locales/en/translation.json+++ b/src/locales/en/translation.json@@ -647,6 +647,46 @@"title": "What gets logged"}},+ "apiKeysSection": {+ "title": "API Keys",+ "description": "Create keys to access the OpenWhispr API programmatically.",+ "empty": "No API keys yet",+ "createButton": "Create API Key",+ "create": {+ "title": "Create API Key",+ "nameLabel": "Key Name",+ "namePlaceholder": "e.g. My Integration",+ "scopesLabel": "Permissions",+ "submit": "Create",+ "cancel": "Cancel"+ },+ "created": {+ "title": "API Key Created",+ "warning": "Copy this key now. It won't be shown again.",+ "copied": "Copied!",+ "copyButton": "Copy to Clipboard",+ "done": "Done"+ },+ "scopes": {+ "notes:read": "Read notes",+ "notes:write": "Create & edit notes",+ "transcriptions:read": "Read transcriptions",+ "usage:read": "View usage"+ },+ "revoke": {+ "button": "Revoke",+ "confirm": "Revoke this key? Any integrations using it will stop working.",+ "success": "API key revoked"+ },+ "neverUsed": "Never used",+ "lastUsed": "Last used {{time}}",+ "maxKeysReached": "Maximum {{max}} keys allowed",+ "errors": {+ "loadFailed": "Failed to load API keys",+ "createFailed": "Failed to create API key",+ "revokeFailed": "Failed to revoke API key"+ }+ },"dictionarySuffix": "Dictionary Suffix","emailVerification": {"checkEmailDescription": "We sent a verification link to",@@ -895,6 +935,10 @@"description": "Plans, usage & billing","label": "Plans & Billing"},+ "apiKeys": {+ "label": "API Keys",+ "description": "Manage API access"+ },"general": {"description": "Appearance, sounds & startup","label": "Preferences"@@ -1124,6 +1168,11 @@"bulletPoints": "Hey {{agentName}}, convert this to bullet points"}},+ "apiKeys": {+ "title": "API Keys",+ "signInRequired": "Sign in required",+ "signInRequiredDescription": "Sign in to manage your API keys."+ },"aiModels": {"customSetup": "Custom Setup","customSetupDescription": "Use your own provider and API key.",diff --git a/src/locales/es/translation.json b/src/locales/es/translation.jsonindex 91f60ea1c..3ae0b2847 100644--- a/src/locales/es/translation.json+++ b/src/locales/es/translation.json@@ -599,6 +599,46 @@"title": "Qué se registra"}},+ "apiKeysSection": {+ "title": "Claves API",+ "description": "Crea claves para acceder a la API de OpenWhispr de forma programática.",+ "empty": "Aún no hay claves API",+ "createButton": "Crear clave API",+ "create": {+ "title": "Crear clave API",+ "nameLabel": "Nombre de la clave",+ "namePlaceholder": "ej. Mi Integración",+ "scopesLabel": "Permisos",+ "submit": "Crear",+ "cancel": "Cancelar"+ },+ "created": {+ "title": "Clave API creada",+ "warning": "Copia esta clave ahora. No se mostrará de nuevo.",+ "copied": "¡Copiado!",+ "copyButton": "Copiar al portapapeles",+ "done": "Listo"+ },+ "scopes": {+ "notes:read": "Leer notas",+ "notes:write": "Crear y editar notas",+ "transcriptions:read": "Leer transcripciones",+ "usage:read": "Ver uso"+ },+ "revoke": {+ "button": "Revocar",+ "confirm": "¿Revocar esta clave? Las integraciones que la usen dejarán de funcionar.",+ "success": "Clave API revocada"+ },+ "neverUsed": "Nunca usada",+ "lastUsed": "Último uso {{time}}",+ "maxKeysReached": "Máximo de {{max}} claves permitidas",+ "errors": {+ "loadFailed": "No se pudieron cargar las claves API",+ "createFailed": "No se pudo crear la clave API",+ "revokeFailed": "No se pudo revocar la clave API"+ }+ },"dictionarySuffix": "Sufijo del diccionario","emailVerification": {"checkEmailDescription": "Enviamos un enlace de verificación a",@@ -847,6 +887,10 @@"description": "Planes, uso y facturación","label": "Planes y facturación"},+ "apiKeys": {+ "label": "Claves API",+ "description": "Gestionar acceso API"+ },"general": {"description": "Apariencia, sonidos e inicio","label": "Preferencias"@@ -1076,6 +1120,11 @@"bulletPoints": "Hey {{agentName}}, convierte esto en viñetas"}},+ "apiKeys": {+ "title": "Claves de API",+ "signInRequired": "Inicio de sesión requerido",+ "signInRequiredDescription": "Inicia sesión para administrar tus claves de API."+ },"aiModels": {"customSetup": "Configuración personalizada","customSetupDescription": "Usa tu propio proveedor y clave API.",diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.jsonindex 36c6f02db..52ea888a6 100644--- a/src/locales/fr/translation.json+++ b/src/locales/fr/translation.json@@ -599,6 +599,46 @@"title": "Ce qui est enregistré"}},+ "apiKeysSection": {+ "title": "Clés API",+ "description": "Créez des clés pour accéder à l'API OpenWhispr de manière programmatique.",+ "empty": "Aucune clé API pour le moment",+ "createButton": "Créer une clé API",+ "create": {+ "title": "Créer une clé API",+ "nameLabel": "Nom de la clé",+ "namePlaceholder": "ex. Mon intégration",+ "scopesLabel": "Autorisations",+ "submit": "Créer",+ "cancel": "Annuler"+ },+ "created": {+ "title": "Clé API créée",+ "warning": "Copiez cette clé maintenant. Elle ne sera plus affichée.",+ "copied": "Copié !",+ "copyButton": "Copier dans le presse-papiers",+ "done": "Terminé"+ },+ "scopes": {+ "notes:read": "Lire les notes",+ "notes:write": "Créer et modifier les notes",+ "transcriptions:read": "Lire les transcriptions",+ "usage:read": "Voir l'utilisation"+ },+ "revoke": {+ "button": "Révoquer",+ "confirm": "Révoquer cette clé ? Les intégrations qui l'utilisent cesseront de fonctionner.",+ "success": "Clé API révoquée"+ },+ "neverUsed": "Jamais utilisée",+ "lastUsed": "Dernière utilisation {{time}}",+ "maxKeysReached": "Maximum de {{max}} clés autorisées",+ "errors": {+ "loadFailed": "Impossible de charger les clés API",+ "createFailed": "Impossible de créer la clé API",+ "revokeFailed": "Impossible de révoquer la clé API"+ }+ },"dictionarySuffix": "Suffixe du dictionnaire","emailVerification": {"checkEmailDescription": "Nous avons envoyé un lien de vérification à",@@ -847,6 +887,10 @@"description": "Forfaits, utilisation & facturation","label": "Forfaits & facturation"},+ "apiKeys": {+ "label": "Clés API",+ "description": "Gérer l'accès API"+ },"general": {"description": "Apparence, sons & démarrage","label": "Préférences"@@ -1076,6 +1120,11 @@"bulletPoints": "Hey {{agentName}}, convertis ça en liste à puces"}},+ "apiKeys": {+ "title": "Clés API",+ "signInRequired": "Connexion requise",+ "signInRequiredDescription": "Connectez-vous pour gérer vos clés API."+ },"aiModels": {"customSetup": "Configuration personnalisée","customSetupDescription": "Utilisez votre propre fournisseur et clé API.",diff --git a/src/locales/it/translation.json b/src/locales/it/translation.jsonindex 9b0d20064..2bdc03a28 100644--- a/src/locales/it/translation.json+++ b/src/locales/it/translation.json@@ -847,6 +847,10 @@"description": "Piani, utilizzo e fatturazione","label": "Piani e fatturazione"},+ "apiKeys": {+ "label": "Chiavi API",+ "description": "Gestisci accesso API"+ },"general": {"description": "Aspetto, suoni e avvio","label": "Preferenze"@@ -1076,6 +1080,11 @@"bulletPoints": "Hey {{agentName}}, converti questo in elenco puntato"}},+ "apiKeys": {+ "title": "Chiavi API",+ "signInRequired": "Accesso richiesto",+ "signInRequiredDescription": "Accedi per gestire le tue chiavi API."+ },"aiModels": {"customSetup": "Configurazione personalizzata","customSetupDescription": "Usa il tuo provider e la tua chiave API.",@@ -2001,5 +2010,45 @@"title": "Autorizzazioni necessarie","description": "OpenWhispr ha bisogno di alcune autorizzazioni per funzionare su questo computer.","continue": "Continua"+ },+ "apiKeysSection": {+ "title": "Chiavi API",+ "description": "Crea chiavi per accedere all'API di OpenWhispr in modo programmatico.",+ "empty": "Nessuna chiave API ancora",+ "createButton": "Crea chiave API",+ "create": {+ "title": "Crea chiave API",+ "nameLabel": "Nome della chiave",+ "namePlaceholder": "es. La mia integrazione",+ "scopesLabel": "Permessi",+ "submit": "Crea",+ "cancel": "Annulla"+ },+ "created": {+ "title": "Chiave API creata",+ "warning": "Copia questa chiave ora. Non verrà più mostrata.",+ "copied": "Copiato!",+ "copyButton": "Copia negli appunti",+ "done": "Fatto"+ },+ "scopes": {+ "notes:read": "Leggi note",+ "notes:write": "Crea e modifica note",+ "transcriptions:read": "Leggi trascrizioni",+ "usage:read": "Visualizza utilizzo"+ },+ "revoke": {+ "button": "Revoca",+ "confirm": "Revocare questa chiave? Le integrazioni che la utilizzano smetteranno di funzionare.",+ "success": "Chiave API revocata"+ },+ "neverUsed": "Mai utilizzata",+ "lastUsed": "Ultimo utilizzo {{time}}",+ "maxKeysReached": "Massimo {{max}} chiavi consentite",+ "errors": {+ "loadFailed": "Impossibile caricare le chiavi API",+ "createFailed": "Impossibile creare la chiave API",+ "revokeFailed": "Impossibile revocare la chiave API"+ }}}diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.jsonindex e05ed8811..afabb5dab 100644--- a/src/locales/ja/translation.json+++ b/src/locales/ja/translation.json@@ -847,6 +847,10 @@"description": "プラン、使用状況、請求","label": "プランと請求"},+ "apiKeys": {+ "description": "APIキーの管理",+ "label": "APIキー"+ },"general": {"description": "外観、サウンド、起動設定","label": "環境設定"@@ -1076,6 +1080,11 @@"bulletPoints": "Hey {{agentName}}、これを箇条書きに変換して"}},+ "apiKeys": {+ "title": "APIキー",+ "signInRequired": "サインインが必要です",+ "signInRequiredDescription": "APIキーを管理するにはサインインしてください。"+ },"aiModels": {"customSetup": "カスタム設定","customSetupDescription": "独自のプロバイダーと API キーを使用。",@@ -2001,5 +2010,45 @@"title": "権限が必要です","description": "OpenWhispr がこのコンピュータで動作するために、いくつかの権限が必要です。","continue": "続行"+ },+ "apiKeysSection": {+ "title": "APIキー",+ "description": "アカウントへのプログラムアクセス用のキーを管理",+ "empty": "APIキーはまだありません",+ "createButton": "キーを作成",+ "create": {+ "title": "APIキーを作成",+ "nameLabel": "キー名",+ "namePlaceholder": "例: マイインテグレーション",+ "scopesLabel": "権限",+ "submit": "作成",+ "cancel": "キャンセル"+ },+ "created": {+ "title": "キーが作成されました",+ "warning": "このキーを今すぐコピーしてください。再度表示されることはありません。",+ "copied": "コピー済み",+ "copyButton": "クリップボードにコピー",+ "done": "完了"+ },+ "scopes": {+ "notes:read": "ノートの読み取り",+ "notes:write": "ノートの作成と編集",+ "transcriptions:read": "文字起こしの読み取り",+ "usage:read": "使用状況の表示"+ },+ "revoke": {+ "button": "取り消し",+ "confirm": "このAPIキーを取り消しますか?このキーを使用しているインテグレーションは機能しなくなります。",+ "success": "APIキーが取り消されました"+ },+ "neverUsed": "未使用",+ "lastUsed": "{{time}}に使用",+ "maxKeysReached": "キーの上限({{max}}個)に達しました",+ "errors": {+ "loadFailed": "APIキーを読み込めませんでした",+ "createFailed": "APIキーを作成できませんでした",+ "revokeFailed": "APIキーを取り消せませんでした"+ }}}diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.jsonindex f032757a0..740b8881d 100644--- a/src/locales/pt/translation.json+++ b/src/locales/pt/translation.json@@ -819,6 +819,10 @@"description": "Planos, uso e cobrança","label": "Planos e cobrança"},+ "apiKeys": {+ "label": "Chaves API",+ "description": "Gerenciar acesso API"+ },"general": {"description": "Aparência, sons e inicialização","label": "Preferências"@@ -1048,6 +1052,11 @@"bulletPoints": "Hey {{agentName}}, converta isso em tópicos"}},+ "apiKeys": {+ "title": "Chaves de API",+ "signInRequired": "Login necessário",+ "signInRequiredDescription": "Faça login para gerenciar suas chaves de API."+ },"aiModels": {"customSetup": "Configuração personalizada","customSetupDescription": "Use seu próprio provedor e chave API.",@@ -2001,5 +2010,45 @@"title": "Permissões necessárias","description": "O OpenWhispr precisa de algumas permissões para funcionar neste computador.","continue": "Continuar"+ },+ "apiKeysSection": {+ "title": "Chaves API",+ "description": "Crie chaves para acessar a API do OpenWhispr programaticamente.",+ "empty": "Nenhuma chave API ainda",+ "createButton": "Criar chave API",+ "create": {+ "title": "Criar chave API",+ "nameLabel": "Nome da chave",+ "namePlaceholder": "ex. Minha Integração",+ "scopesLabel": "Permissões",+ "submit": "Criar",+ "cancel": "Cancelar"+ },+ "created": {+ "title": "Chave API criada",+ "warning": "Copie esta chave agora. Ela não será exibida novamente.",+ "copied": "Copiado!",+ "copyButton": "Copiar para a área de transferência",+ "done": "Concluído"+ },+ "scopes": {+ "notes:read": "Ler notas",+ "notes:write": "Criar e editar notas",+ "transcriptions:read": "Ler transcrições",+ "usage:read": "Ver uso"+ },+ "revoke": {+ "button": "Revogar",+ "confirm": "Revogar esta chave? As integrações que a utilizam deixarão de funcionar.",+ "success": "Chave API revogada"+ },+ "neverUsed": "Nunca usada",+ "lastUsed": "Último uso {{time}}",+ "maxKeysReached": "Máximo de {{max}} chaves permitidas",+ "errors": {+ "loadFailed": "Falha ao carregar as chaves API",+ "createFailed": "Falha ao criar a chave API",+ "revokeFailed": "Falha ao revogar a chave API"+ }}}diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.jsonindex 7d11631f9..43e311d9a 100644--- a/src/locales/ru/translation.json+++ b/src/locales/ru/translation.json@@ -847,6 +847,10 @@"description": "Тарифы, использование и оплата","label": "Тарифы и оплата"},+ "apiKeys": {+ "label": "API-ключи",+ "description": "Управление доступом к API"+ },"general": {"description": "Внешний вид, звуки и автозапуск","label": "Настройки"@@ -1076,6 +1080,11 @@"bulletPoints": "Hey {{agentName}}, преобразуй это в маркированный список"}},+ "apiKeys": {+ "title": "API-ключи",+ "signInRequired": "Требуется вход",+ "signInRequiredDescription": "Войдите, чтобы управлять API-ключами."+ },"aiModels": {"customSetup": "Пользовательская настройка","customSetupDescription": "Используйте собственного провайдера и API-ключ.",@@ -2001,5 +2010,45 @@"title": "Требуются разрешения","description": "OpenWhispr нужны некоторые разрешения для работы на этом компьютере.","continue": "Продолжить"+ },+ "apiKeysSection": {+ "title": "API-ключи",+ "description": "Создавайте ключи для программного доступа к API OpenWhispr.",+ "empty": "API-ключей пока нет",+ "createButton": "Создать API-ключ",+ "create": {+ "title": "Создать API-ключ",+ "nameLabel": "Название ключа",+ "namePlaceholder": "напр. Моя интеграция",+ "scopesLabel": "Разрешения",+ "submit": "Создать",+ "cancel": "Отмена"+ },+ "created": {+ "title": "API-ключ создан",+ "warning": "Скопируйте этот ключ сейчас. Он больше не будет показан.",+ "copied": "Скопировано!",+ "copyButton": "Скопировать в буфер обмена",+ "done": "Готово"+ },+ "scopes": {+ "notes:read": "Чтение заметок",+ "notes:write": "Создание и редактирование заметок",+ "transcriptions:read": "Чтение транскрипций",+ "usage:read": "Просмотр использования"+ },+ "revoke": {+ "button": "Отозвать",+ "confirm": "Отозвать этот ключ? Интеграции, использующие его, перестанут работать.",+ "success": "API-ключ отозван"+ },+ "neverUsed": "Не использовался",+ "lastUsed": "Последнее использование {{time}}",+ "maxKeysReached": "Максимум {{max}} ключей разрешено",+ "errors": {+ "loadFailed": "Не удалось загрузить API-ключи",+ "createFailed": "Не удалось создать API-ключ",+ "revokeFailed": "Не удалось отозвать API-ключ"+ }}}diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.jsonindex 188a5c885..70d40a041 100644--- a/src/locales/zh-CN/translation.json+++ b/src/locales/zh-CN/translation.json@@ -847,6 +847,10 @@"description": "套餐、用量与账单","label": "套餐与账单"},+ "apiKeys": {+ "label": "API 密钥",+ "description": "管理 API 访问"+ },"general": {"description": "外观、声音与启动","label": "偏好设置"@@ -1076,6 +1080,11 @@"bulletPoints": "Hey {{agentName}},把这个转换成要点列表"}},+ "apiKeys": {+ "title": "API 密钥",+ "signInRequired": "需要登录",+ "signInRequiredDescription": "登录以管理您的 API 密钥。"+ },"aiModels": {"customSetup": "自定义设置","customSetupDescription": "使用你自己的服务商和 API Key。",@@ -2001,5 +2010,45 @@"title": "需要权限","description": "OpenWhispr 需要一些权限才能在此电脑上正常运行。","continue": "继续"+ },+ "apiKeysSection": {+ "title": "API 密钥",+ "description": "创建密钥以编程方式访问 OpenWhispr API。",+ "empty": "暂无 API 密钥",+ "createButton": "创建 API 密钥",+ "create": {+ "title": "创建 API 密钥",+ "nameLabel": "密钥名称",+ "namePlaceholder": "例如:我的集成",+ "scopesLabel": "权限",+ "submit": "创建",+ "cancel": "取消"+ },+ "created": {+ "title": "API 密钥已创建",+ "warning": "请立即复制此密钥,它将不会再次显示。",+ "copied": "已复制!",+ "copyButton": "复制到剪贴板",+ "done": "完成"+ },+ "scopes": {+ "notes:read": "读取笔记",+ "notes:write": "创建和编辑笔记",+ "transcriptions:read": "读取转录",+ "usage:read": "查看使用情况"+ },+ "revoke": {+ "button": "撤销",+ "confirm": "撤销此密钥?使用它的集成将停止工作。",+ "success": "API 密钥已撤销"+ },+ "neverUsed": "从未使用",+ "lastUsed": "上次使用 {{time}}",+ "maxKeysReached": "最多允许 {{max}} 个密钥",+ "errors": {+ "loadFailed": "无法加载 API 密钥",+ "createFailed": "无法创建 API 密钥",+ "revokeFailed": "无法撤销 API 密钥"+ }}}diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.jsonindex 9fe0164ed..5f3a8b164 100644--- a/src/locales/zh-TW/translation.json+++ b/src/locales/zh-TW/translation.json@@ -847,6 +847,10 @@"description": "方案、用量與帳單","label": "方案與帳單"},+ "apiKeys": {+ "label": "API 金鑰",+ "description": "管理 API 存取"+ },"general": {"description": "外觀、音效與啟動","label": "偏好設定"@@ -1076,6 +1080,11 @@"bulletPoints": "Hey {{agentName}},將這個轉換成要點列表"}},+ "apiKeys": {+ "title": "API 金鑰",+ "signInRequired": "需要登入",+ "signInRequiredDescription": "登入以管理您的 API 金鑰。"+ },"aiModels": {"customSetup": "自訂設定","customSetupDescription": "使用你自己的供應商和 API Key。",@@ -2001,5 +2010,45 @@"title": "需要權限","description": "OpenWhispr 需要一些權限才能在此電腦上正常運作。","continue": "繼續"+ },+ "apiKeysSection": {+ "title": "API 金鑰",+ "description": "建立金鑰以程式化方式存取 OpenWhispr API。",+ "empty": "尚無 API 金鑰",+ "createButton": "建立 API 金鑰",+ "create": {+ "title": "建立 API 金鑰",+ "nameLabel": "金鑰名稱",+ "namePlaceholder": "例如:我的整合",+ "scopesLabel": "權限",+ "submit": "建立",+ "cancel": "取消"+ },+ "created": {+ "title": "API 金鑰已建立",+ "warning": "請立即複製此金鑰,它將不會再次顯示。",+ "copied": "已複製!",+ "copyButton": "複製到剪貼簿",+ "done": "完成"+ },+ "scopes": {+ "notes:read": "讀取筆記",+ "notes:write": "建立與編輯筆記",+ "transcriptions:read": "讀取轉錄",+ "usage:read": "檢視使用情況"+ },+ "revoke": {+ "button": "撤銷",+ "confirm": "撤銷此金鑰?使用它的整合將停止運作。",+ "success": "API 金鑰已撤銷"+ },+ "neverUsed": "從未使用",+ "lastUsed": "上次使用 {{time}}",+ "maxKeysReached": "最多允許 {{max}} 個金鑰",+ "errors": {+ "loadFailed": "無法載入 API 金鑰",+ "createFailed": "無法建立 API 金鑰",+ "revokeFailed": "無法撤銷 API 金鑰"+ }}}diff --git a/src/services/ApiKeysService.ts b/src/services/ApiKeysService.tsnew file mode 100644index 000000000..6375d4858--- /dev/null+++ b/src/services/ApiKeysService.ts@@ -0,0 +1,54 @@+import { OPENWHISPR_API_URL } from "../config/constants.js";++interface ApiKey {+ id: string;+ name: string;+ key_prefix: string;+ scopes: string[];+ last_used_at: string | null;+ expires_at: string | null;+ created_at: string;+}++interface CreateApiKeyResponse extends ApiKey {+ key: string;+}++async function listApiKeys(): Promise<{ keys: ApiKey[] }> {+ const res = await fetch(`${OPENWHISPR_API_URL}/api/api-keys/list`, {+ credentials: "include",+ });+ if (!res.ok) throw new Error(await res.text());+ return res.json() as Promise<{ keys: ApiKey[] }>;+}++async function createApiKey(name: string, scopes: string[]): Promise<CreateApiKeyResponse> {+ const res = await fetch(`${OPENWHISPR_API_URL}/api/api-keys/create`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ credentials: "include",+ body: JSON.stringify({ name, scopes }),+ });+ if (!res.ok) throw new Error(await res.text());+ return res.json() as Promise<CreateApiKeyResponse>;+}++async function revokeApiKey(id: string): Promise<{ revoked: true }> {+ const res = await fetch(`${OPENWHISPR_API_URL}/api/api-keys/revoke`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ credentials: "include",+ body: JSON.stringify({ id }),+ });+ if (!res.ok) throw new Error(await res.text());+ return res.json() as Promise<{ revoked: true }>;+}++export { listApiKeys, createApiKey, revokeApiKey };+export type { ApiKey, CreateApiKeyResponse };++export const ApiKeysService = {+ list: listApiKeys,+ create: createApiKey,+ revoke: revokeApiKey,+};