peppa/apps/web/components/EgovSign.tsx
peppa-bot 324c2139b8 PEP-194: вход через eGov — повтор запроса к сервису подписи и понятная ошибка
Сервис подписи sign.aitu.uz иногда висит на одном из адресов; ответ 502
Cloudflare подменял своей страницей, и на экране входа было
«Unexpected token <… is not valid JSON».

- relay: таймаут 8 с, один повтор при сетевой ошибке или 5xx
- маршруты start/status отвечают 424 (не 5xx — Cloudflare не подменяет)
- страница входа: непонятный ответ → «eGov сейчас не отвечает…»,
  опрос статуса переживает до 5 сбоев подряд
- мок: failNext, тест повтора

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 14:22:37 +05:00

189 lines
8.5 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"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<string, string> = {
pending: m("Отсканируйте QR в eGov Mobile"),
scanned: m("QR отсканирован — подпишите в eGov Mobile"),
completed: m("Подписано, входим…"),
};
const PHONE_STATUS: Record<string, string> = {
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<Phase>({ 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<void>((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
<img src={phase.qr} alt={t("QR для eGov Mobile")} width={220} height={220} className="rounded-md bg-white p-1" />
);
const status = t.text((phone ? PHONE_STATUS : STATUS)[phase.status] ?? phase.status);
if (phone && phase.deeplink) {
return (
<div className="flex w-full flex-col items-center gap-3 rounded-lg border bg-card p-4">
<Button asChild variant="default" size="lg" className="w-full">
<a href={phase.deeplink}>
<Smartphone /> {t("Открыть eGov Mobile")}
</a>
</Button>
<p className="m-0 text-sm text-muted-foreground" aria-live="polite">{status}</p>
<button type="button" className="inline-flex items-center gap-1 text-xs text-muted-foreground underline-offset-2 hover:underline" onClick={() => setShowQr((v) => !v)}>
<ChevronDown className={showQr ? "size-3 rotate-180" : "size-3"} /> {showQr ? t("Скрыть QR") : t("Войти с другого телефона по QR")}
</button>
{showQr && qrBlock}
</div>
);
}
return (
<div className="flex w-full flex-col items-center gap-3 rounded-lg border bg-card p-4">
{qrBlock}
<p className="m-0 text-sm text-muted-foreground" aria-live="polite">{status}</p>
{phase.deeplink && (
<Button asChild variant="outline" size="sm" className="w-full">
<a href={phase.deeplink}>
<Smartphone /> {t("Открыть в eGov Mobile")}
</a>
</Button>
)}
</div>
);
}
return (
<div className="flex w-full flex-col gap-2">
{phase.at === "error" && <p className="m-0 text-sm text-destructive">{t.text(phase.message)}</p>}
<Button variant={purpose === "login" ? "default" : "outline"} size="lg" className="w-full" disabled={phase.at === "done"} onClick={() => void start().catch((e: Error) => fail(e.message))}>
{phone ? <Smartphone /> : <QrCode />} {phase.at === "error" ? (phone ? t("Начать заново") : t("Новый QR")) : phone ? `${label} Mobile` : label}
</Button>
</div>
);
}