Normalize copied API keys and show explicit setup validation errors

This commit is contained in:
Vickenty Zherebov 2026-10-20 13:17:02 +03:00
parent a44d45f431
commit 8739a521bf
4 changed files with 43 additions and 11 deletions

View file

@ -2,4 +2,4 @@
from __future__ import annotations
__version__ = "0.3.0b7"
__version__ = "0.3.0b8"

View file

@ -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

View file

@ -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(

View file

@ -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"