Skip to content

armgit / mimik

Public Imported from GitHub
0

🎬 A browser extension and desktop app that turns your clicks into step-by-step guides with annotated screenshots 📖

feat(settings): verify the AI API key when settings are saved

Luis Ortiz4d04849364a0
diff --git a/src/core/capture/ai/__tests__/validate.test.ts b/src/core/capture/ai/__tests__/validate.test.ts
new file mode 100644
index 0000000..fbf7867
--- /dev/null
+++ b/src/core/capture/ai/__tests__/validate.test.ts
@@ -0,0 +1,53 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { validateApiKey } from '../validate';
+
+const fetchMock = vi.fn();
+vi.stubGlobal('fetch', fetchMock);
+
+describe('validateApiKey', () => {
+ beforeEach(() => {
+ fetchMock.mockReset();
+ });
+
+ it('accepts a key the provider returns 200 for', async () => {
+ fetchMock.mockResolvedValue({ ok: true, status: 200 });
+ expect(await validateApiKey('openai', 'sk-good')).toEqual({ valid: true });
+ });
+
+ it('reports a 401 as rejected, not as a network problem', async () => {
+ fetchMock.mockResolvedValue({ ok: false, status: 401 });
+ expect(await validateApiKey('openai', 'sk-bad')).toEqual({ valid: false, reason: 'rejected' });
+ });
+
+ it('reports a 403 as rejected', async () => {
+ fetchMock.mockResolvedValue({ ok: false, status: 403 });
+ expect(await validateApiKey('anthropic', 'bad')).toEqual({ valid: false, reason: 'rejected' });
+ });
+
+ it('does not blame the key when the request never completes', async () => {
+ fetchMock.mockRejectedValue(new Error('offline'));
+ expect(await validateApiKey('openai', 'sk-good')).toEqual({ valid: false, reason: 'network' });
+ });
+
+ it('does not blame the key on a provider outage', async () => {
+ fetchMock.mockResolvedValue({ ok: false, status: 500 });
+ expect(await validateApiKey('openai', 'sk-good')).toEqual({ valid: false, reason: 'network' });
+ });
+
+ it('sends the anthropic browser-access header so the request is not blocked by CORS', async () => {
+ fetchMock.mockResolvedValue({ ok: true, status: 200 });
+ await validateApiKey('anthropic', 'ant-key');
+ const [url, init] = fetchMock.mock.calls[0];
+ expect(url).toBe('https://api.anthropic.com/v1/models');
+ expect(init.headers['x-api-key']).toBe('ant-key');
+ expect(init.headers['anthropic-dangerous-direct-browser-access']).toBe('true');
+ });
+
+ it('sends a bearer token for openai', async () => {
+ fetchMock.mockResolvedValue({ ok: true, status: 200 });
+ await validateApiKey('openai', 'sk-key');
+ const [url, init] = fetchMock.mock.calls[0];
+ expect(url).toBe('https://api.openai.com/v1/models');
+ expect(init.headers.Authorization).toBe('Bearer sk-key');
+ });
+});
diff --git a/src/core/capture/ai/validate.ts b/src/core/capture/ai/validate.ts
new file mode 100644
index 0000000..c1dc49d
--- /dev/null
+++ b/src/core/capture/ai/validate.ts
@@ -0,0 +1,31 @@
+import { logger } from '@/lib/logger';
+
+export type KeyValidation = { valid: true } | { valid: false; reason: 'rejected' | 'network' };
+
+const ENDPOINTS: Record<string, { url: string; headers: (key: string) => Record<string, string> }> = {
+ openai: {
+ url: 'https://api.openai.com/v1/models',
+ headers: (key) => ({ Authorization: `Bearer ${key}` }),
+ },
+ anthropic: {
+ url: 'https://api.anthropic.com/v1/models',
+ headers: (key) => ({
+ 'x-api-key': key,
+ 'anthropic-version': '2023-06-01',
+ 'anthropic-dangerous-direct-browser-access': 'true',
+ }),
+ },
+};
+
+export async function validateApiKey(provider: string, apiKey: string): Promise<KeyValidation> {
+ const endpoint = ENDPOINTS[provider] ?? ENDPOINTS.openai;
+ try {
+ const res = await fetch(endpoint.url, { headers: endpoint.headers(apiKey) });
+ if (res.ok) return { valid: true };
+ if (res.status === 401 || res.status === 403) return { valid: false, reason: 'rejected' };
+ return { valid: false, reason: 'network' };
+ } catch (err) {
+ logger.error('API key validation request failed', err);
+ return { valid: false, reason: 'network' };
+ }
+}
diff --git a/src/entrypoints/background/index.ts b/src/entrypoints/background/index.ts
index 8849ff2..358968d 100644
--- a/src/entrypoints/background/index.ts
+++ b/src/entrypoints/background/index.ts
@@ -1,4 +1,5 @@
import { browser, defineBackground } from '#imports';
+import { validateApiKey } from '@/core/capture/ai/validate';
import { stepRequiresManual } from '@/core/guideme/manual';
import { advanceSession, cancelSession, completeSession, getSession, startSession } from '@/core/guideme/session';
import { createGuide, getScreenshotsForSteps, getStepsForGuide } from '@/core/guides/service';
@@ -131,6 +132,8 @@ export default defineBackground(() => {
onMessage('generateGuideDescription', ({ data }) => generateDescriptionOnDemand(data.guideId));
+ onMessage('validateApiKey', ({ data }) => validateApiKey(data.provider, data.apiKey));
+
onMessage('captureStep', async ({ data }) => {
await waitUntilReady();
return handleCaptureStep(data);
diff --git a/src/lib/messaging.ts b/src/lib/messaging.ts
index e0ca9c1..7d48002 100644
--- a/src/lib/messaging.ts
+++ b/src/lib/messaging.ts
@@ -92,6 +92,16 @@ export interface GenerateGuideDescriptionResponse {
error?: GuideDescriptionError;
}
+export interface ValidateApiKeyData {
+ provider: string;
+ apiKey: string;
+}
+
+export interface ValidateApiKeyResponse {
+ valid: boolean;
+ reason?: 'rejected' | 'network';
+}
+
export interface EnterBlurModeResponse {
entered: boolean;
}
@@ -114,6 +124,7 @@ interface MimikProtocol {
enterBlurMode(): EnterBlurModeResponse;
exitBlurMode(): ExitBlurModeResponse;
generateGuideDescription(data: GenerateGuideDescriptionData): GenerateGuideDescriptionResponse;
+ validateApiKey(data: ValidateApiKeyData): ValidateApiKeyResponse;
}
export const { sendMessage, onMessage } = defineExtensionMessaging<MimikProtocol>();
diff --git a/src/locales/en.yml b/src/locales/en.yml
index 8bb1909..3242fd7 100644
--- a/src/locales/en.yml
+++ b/src/locales/en.yml
@@ -101,6 +101,9 @@ settings:
attributionHint: "In the footer of every export"
saveSettings: Save Settings
saved: Saved
+ validatingKey: "Checking key\u2026"
+ keyValid: API key verified.
+ keyInvalid: That API key was rejected. Check it and try again.
smartBlur: Smart Blur
privacyNotice: Your API key is stored locally and only sent to the selected AI provider. No data leaves your browser otherwise.
bugReport: "Found a bug? Report it on GitHub"
@@ -206,6 +209,7 @@ history:
descriptionErrorNoSteps: This guide has no described steps to summarise.
descriptionErrorFailed: Could not generate a description. Try again.
descriptionErrorSaveFailed: Generated the description but could not save it. Try again.
+ writingStepDescription: "Writing description\u2026"
emptyGuide:
title: This guide is empty
diff --git a/src/locales/es.yml b/src/locales/es.yml
index 207b84c..50efd3b 100644
--- a/src/locales/es.yml
+++ b/src/locales/es.yml
@@ -101,6 +101,9 @@ settings:
attributionHint: "En el pie de cada exportación"
saveSettings: Guardar ajustes
saved: Guardado
+ validatingKey: "Comprobando clave\u2026"
+ keyValid: Clave de API verificada.
+ keyInvalid: Esa clave de API fue rechazada. Compru\xE9bala e int\xE9ntalo de nuevo.
smartBlur: Desenfoque inteligente
privacyNotice: Tu clave API se guarda en tu navegador y solo se envía al proveedor de IA que elijas. Nada más sale de aquí.
bugReport: "¿Encontraste un bug? Repórtalo en GitHub"
@@ -206,6 +209,7 @@ history:
descriptionErrorNoSteps: Esta guía no tiene pasos descritos que resumir.
descriptionErrorFailed: No se pudo generar una descripción. Inténtalo de nuevo.
descriptionErrorSaveFailed: Se generó la descripción pero no se pudo guardar. Inténtalo de nuevo.
+ writingStepDescription: "Escribiendo descripci\xF3n\u2026"
emptyGuide:
title: Esta guía está vacía
diff --git a/src/locales/fr.yml b/src/locales/fr.yml
index d1de4ce..f51af43 100644
--- a/src/locales/fr.yml
+++ b/src/locales/fr.yml
@@ -101,6 +101,9 @@ settings:
attributionHint: "Dans le pied de chaque export"
saveSettings: "Enregistrer"
saved: "Enregistré"
+ validatingKey: "V\xE9rification de la cl\xE9\u2026"
+ keyValid: Cl\xE9 API v\xE9rifi\xE9e.
+ keyInvalid: Cette cl\xE9 API a \xE9t\xE9 refus\xE9e. V\xE9rifiez-la et r\xE9essayez.
smartBlur: Flou intelligent
privacyNotice: "Votre clé API reste dans votre navigateur et n'est envoyée qu'au fournisseur IA choisi. Rien d'autre ne sort d'ici."
bugReport: "Un bug ? Signalez-le sur GitHub"
@@ -206,6 +209,7 @@ history:
descriptionErrorNoSteps: "Ce guide n'a aucune étape décrite à résumer."
descriptionErrorFailed: "Impossible de générer une description. Réessayez."
descriptionErrorSaveFailed: "Description générée mais impossible de l'enregistrer. Réessayez."
+ writingStepDescription: "R\xE9daction de la description\u2026"
emptyGuide:
title: Ce guide est vide
diff --git a/src/locales/pt-BR.yml b/src/locales/pt-BR.yml
index b531ddf..9d0882d 100644
--- a/src/locales/pt-BR.yml
+++ b/src/locales/pt-BR.yml
@@ -101,6 +101,9 @@ settings:
attributionHint: "No rodapé de cada exportação"
saveSettings: Salvar ajustes
saved: Salvo
+ validatingKey: "Verificando chave\u2026"
+ keyValid: Chave de API verificada.
+ keyInvalid: Essa chave de API foi recusada. Verifique-a e tente novamente.
smartBlur: Desfoque inteligente
privacyNotice: Sua chave API fica salva no navegador e só é enviada pro provedor de IA que você escolher. Nada mais sai daqui.
bugReport: "Achou um bug? Reporta no GitHub"
@@ -206,6 +209,7 @@ history:
descriptionErrorNoSteps: Este guia não tem etapas descritas para resumir.
descriptionErrorFailed: Não foi possível gerar uma descrição. Tente novamente.
descriptionErrorSaveFailed: A descrição foi gerada mas não foi possível salvá-la. Tente novamente.
+ writingStepDescription: "Escrevendo descri\xE7\xE3o\u2026"
emptyGuide:
title: Esse guia tá vazio
diff --git a/src/ui/shared/SettingsView.tsx b/src/ui/shared/SettingsView.tsx
index 431214c..e97b72f 100644
--- a/src/ui/shared/SettingsView.tsx
+++ b/src/ui/shared/SettingsView.tsx
@@ -21,6 +21,7 @@ import { AI_LANGUAGES, type AILanguageCode } from '@/core/capture/ai/prompts';
import { type BrandLogo, defaultFooterLine, makeBrandLogo } from '@/core/export/branding';
import { DEFAULT_TARGET_COLOR, TARGET_COLORS } from '@/core/screenshot/types';
import { localStorage } from '@/lib/browser-api';
+import { sendMessage } from '@/lib/messaging';
import { Button } from '@/ui/components/ui/button';
import { Input } from '@/ui/components/ui/input';
import { Popover, PopoverContent, PopoverTrigger } from '@/ui/components/ui/popover';
@@ -42,6 +43,7 @@ export default function SettingsView({ onBack }: SettingsViewProps) {
const [model, setModel] = useState(AI_PROVIDERS.openai.defaultModel);
const [apiKey, setApiKey] = useState('');
const [saved, setSaved] = useState(false);
+ const [keyStatus, setKeyStatus] = useState<'checking' | 'valid' | 'rejected' | null>(null);
const [aiLanguage, setAiLanguage] = useState<AILanguageCode>('en');
const [targetColor, setTargetColor] = useState<string>(DEFAULT_TARGET_COLOR);
const [brandLogo, setBrandLogo] = useState<BrandLogo | null>(null);
@@ -108,6 +110,18 @@ export default function SettingsView({ onBack }: SettingsViewProps) {
});
setSaved(true);
setTimeout(() => setSaved(false), 2000);
+
+ if (!apiKey) {
+ setKeyStatus(null);
+ return;
+ }
+ setKeyStatus('checking');
+ try {
+ const result = await sendMessage('validateApiKey', { provider, apiKey });
+ setKeyStatus(result.valid ? 'valid' : result.reason === 'rejected' ? 'rejected' : null);
+ } catch {
+ setKeyStatus(null);
+ }
};
const providerConfig = AI_PROVIDERS[provider];
@@ -187,6 +201,18 @@ export default function SettingsView({ onBack }: SettingsViewProps) {
placeholder="sk-..."
className="h-8 text-[12px] rounded-lg border-border"
/>
+ {keyStatus === 'checking' && (
+ <p className="mt-1 text-[11px] text-muted-foreground">{i18n.t('settings.validatingKey')}</p>
+ )}
+ {keyStatus === 'valid' && (
+ <p className="mt-1 text-[11px] flex items-center gap-1" style={{ color: 'var(--color-success)' }}>
+ <Check size={11} />
+ {i18n.t('settings.keyValid')}
+ </p>
+ )}
+ {keyStatus === 'rejected' && (
+ <p className="mt-1 text-[11px] text-destructive">{i18n.t('settings.keyInvalid')}</p>
+ )}
</div>
<div>