"use client"; import { useEffect, useRef, useState } from "react"; import { QrCode, Smartphone } from "lucide-react"; import { Button } from "@/components/ui/button"; type Phase = { at: "idle" } | { at: "qr"; qr: string; deeplink: string; status: string } | { at: "done" } | { at: "error"; message: string }; const STATUS: Record = { pending: "Отсканируйте QR в eGov Mobile", scanned: "QR отсканирован — подпишите в eGov Mobile", completed: "Подписано, входим…", }; /** * eGov QR (PEP-65): shows the relay's QR and a deep link for the same phone, polls the flow and * finishes it. `login` signs in; `link` binds the IIN to the current account (Settings). */ export function EgovSign({ purpose, next, label }: { purpose: "login" | "link"; next?: string; label: string }) { const [phase, setPhase] = useState({ at: "idle" }); const alive = useRef(true); // Set on mount too: StrictMode (dev) mounts, unmounts and mounts again. useEffect(() => { alive.current = true; return () => void (alive.current = false); }, []); const fail = (message: string) => alive.current && setPhase({ at: "error", message }); async function start() { const r = await fetch("/auth/egov/start", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ purpose }) }); const body = (await r.json()) as { qr?: string; deeplink?: string; error?: string }; if (!r.ok || !body.qr) return fail(body.error ?? "Не удалось создать QR"); setPhase({ at: "qr", qr: body.qr, deeplink: body.deeplink ?? "", status: "pending" }); for (;;) { await new Promise((res) => setTimeout(res, 2000)); const s = (await (await fetch("/auth/egov/status", { cache: "no-store" })).json().catch(() => ({}))) as { status?: string; error?: string }; if (!alive.current) return; if (s.error) return fail(s.error); if (s.status === "expired") return fail("QR-код истёк — начните заново"); if (s.status === "rejected") return fail("Подписание отменено в eGov Mobile"); setPhase((p) => (p.at === "qr" ? { ...p, status: s.status ?? p.status } : p)); if (s.status === "completed") break; } const c = await fetch("/auth/egov/complete", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ next }) }); const done = (await c.json().catch(() => ({}))) as { redirect?: string; error?: string }; if (!c.ok || !done.redirect) return fail(done.error ?? "Не удалось войти через eGov"); setPhase({ at: "done" }); window.location.assign(done.redirect); } if (phase.at === "qr") { return (
{/* eslint-disable-next-line @next/next/no-img-element -- data URL from the server */} QR для eGov Mobile

{STATUS[phase.status] ?? phase.status}

{phase.deeplink && ( )}
); } return (
{phase.at === "error" &&

{phase.message}

}
); }