"use client"; import { useEffect, useRef, useState } from "react"; import { ChevronDown, QrCode, Smartphone } from "lucide-react"; import { Button } from "@/components/ui/button"; type Purpose = "login" | "link"; 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: "Подписано, входим…", }; const PHONE_STATUS: Record = { pending: "Откройте eGov Mobile и подпишите вход, потом вернитесь сюда", scanned: "Подпишите в eGov Mobile и вернитесь сюда", completed: "Подписано, входим…", }; /** Saved per tab so a phone that reloads the page on return from eGov Mobile picks the flow up again. */ const SAVED = "peppa.egov.flow"; interface Saved { purpose: Purpose; qr: string; deeplink: string; expiresAt: number; } function readSaved(purpose: Purpose): Saved | null { try { const s = JSON.parse(sessionStorage.getItem(SAVED) ?? "null") as Saved | null; return s && s.purpose === purpose && s.expiresAt > Date.now() ? s : null; } catch { return null; } } function writeSaved(s: Saved | null) { try { if (s) sessionStorage.setItem(SAVED, JSON.stringify(s)); else sessionStorage.removeItem(SAVED); } catch { /* private mode: no resume, the flow still works */ } } const isPhone = () => typeof window !== "undefined" && (/Android|iPhone|iPad|iPod/i.test(navigator.userAgent) || (navigator.maxTouchPoints > 1 && /Macintosh/.test(navigator.userAgent))); /** * eGov sign-in (PEP-65/72): on a computer — the relay's QR for eGov Mobile; on the phone itself — * a deep link that opens eGov Mobile, with the QR folded away. Polls the flow and finishes it; * `login` signs in (PEP-71: registers on first login), `link` binds the IIN (Settings). */ export function EgovSign({ purpose, next, label }: { purpose: Purpose; next?: string; label: string }) { const [phase, setPhase] = useState({ at: "idle" }); const [phone, setPhone] = useState(false); const [showQr, setShowQr] = useState(false); const alive = useRef(true); const gen = useRef(0); const wake = useRef<(() => void) | null>(null); const fail = (message: string) => { writeSaved(null); if (alive.current) setPhase({ at: "error", message }); }; async function poll() { // One loop at a time: a newer poll (or unmount) bumps the generation and the old one stops. const my = ++gen.current; const stale = () => !alive.current || gen.current !== my; { for (;;) { // Wait 2 s, or less when the tab comes back from eGov Mobile. await new Promise((res) => { const t = setTimeout(res, 2000); wake.current = () => { clearTimeout(t); res(); }; }); wake.current = null; if (stale()) return; const s = (await (await fetch("/auth/egov/status", { cache: "no-store" })).json().catch(() => ({}))) as { status?: string; error?: string }; if (stale()) return; if (s.error) return fail(s.error); if (s.status === "expired") return fail("Вход истёк — начните заново"); 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"); writeSaved(null); setPhase({ at: "done" }); window.location.assign(done.redirect); } } // Set on mount too: StrictMode (dev) mounts, unmounts and mounts again. useEffect(() => { alive.current = true; setPhone(isPhone()); const saved = readSaved(purpose); if (saved) { setPhase({ at: "qr", qr: saved.qr, deeplink: saved.deeplink, status: "pending" }); void poll().catch((e: Error) => fail(e.message)); } const onVisible = () => document.visibilityState === "visible" && wake.current?.(); document.addEventListener("visibilitychange", onVisible); window.addEventListener("pageshow", onVisible); return () => { alive.current = false; gen.current++; wake.current?.(); document.removeEventListener("visibilitychange", onVisible); window.removeEventListener("pageshow", onVisible); }; // eslint-disable-next-line react-hooks/exhaustive-deps -- once per mount }, []); 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; expiresAt?: number; error?: string }; if (!r.ok || !body.qr) return fail(body.error ?? "Не удалось начать вход через eGov"); const deeplink = body.deeplink ?? ""; writeSaved({ purpose, qr: body.qr, deeplink, expiresAt: body.expiresAt ?? Date.now() + 5 * 60_000 }); setShowQr(false); setPhase({ at: "qr", qr: body.qr, deeplink, status: "pending" }); await poll(); } if (phase.at === "qr") { const qrBlock = ( // eslint-disable-next-line @next/next/no-img-element -- data URL from the server QR для eGov Mobile ); const status = (phone ? PHONE_STATUS : STATUS)[phase.status] ?? phase.status; if (phone && phase.deeplink) { return (

{status}

{showQr && qrBlock}
); } return (
{qrBlock}

{status}

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

{phase.message}

}
); }