"use client"; import { useEffect, useRef, useState } from "react"; import { ChevronDown, QrCode, Smartphone } from "lucide-react"; import { Button } from "@/components/ui/button"; import { useT } from "@/components/I18n"; import { m } from "@peppa/shared/i18n"; 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: m("Отсканируйте QR в eGov Mobile"), scanned: m("QR отсканирован — подпишите в eGov Mobile"), completed: m("Подписано, входим…"), }; const PHONE_STATUS: Record = { pending: m("Откройте eGov Mobile и подпишите вход, потом вернитесь сюда"), scanned: m("Подпишите в eGov Mobile и вернитесь сюда"), completed: m("Подписано, входим…"), }; /** 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 t = useT(); 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; { let misses = 0; 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 r = await fetch("/auth/egov/status", { cache: "no-store" }).catch(() => null); const s = ((await r?.json().catch(() => null)) ?? null) as { status?: string; error?: string } | null; if (stale()) return; // A hiccup of the network or of eGov does not end the sign-in: give up after 5 failures in a row (PEP-194). if (!r?.ok || !s) { if (++misses >= 5) return fail(s?.error ?? m("eGov сейчас не отвечает — попробуйте ещё раз через минуту")); continue; } misses = 0; if (s.error) return fail(s.error); if (s.status === "expired") return fail(m("Вход истёк — начните заново")); if (s.status === "rejected") return fail(m("Подписание отменено в 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 ?? m("Не удалось войти через 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 }) }).catch(() => null); const body = ((await r?.json().catch(() => null)) ?? {}) as { qr?: string; deeplink?: string; expiresAt?: number; error?: string }; if (!r?.ok || !body.qr) return fail(body.error ?? m("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 {t("QR ); const status = t.text((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" &&

{t.text(phase.message)}

}
); }