diff --git a/apps/web/app/login/page.tsx b/apps/web/app/login/page.tsx
index e649de5e..58bccf1f 100644
--- a/apps/web/app/login/page.tsx
+++ b/apps/web/app/login/page.tsx
@@ -18,7 +18,7 @@ export default async function Login({ searchParams }: { searchParams: Promise<{
Софтвейр-фабрика: проекты в Gitea, стори по OpenSpec, агенты Claude Code и Codex.
- Первый вход сразу создаёт учётку по вашему ИИН. С телефона — кнопка «Открыть в eGov Mobile».
+ Первый вход сразу создаёт учётку по вашему ИИН. На телефоне вход открывает eGov Mobile, QR не нужен.
diff --git a/apps/web/components/EgovSign.tsx b/apps/web/components/EgovSign.tsx
index 5405327d..d0055e39 100644
--- a/apps/web/components/EgovSign.tsx
+++ b/apps/web/components/EgovSign.tsx
@@ -1,9 +1,10 @@
"use client";
import { useEffect, useRef, useState } from "react";
-import { QrCode, Smartphone } from "lucide-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 = {
@@ -11,50 +12,150 @@ const STATUS: Record = {
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 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).
+ * 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: "login" | "link"; next?: string; label: string }) {
+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;
- return () => void (alive.current = false);
+ 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
}, []);
- 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);
+ 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
+
+ );
+ const status = (phone ? PHONE_STATUS : STATUS)[phase.status] ?? phase.status;
+ if (phone && phase.deeplink) {
+ return (
+
+
+
{status}
+
+ {showQr && qrBlock}
+
+ );
+ }
return (
- {/* eslint-disable-next-line @next/next/no-img-element -- data URL from the server */}
-

-
{STATUS[phase.status] ?? phase.status}
+ {qrBlock}
+
{status}
{phase.deeplink && (