From 8739a521bf4873795ac20c6e2844b6970376b4cc Mon Sep 17 00:00:00 2001 From: Vickenty Zherebov Date: Tue, 20 Oct 2026 13:17:02 +0300 Subject: [PATCH] Normalize copied API keys and show explicit setup validation errors --- src/voice_dictation/__init__.py | 2 +- .../infrastructure/credentials.py | 28 +++++++++++++++---- src/voice_dictation/ui/setup_wizard.py | 9 +++--- tests/unit/test_credentials.py | 15 ++++++++++ 4 files changed, 43 insertions(+), 11 deletions(-) diff --git a/src/voice_dictation/__init__.py b/src/voice_dictation/__init__.py index df57900..70df26b 100644 --- a/src/voice_dictation/__init__.py +++ b/src/voice_dictation/__init__.py @@ -2,4 +2,4 @@ from __future__ import annotations -__version__ = "0.3.0b7" +__version__ = "0.3.0b8" diff --git a/src/voice_dictation/infrastructure/credentials.py b/src/voice_dictation/infrastructure/credentials.py index 3e7dd4d..a4ac8d9 100644 --- a/src/voice_dictation/infrastructure/credentials.py +++ b/src/voice_dictation/infrastructure/credentials.py @@ -4,6 +4,7 @@ from __future__ import annotations import json import os +import re import tempfile from io import StringIO from pathlib import Path @@ -23,16 +24,31 @@ def read_api_key(root: Path) -> str: def normalize_api_key(value: str) -> str: """Accept a key or one OPENAI_API_KEY assignment pasted from dotenv.""" - candidate = value.strip() - if candidate.startswith(("OPENAI_API_KEY=", "OPENAI_API_KEY =", "export OPENAI_API_KEY=")): + candidate = value.strip().lstrip("\ufeff") + assignment = re.match(r"^(?:export\s+)?OPENAI_API_KEY\s*=", candidate) + if assignment: + candidate = "OPENAI_API_KEY=" + candidate[assignment.end() :] parsed = dotenv_values(stream=StringIO(candidate), interpolate=False) if set(parsed) != {"OPENAI_API_KEY"}: - raise ValueError("Вставьте только строку OPENAI_API_KEY или значение ключа") + raise ValueError("Скопировано несколько настроек. Нужна только строка OPENAI_API_KEY.") candidate = (parsed.get("OPENAI_API_KEY") or "").strip() - elif len(candidate) >= 2 and candidate[0] == candidate[-1] and candidate[0] in "\"'": + quote_pairs = {'"': '"', "'": "'", "“": "”", "«": "»"} + if len(candidate) >= 2 and quote_pairs.get(candidate[0]) == candidate[-1]: candidate = candidate[1:-1].strip() - if not candidate or any(char.isspace() for char in candidate) or "=" in candidate: - raise ValueError("Введите ключ без пробелов и переносов строк") + if not candidate: + raise ValueError("Поле ключа пустое. Вставьте значение OPENAI_API_KEY из .env.") + # Long keys are sometimes copied with visual line wrapping or invisible separators. + compact = "".join( + char for char in candidate if not char.isspace() and char not in "\u200b\ufeff" + ) + if compact.startswith("sk-") and re.fullmatch(r"[A-Za-z0-9_-]+", compact): + candidate = compact + if any(char.isspace() for char in candidate): + raise ValueError( + "В ключе остались пробелы или лишние строки. Скопируйте только значение после =." + ) + if "=" in candidate: + raise ValueError("Не удалось разобрать строку. Ожидается OPENAI_API_KEY=значение.") return candidate diff --git a/src/voice_dictation/ui/setup_wizard.py b/src/voice_dictation/ui/setup_wizard.py index c6bb977..c600050 100644 --- a/src/voice_dictation/ui/setup_wizard.py +++ b/src/voice_dictation/ui/setup_wizard.py @@ -5,6 +5,7 @@ from __future__ import annotations import subprocess import sys from pathlib import Path +from tkinter import messagebox import customtkinter as ctk @@ -123,10 +124,10 @@ def run_setup(root: Path, store: ConfigStore, *, smoke_test: bool = False) -> bo try: if key.get().strip(): save_api_key(root, key.get()) - except ValueError: - message.configure( - text="Вставьте значение ключа или одну строку OPENAI_API_KEY=… из .env." - ) + except ValueError as exc: + message.configure(text=str(exc)) + messagebox.showerror("Ключ не сохранён", str(exc), parent=window) + key.focus_set() return except OSError: message.configure( diff --git a/tests/unit/test_credentials.py b/tests/unit/test_credentials.py index b33022e..5f40918 100644 --- a/tests/unit/test_credentials.py +++ b/tests/unit/test_credentials.py @@ -53,3 +53,18 @@ def test_multiple_env_values_rejected(tmp_path: Path) -> None: with pytest.raises(ValueError): save_api_key(tmp_path, "OPENAI_API_KEY=sk-test\nOTHER_KEY=test") assert not (tmp_path / "credentials.json").exists() + + +@pytest.mark.parametrize( + "value", + [ + "OPENAI_API_KEY\t=sk-test-not-real", + "export OPENAI_API_KEY = sk-test-not-real", + "sk-test-\nnot-real", + "“sk-test-not-real”", + "sk-test-\u200bnot-real", + ], +) +def test_copy_formatting_is_normalized(tmp_path: Path, value: str) -> None: + save_api_key(tmp_path, value) + assert read_api_key(tmp_path) == "sk-test-not-real"