feat: add VK ID and passkey authentication

This commit is contained in:
nstarikov 2026-08-11 12:47:48 +03:00
parent 6574ed6213
commit 227132d15e
8 changed files with 704 additions and 8 deletions

View file

@ -13,9 +13,11 @@ import {
ExternalLink,
FilePenLine,
FileText,
Fingerprint,
ImagePlus,
Link2,
Loader2,
LogIn,
Radio,
RefreshCw,
Save,
@ -286,6 +288,217 @@ async function api<T>(path: string, init?: RequestInit): Promise<T> {
return response.json() as Promise<T>
}
type VkIdSdk = {
Config: { init: (config: Record<string, unknown>) => void }
ConfigResponseMode?: { Callback?: unknown }
ConfigSource?: { LOWCODE?: unknown }
OneTap: new () => { render: (options: Record<string, unknown>) => { on: (event: unknown, callback: (payload: any) => void) => unknown } }
Auth: { exchangeCode: (code: string, deviceId: string) => Promise<{ access_token: string }> }
WidgetEvents: { ERROR: unknown }
OneTapInternalEvents: { LOGIN_SUCCESS: unknown }
}
declare global {
interface Window {
VKIDSDK?: VkIdSdk
}
}
function base64UrlToBytes(value: string) {
const padded = value.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(value.length / 4) * 4, "=")
const binary = window.atob(padded)
return Uint8Array.from(binary, (character) => character.charCodeAt(0))
}
function bytesToBase64Url(value: ArrayBuffer | Uint8Array) {
const bytes = value instanceof Uint8Array ? value : new Uint8Array(value)
let binary = ""
bytes.forEach((byte) => { binary += String.fromCharCode(byte) })
return window.btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "")
}
function registrationOptionsForBrowser(options: any) {
return {
...options,
challenge: base64UrlToBytes(options.challenge),
user: { ...options.user, id: base64UrlToBytes(options.user.id) },
excludeCredentials: (options.excludeCredentials || []).map((item: any) => ({ ...item, id: base64UrlToBytes(item.id) })),
}
}
function authenticationOptionsForBrowser(options: any) {
return {
...options,
challenge: base64UrlToBytes(options.challenge),
allowCredentials: (options.allowCredentials || []).map((item: any) => ({ ...item, id: base64UrlToBytes(item.id) })),
}
}
function serializePublicKeyCredential(credential: PublicKeyCredential) {
const response = credential.response as AuthenticatorAssertionResponse | AuthenticatorAttestationResponse
const payload: Record<string, unknown> = {
id: credential.id,
rawId: bytesToBase64Url(credential.rawId),
type: credential.type,
}
if ("attestationObject" in response) {
payload.response = {
clientDataJSON: bytesToBase64Url(response.clientDataJSON),
attestationObject: bytesToBase64Url(response.attestationObject),
}
} else {
payload.response = {
clientDataJSON: bytesToBase64Url(response.clientDataJSON),
authenticatorData: bytesToBase64Url(response.authenticatorData),
signature: bytesToBase64Url(response.signature),
userHandle: response.userHandle ? bytesToBase64Url(response.userHandle) : null,
}
}
return payload
}
function loadVkIdSdk() {
if (window.VKIDSDK) return Promise.resolve(window.VKIDSDK)
return new Promise<VkIdSdk>((resolve, reject) => {
const existing = document.querySelector<HTMLScriptElement>('script[data-vk-id-sdk="true"]')
if (existing) {
existing.addEventListener("load", () => window.VKIDSDK ? resolve(window.VKIDSDK) : reject(new Error("VK ID SDK не загрузился")), { once: true })
existing.addEventListener("error", () => reject(new Error("Не удалось загрузить VK ID SDK")), { once: true })
return
}
const script = document.createElement("script")
script.dataset.vkIdSdk = "true"
script.src = "https://unpkg.com/@vkid/sdk@2.6.1/dist-sdk/umd/index.js"
script.onload = () => window.VKIDSDK ? resolve(window.VKIDSDK) : reject(new Error("VK ID SDK не загрузился"))
script.onerror = () => reject(new Error("Не удалось загрузить VK ID SDK"))
document.head.appendChild(script)
})
}
function AuthScreen({ hasPasskeys, onAuthenticated }: { hasPasskeys: boolean; onAuthenticated: () => void }) {
const [message, setMessage] = useState("")
const [busy, setBusy] = useState(false)
const [vkAuthenticated, setVkAuthenticated] = useState(false)
const vkContainerRef = useRef<HTMLDivElement | null>(null)
const loginInFlightRef = useRef(false)
const finishVkLogin = useCallback(async (accessToken: string) => {
if (loginInFlightRef.current) return
loginInFlightRef.current = true
setBusy(true)
try {
await api("/api/auth/vk", { method: "POST", body: JSON.stringify({ accessToken }) })
setVkAuthenticated(true)
setMessage("VK ID подтверждён. Можно продолжить или добавить вход по Face ID / Touch ID.")
} catch (error) {
setMessage(error instanceof Error ? error.message : "VK ID не подтвердил пользователя")
} finally {
loginInFlightRef.current = false
setBusy(false)
}
}, [onAuthenticated])
useEffect(() => {
let cancelled = false
const callback = new URLSearchParams(window.location.search)
const callbackCode = callback.get("code")
const callbackDeviceId = callback.get("device_id")
loadVkIdSdk().then((VKID) => {
if (cancelled) return
VKID.Config.init({
app: 54716062,
redirectUrl: `${window.location.origin}/auth/callback/vk`,
responseMode: VKID.ConfigResponseMode?.Callback,
source: VKID.ConfigSource?.LOWCODE,
scope: "",
})
const exchange = (code: string, deviceId: string) => VKID.Auth.exchangeCode(code, deviceId).then((tokens) => finishVkLogin(tokens.access_token))
if (callbackCode && callbackDeviceId) {
void exchange(callbackCode, callbackDeviceId).catch((error) => setMessage(String(error)))
window.history.replaceState({}, "", "/admin")
}
const oneTap = new VKID.OneTap()
const rendered = oneTap.render({ container: vkContainerRef.current, showAlternativeLogin: true })
rendered.on(VKID.OneTapInternalEvents.LOGIN_SUCCESS, (payload) => {
if (payload?.code && payload?.device_id) void exchange(payload.code, payload.device_id).catch((error) => setMessage(String(error)))
})
rendered.on(VKID.WidgetEvents.ERROR, (error) => setMessage(`Ошибка VK ID: ${JSON.stringify(error)}`))
}).catch((error) => setMessage(error instanceof Error ? error.message : String(error)))
return () => { cancelled = true }
}, [finishVkLogin])
async function loginWithPasskey() {
setBusy(true)
setMessage("")
try {
if (!window.PublicKeyCredential || !navigator.credentials) throw new Error("Passkey не поддерживается этим браузером")
const started = await api<{ challengeId: string; options: any }>("/api/auth/login/options", { method: "POST" })
const credential = await navigator.credentials.get({ publicKey: authenticationOptionsForBrowser(started.options) }) as PublicKeyCredential | null
if (!credential) throw new Error("Вход по passkey отменён")
await api("/api/auth/login/verify", { method: "POST", body: JSON.stringify({ challengeId: started.challengeId, credential: serializePublicKeyCredential(credential) }) })
onAuthenticated()
} catch (error) {
setMessage(error instanceof Error ? error.message : String(error))
} finally {
setBusy(false)
}
}
async function registerPasskey() {
if (!vkAuthenticated) {
setMessage("Сначала войдите через VK ID.")
return
}
setBusy(true)
try {
const started = await api<{ challengeId: string; options: any }>("/api/auth/register/options", { method: "POST" })
const credential = await navigator.credentials.create({ publicKey: registrationOptionsForBrowser(started.options) }) as PublicKeyCredential | null
if (!credential) throw new Error("Регистрация passkey отменена")
await api("/api/auth/register/verify", { method: "POST", body: JSON.stringify({ challengeId: started.challengeId, credential: serializePublicKeyCredential(credential) }) })
onAuthenticated()
} catch (error) {
setMessage(error instanceof Error ? error.message : String(error))
} finally {
setBusy(false)
}
}
return (
<main className="flex min-h-screen items-center justify-center bg-muted/35 p-4">
<section className="w-full max-w-md rounded-lg border bg-background p-6 shadow-lg">
<div className="mb-6 flex items-center gap-3">
<img alt="Логотип Дзен-ассистента" className="size-12 rounded-md" src="/favicon.png" />
<div><h1 className="text-xl font-semibold">Дзен-ассистент</h1><p className="text-sm text-muted-foreground">Вход в редакторскую панель</p></div>
</div>
{message ? <div className="mb-4 rounded-md border border-destructive/30 bg-destructive/10 p-3 text-sm text-destructive">{message}</div> : null}
<div ref={vkContainerRef} className="min-h-12" />
{hasPasskeys ? (
<Button className="mt-3 w-full" disabled={busy} onClick={loginWithPasskey}>
{busy ? <Loader2 className="animate-spin" data-icon="inline-start" /> : <Fingerprint data-icon="inline-start" />}
Войти по Face ID / Touch ID
</Button>
) : null}
{vkAuthenticated ? (
<>
<Button className="mt-3 w-full" disabled={busy} onClick={onAuthenticated} variant="outline">
Продолжить через VK ID
</Button>
<Button className="mt-3 w-full" disabled={busy} onClick={registerPasskey}>
<Fingerprint data-icon="inline-start" />
Добавить Face ID / Touch ID
</Button>
</>
) : null}
{!hasPasskeys ? <p className="mt-4 text-xs text-muted-foreground">После входа через VK ID можно будет добавить Face ID, Touch ID или Windows Hello.</p> : null}
<Button className="mt-4 w-full" variant="ghost" disabled={busy} onClick={registerPasskey}>
<LogIn data-icon="inline-start" />
Зарегистрировать это устройство после входа через VK ID
</Button>
</section>
</main>
)
}
function escapeHtml(value: string) {
return value
.replace(/&/g, "&amp;")
@ -729,6 +942,8 @@ function ArticlePlaceholder() {
}
export default function App() {
const [authState, setAuthState] = useState<"loading" | "unauthenticated" | "authenticated">("loading")
const [hasPasskeys, setHasPasskeys] = useState(false)
const [activeView, setActiveView] = useState<"dashboard" | "settings">("dashboard")
const [appSettings, setAppSettings] = useState<AppSettings>({ signatureHtml: "", llmInstructions: "" })
const [videos, setVideos] = useState<Video[]>([])
@ -767,6 +982,10 @@ export default function App() {
const articlesLoadingRef = useRef(false)
const articlesHasMoreRef = useRef(false)
const handleAuthenticated = useCallback(() => {
setAuthState("authenticated")
}, [])
const handleSettingsSaved = useCallback((next: AppSettings) => {
setAppSettings(next)
}, [])
@ -837,21 +1056,30 @@ export default function App() {
}
useEffect(() => {
refresh().catch((error) => {
setStatusMessage(`Ошибка загрузки: ${error.message}`)
})
api<AppSettings>("/api/settings").then(setAppSettings).catch(() => undefined)
api<{ authenticated: boolean; hasPasskeys: boolean }>("/api/auth/status")
.then((status) => {
setHasPasskeys(status.hasPasskeys)
setAuthState(status.authenticated ? "authenticated" : "unauthenticated")
if (status.authenticated) {
refresh().catch((error) => setStatusMessage(`Ошибка загрузки: ${error.message}`))
api<AppSettings>("/api/settings").then(setAppSettings).catch(() => undefined)
}
})
.catch((error) => {
setAuthState("unauthenticated")
setStatusMessage(`Ошибка проверки авторизации: ${error.message}`)
})
}, [])
useEffect(() => {
if (activeVideos.length === 0) return
if (authState !== "authenticated" || activeVideos.length === 0) return
const timer = window.setInterval(() => {
refresh().catch((error) => {
setStatusMessage(`Ошибка обновления: ${error.message}`)
})
}, 5000)
return () => window.clearInterval(timer)
}, [activeVideos.length])
}, [activeVideos.length, authState])
useEffect(() => {
videos.forEach((video) => {
@ -1428,6 +1656,10 @@ export default function App() {
}
}
if (authState !== "authenticated") {
return authState === "loading" ? <main className="flex min-h-screen items-center justify-center bg-muted/35 text-sm text-muted-foreground">Проверяю авторизацию...</main> : <AuthScreen hasPasskeys={hasPasskeys} onAuthenticated={handleAuthenticated} />
}
return (
<main className="min-h-screen bg-muted/35 editorial-studio">
<div className="mx-auto flex w-full max-w-[1920px] flex-col gap-6 p-4 sm:p-6">

286
dzen-assistant/app/auth.py Normal file
View file

@ -0,0 +1,286 @@
from __future__ import annotations
from base64 import urlsafe_b64encode
from datetime import datetime, timedelta, timezone
import hashlib
import json
import secrets
from typing import Any
from fastapi import HTTPException, Request, Response
from fastapi.responses import JSONResponse
from sqlalchemy import select
from sqlalchemy.orm import Session
from webauthn import (
base64url_to_bytes,
generate_authentication_options,
generate_registration_options,
options_to_json,
verify_authentication_response,
verify_registration_response,
)
from webauthn.helpers.structs import (
AuthenticatorSelectionCriteria,
PublicKeyCredentialDescriptor,
ResidentKeyRequirement,
UserVerificationRequirement,
)
import httpx
from app.config import Settings
from app.database import SessionLocal
from app.models import AuthChallenge, AuthSession, PasskeyCredential
SESSION_COOKIE = "dzen_session"
CHALLENGE_TTL_SECONDS = 300
ADMIN_USER_ID = b"dzen-assistant-admin"
def utc_now() -> datetime:
return datetime.now(timezone.utc)
def as_utc(value: datetime) -> datetime:
return value.replace(tzinfo=timezone.utc) if value.tzinfo is None else value
def b64(value: bytes) -> str:
return urlsafe_b64encode(value).rstrip(b"=").decode("ascii")
def token_hash(token: str) -> str:
return hashlib.sha256(token.encode("utf-8")).hexdigest()
def create_challenge(session: Session, kind: str, challenge: bytes) -> str:
token = secrets.token_urlsafe(32)
session.add(
AuthChallenge(
token_hash=token_hash(token),
challenge=b64(challenge),
kind=kind,
expires_at=utc_now() + timedelta(seconds=CHALLENGE_TTL_SECONDS),
)
)
session.commit()
return token
def consume_challenge(session: Session, token: str, kind: str) -> bytes:
record = session.scalar(
select(AuthChallenge).where(
AuthChallenge.token_hash == token_hash(token),
AuthChallenge.kind == kind,
)
)
if not record or as_utc(record.expires_at) <= utc_now():
if record:
session.delete(record)
session.commit()
raise HTTPException(status_code=422, detail="Срок действия запроса авторизации истёк.")
challenge = base64url_to_bytes(record.challenge)
session.delete(record)
session.commit()
return challenge
def session_cookie(response: Response, settings: Settings) -> None:
token = secrets.token_urlsafe(48)
with SessionLocal() as session:
session.add(
AuthSession(
token_hash=token_hash(token),
expires_at=utc_now() + timedelta(seconds=settings.auth_session_ttl_seconds),
)
)
session.commit()
response.set_cookie(
SESSION_COOKIE,
token,
max_age=settings.auth_session_ttl_seconds,
httponly=True,
secure=True,
samesite="lax",
path="/",
)
def clear_session(response: Response, request: Request) -> None:
token = request.cookies.get(SESSION_COOKIE)
if token:
with SessionLocal() as session:
record = session.scalar(select(AuthSession).where(AuthSession.token_hash == token_hash(token)))
if record:
session.delete(record)
session.commit()
response.delete_cookie(SESSION_COOKIE, path="/")
def has_valid_session(token: str | None) -> bool:
if not token:
return False
with SessionLocal() as session:
record = session.scalar(select(AuthSession).where(AuthSession.token_hash == token_hash(token)))
if not record:
return False
if as_utc(record.expires_at) <= utc_now():
session.delete(record)
session.commit()
return False
return True
def require_session(request: Request) -> None:
if not has_valid_session(request.cookies.get(SESSION_COOKIE)):
raise HTTPException(status_code=401, detail="Сначала войдите через VK ID.")
async def verify_vk_access_token(access_token: str, settings: Settings) -> None:
if not access_token.strip():
raise HTTPException(status_code=422, detail="VK ID не вернул access token.")
try:
async with httpx.AsyncClient(timeout=15) as client:
response = await client.get(
settings.vk_id_user_info_url,
headers={"Authorization": f"Bearer {access_token.strip()}"},
)
response.raise_for_status()
payload = response.json()
except (httpx.HTTPError, ValueError) as exc:
raise HTTPException(status_code=401, detail="Не удалось проверить VK ID.") from exc
user_id = payload.get("user_id") or payload.get("user", {}).get("user_id")
try:
valid_user_id = int(user_id) == settings.vk_id_allowed_user_id
except (TypeError, ValueError):
valid_user_id = False
if not valid_user_id:
raise HTTPException(status_code=403, detail="Этот VK ID не имеет доступа к Дзен-ассистенту.")
def credential_id_from_payload(credential: dict[str, Any]) -> bytes:
raw_id = credential.get("rawId") or credential.get("id")
if not isinstance(raw_id, str) or not raw_id:
raise HTTPException(status_code=422, detail="WebAuthn не вернул идентификатор устройства.")
try:
return base64url_to_bytes(raw_id)
except Exception as exc:
raise HTTPException(status_code=422, detail="Некорректный идентификатор passkey.") from exc
def registration_options(session: Session, settings: Settings) -> dict[str, Any]:
existing = [
PublicKeyCredentialDescriptor(id=base64url_to_bytes(item.credential_id))
for item in session.scalars(select(PasskeyCredential)).all()
]
options = generate_registration_options(
rp_id=settings.webauthn_rp_id,
rp_name=settings.webauthn_rp_name,
user_id=ADMIN_USER_ID,
user_name="admin@nstarikov.ru",
user_display_name="Администратор Дзен-ассистента",
exclude_credentials=existing,
authenticator_selection=AuthenticatorSelectionCriteria(
resident_key=ResidentKeyRequirement.PREFERRED,
user_verification=UserVerificationRequirement.REQUIRED,
),
)
token = create_challenge(session, "registration", options.challenge)
return {"challengeId": token, "options": json.loads(options_to_json(options))}
def verify_registration(
session: Session,
settings: Settings,
challenge_id: str,
credential: dict[str, Any],
) -> None:
challenge = consume_challenge(session, challenge_id, "registration")
try:
verified = verify_registration_response(
credential=credential,
expected_challenge=challenge,
expected_rp_id=settings.webauthn_rp_id,
expected_origin=settings.webauthn_origin,
require_user_verification=True,
)
except Exception as exc:
raise HTTPException(status_code=422, detail=f"Не удалось зарегистрировать устройство: {exc}") from exc
session.add(
PasskeyCredential(
credential_id=b64(verified.credential_id),
public_key=b64(verified.credential_public_key),
sign_count=verified.sign_count,
label="Устройство администратора",
)
)
session.commit()
def authentication_options(session: Session, settings: Settings) -> dict[str, Any]:
credentials = [
PublicKeyCredentialDescriptor(id=base64url_to_bytes(item.credential_id))
for item in session.scalars(select(PasskeyCredential)).all()
]
options = generate_authentication_options(
rp_id=settings.webauthn_rp_id,
allow_credentials=credentials,
user_verification=UserVerificationRequirement.REQUIRED,
)
token = create_challenge(session, "authentication", options.challenge)
return {"challengeId": token, "options": json.loads(options_to_json(options))}
def verify_authentication(
session: Session,
settings: Settings,
challenge_id: str,
credential: dict[str, Any],
) -> None:
challenge = consume_challenge(session, challenge_id, "authentication")
credential_id = credential_id_from_payload(credential)
record = session.scalar(select(PasskeyCredential).where(PasskeyCredential.credential_id == b64(credential_id)))
if not record:
raise HTTPException(status_code=401, detail="Это устройство не зарегистрировано.")
try:
verified = verify_authentication_response(
credential=credential,
expected_challenge=challenge,
expected_rp_id=settings.webauthn_rp_id,
expected_origin=settings.webauthn_origin,
credential_public_key=base64url_to_bytes(record.public_key),
credential_current_sign_count=record.sign_count,
require_user_verification=True,
)
except Exception as exc:
raise HTTPException(status_code=401, detail=f"Не удалось подтвердить passkey: {exc}") from exc
record.sign_count = verified.new_sign_count
record.last_used_at = utc_now()
session.commit()
def auth_status() -> bool:
return True
class AuthMiddleware:
def __init__(self, app):
self.app = app
async def __call__(self, scope, receive, send):
path = scope.get("path", "")
protected = path.startswith("/api/") and not path.startswith("/api/auth/")
if not protected:
await self.app(scope, receive, send)
return
headers = dict(scope.get("headers", []))
cookie_header = headers.get(b"cookie", b"").decode("latin-1")
token = next((part.strip().split("=", 1)[1] for part in cookie_header.split(";") if part.strip().startswith(f"{SESSION_COOKIE}=")), None)
if has_valid_session(token):
await self.app(scope, receive, send)
return
if scope["type"] == "websocket":
await send({"type": "websocket.close", "code": 4401})
return
response = JSONResponse({"detail": "Требуется вход по passkey."}, status_code=401)
await response(scope, receive, send)

View file

@ -18,6 +18,13 @@ class Settings(BaseSettings):
celery_result_backend: str = "redis://redis:6379/1"
admin_token: str = "change-me"
webauthn_rp_id: str = "dzen.nstarikov.ru"
webauthn_rp_name: str = "Дзен-ассистент"
webauthn_origin: str = "https://dzen.nstarikov.ru"
auth_session_ttl_seconds: int = 2592000
vk_id_app_id: int = 54716062
vk_id_allowed_user_id: int = 32018
vk_id_user_info_url: str = "https://id.vk.com/oauth2/user_info"
whisper_command: str = "/LLM/Whisper/whisper --model medium --language ru --output_format txt"
ytdlp_cookies_path: str = "/app/data/cookies.txt"
vk_api_token: str = ""

View file

@ -7,6 +7,7 @@ from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
from app.config import get_settings
from app.auth import AuthMiddleware
from app.database import init_db
from app.routes import router
@ -28,6 +29,7 @@ async def lifespan(_app: FastAPI):
app = FastAPI(title="dzen-assistant", version="0.1.0", lifespan=lifespan)
app.include_router(router)
app.add_middleware(AuthMiddleware)
settings = get_settings()
mimetypes.add_type("image/webp", ".webp")
@ -46,6 +48,7 @@ def favicon() -> FileResponse:
@app.get("/admin")
@app.get("/admin/{path:path}")
@app.get("/auth/callback/vk")
def admin_index() -> FileResponse:
return FileResponse(
admin_dist / "index.html",

View file

@ -29,6 +29,38 @@ class AppSetting(Base):
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
class PasskeyCredential(Base):
__tablename__ = "passkey_credentials"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
credential_id: Mapped[str] = mapped_column(String(512), unique=True, index=True)
public_key: Mapped[str] = mapped_column(Text)
sign_count: Mapped[int] = mapped_column(Integer, default=0)
label: Mapped[str] = mapped_column(String(160), default="Устройство")
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
last_used_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
class AuthChallenge(Base):
__tablename__ = "auth_challenges"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
token_hash: Mapped[str] = mapped_column(String(64), unique=True, index=True)
challenge: Mapped[str] = mapped_column(String(256))
kind: Mapped[str] = mapped_column(String(32))
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), index=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
class AuthSession(Base):
__tablename__ = "auth_sessions"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
token_hash: Mapped[str] = mapped_column(String(64), unique=True, index=True)
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), index=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
class Video(Base):
__tablename__ = "videos"
__table_args__ = (UniqueConstraint("source_id", "external_id", name="uq_videos_source_external"),)

View file

@ -9,19 +9,32 @@ from pathlib import Path
import random
import re
import subprocess
from typing import Any
from uuid import uuid4
from fastapi import APIRouter, Body, Depends, File, HTTPException, Query, UploadFile, WebSocket, WebSocketDisconnect
from fastapi import APIRouter, Body, Depends, File, HTTPException, Query, Request, UploadFile, WebSocket, WebSocketDisconnect
from fastapi.responses import HTMLResponse, RedirectResponse, Response
from pydantic import BaseModel
from sqlalchemy import func, select
from sqlalchemy.orm import Session
from app.config import Settings, get_settings
from app.auth import (
authentication_options,
clear_session,
has_valid_session,
registration_options,
require_session,
session_cookie,
verify_vk_access_token,
verify_authentication,
verify_registration,
SESSION_COOKIE,
)
from app.captions import strip_leading_duplicate_title
from app.chapters import chapter_to_payload, parse_video_chapters
from app.database import SessionLocal, get_session
from app.models import AppSetting, Article, Frame, Source, Video
from app.models import AppSetting, Article, Frame, PasskeyCredential, Source, Video
from app.quality import validate_article_content
from app.rss import article_url, build_feed_xml, render_article_html
from app.worker import best_thumbnail_url, parse_upload_date, process_video, scan_sources, ytdlp_base_args
@ -49,6 +62,15 @@ class ManualVideoIn(BaseModel):
url: str
class AuthCredentialIn(BaseModel):
challengeId: str
credential: dict[str, Any]
class VkAuthIn(BaseModel):
accessToken: str
class AppSettingsIn(BaseModel):
signatureHtml: str = ""
llmInstructions: str = ""
@ -107,6 +129,57 @@ def get_app_settings(session: Session = Depends(get_session)) -> dict[str, str]:
return app_settings_payload(session)
@router.get("/api/auth/status")
def auth_status(request: Request, session: Session = Depends(get_session)) -> dict[str, bool]:
return {
"authenticated": has_valid_session(request.cookies.get(SESSION_COOKIE)),
"hasPasskeys": session.scalar(select(func.count(PasskeyCredential.id))) > 0,
}
@router.post("/api/auth/register/options")
def passkey_registration_options(request: Request, session: Session = Depends(get_session), settings: Settings = Depends(get_settings)) -> dict:
# Passkeys can only be enrolled after the account has been authenticated via VK ID.
# The request object is intentionally checked in the verify endpoint as well.
require_session(request)
return registration_options(session, settings)
@router.post("/api/auth/register/verify")
def passkey_registration_verify(payload: AuthCredentialIn, request: Request, response: Response, session: Session = Depends(get_session), settings: Settings = Depends(get_settings)) -> dict[str, bool]:
require_session(request)
verify_registration(session, settings, payload.challengeId, payload.credential)
session_cookie(response, settings)
return {"authenticated": True}
@router.post("/api/auth/login/options")
def passkey_login_options(session: Session = Depends(get_session), settings: Settings = Depends(get_settings)) -> dict:
if session.scalar(select(func.count(PasskeyCredential.id))) == 0:
raise HTTPException(status_code=404, detail="Пока не зарегистрировано ни одного устройства.")
return authentication_options(session, settings)
@router.post("/api/auth/login/verify")
def passkey_login_verify(payload: AuthCredentialIn, response: Response, session: Session = Depends(get_session), settings: Settings = Depends(get_settings)) -> dict[str, bool]:
verify_authentication(session, settings, payload.challengeId, payload.credential)
session_cookie(response, settings)
return {"authenticated": True}
@router.post("/api/auth/vk")
async def vk_login(payload: VkAuthIn, response: Response, settings: Settings = Depends(get_settings)) -> dict[str, bool]:
await verify_vk_access_token(payload.accessToken, settings)
session_cookie(response, settings)
return {"authenticated": True}
@router.post("/api/auth/logout")
def passkey_logout(request: Request, response: Response) -> dict[str, bool]:
clear_session(response, request)
return {"authenticated": False}
@router.put("/api/settings")
def update_app_settings(payload: AppSettingsIn, session: Session = Depends(get_session)) -> dict[str, str]:
values = {

View file

@ -0,0 +1,62 @@
# Passkey Authentication Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Replace repeated Basic Auth prompts on `dzen.nstarikov.ru` with Face ID, Touch ID, Windows Hello, or another WebAuthn passkey while retaining a guarded emergency Basic Auth path.
**Architecture:** FastAPI will own authentication for `/admin` and `/api`: public WebAuthn challenge endpoints issue registration and authentication options, verification creates an HttpOnly session cookie, and a middleware protects all other admin/API routes. SQLite stores passkey credentials and sessions. Caddy will stop applying Basic Auth to the main host; the existing Basic Auth configuration remains available on a separate emergency host until passkey login is verified.
**Tech Stack:** FastAPI, SQLAlchemy/SQLite, `webauthn` Python package, browser WebAuthn API, React/Vite, Caddy.
---
### Task 1: Persist passkeys and sessions
**Files:**
- Modify: `requirements.txt`
- Modify: `app/models.py`
- Modify: `app/database.py`
- Modify: `app/config.py`
- [ ] Add `webauthn==3.0.0`, passkey credential/session models, and migration columns/tables.
- [ ] Add RP ID, RP name, session lifetime, and one-time bootstrap settings.
- [ ] Verify imports and SQLite table creation in the container.
### Task 2: Add FastAPI WebAuthn flows and protection
**Files:**
- Create: `app/auth.py`
- Modify: `app/main.py`
- Modify: `app/routes.py`
- [ ] Add registration options/verification and authentication options/verification using `generate_*_options`, `verify_*_response`, and JSON helpers from `webauthn`.
- [ ] Set and clear Secure, HttpOnly, SameSite=Lax session cookies.
- [ ] Permit only auth bootstrap/challenge/verify/health without a session; require a session for `/admin`, `/api`, and logs WebSockets.
- [ ] Keep first-device registration guarded by the existing Basic Auth during migration.
### Task 3: Add passkey UI
**Files:**
- Modify: `admin/src/App.tsx`
- Modify: `admin/src/index.css`
- [ ] Show a compact login screen when the API returns `401`.
- [ ] Add «Войти по Face ID / Touch ID» and «Зарегистрировать это устройство» actions using `navigator.credentials`.
- [ ] Add logout and clear error states; preserve the existing dashboard after session restoration.
- [ ] Keep the UI usable in standalone iPhone PWA and desktop browsers.
### Task 4: Update Caddy and verify migration
**Files:**
- Modify: `Caddyfile.server`
- Modify: `Caddyfile.snippet` if needed
- [ ] Remove Basic Auth from the main `dzen.nstarikov.ru` route while keeping an emergency host/path protected by Basic Auth.
- [ ] Validate Caddy configuration, deploy API/admin/Caddy changes, and verify HTTPS origin and cookie behavior.
- [ ] Test registration and login on iPhone Safari/PWA and a desktop platform authenticator.
### Task 5: Regression checks
- [ ] Run `python3 -m py_compile app/*.py` and `npm --prefix admin run build`.
- [ ] Verify unauthenticated API returns `401`, authenticated API returns `200`, `/feed` remains public, and WebSocket logs accept the session cookie.
- [ ] Verify the emergency Basic Auth path remains reachable before removing any old credential mechanism.

View file

@ -10,3 +10,4 @@ python-multipart==0.0.20
requests==2.32.5
SQLAlchemy==2.0.41
uvicorn[standard]==0.34.2
webauthn==3.0.0