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>
This commit is contained in:
peppa-bot 2026-11-17 14:22:31 +05:00
parent c092639a93
commit 324c2139b8
8 changed files with 41 additions and 7 deletions

View File

@ -16,6 +16,6 @@ export async function POST(req: NextRequest) {
res.cookies.set(EGOV_COOKIE, flow.handle, egovCookieOptions(Math.ceil((flow.expiresAt - Date.now()) / 1000)));
return res;
} catch (e) {
return NextResponse.json({ error: e instanceof PeppaError ? e.message : m("Не удалось создать QR eGov") }, { status: 502 });
return NextResponse.json({ error: e instanceof PeppaError ? e.message : m("Не удалось создать QR eGov") }, { status: 424 } /* not 5xx: Cloudflare replaces those with its own page (PEP-194) */);
}
}

View File

@ -10,6 +10,6 @@ export async function GET() {
try {
return NextResponse.json({ status: await egovFlowStatus(db, (await cookies()).get(EGOV_COOKIE)?.value ?? "") });
} catch (e) {
return NextResponse.json({ error: e instanceof PeppaError ? e.message : m("eGov недоступен") }, { status: 502 });
return NextResponse.json({ error: e instanceof PeppaError ? e.message : m("eGov недоступен") }, { status: 424 } /* not 5xx: Cloudflare replaces those with its own page (PEP-194) */);
}
}

View File

@ -72,6 +72,7 @@ export function EgovSign({ purpose, next, label }: { purpose: Purpose; next?: st
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) => {
@ -83,8 +84,15 @@ export function EgovSign({ purpose, next, label }: { purpose: Purpose; next?: st
});
wake.current = null;
if (stale()) return;
const s = (await (await fetch("/auth/egov/status", { cache: "no-store" })).json().catch(() => ({}))) as { status?: string; error?: string };
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"));
@ -123,9 +131,9 @@ export function EgovSign({ purpose, next, label }: { purpose: Purpose; next?: st
}, []);
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 ?? m("Не удалось начать вход через eGov"));
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);

View File

@ -37,7 +37,16 @@ const flowKey = (handle: string) => `egov.flow:${hashToken(handle)}`;
async function relay<T>(path: string, init?: RequestInit): Promise<T> {
const base = loadEnv().KAZEDS_RELAY_BASE.replace(/\/$/, "");
const res = await fetch(base + path, { ...init, headers: { "Content-Type": "application/json" }, signal: AbortSignal.timeout(15_000) });
// The relay sometimes hangs on one of its addresses: one quick retry (PEP-194).
let res: Response | null = null;
for (let attempt = 0; attempt < 2 && (!res || res.status >= 500); attempt++) {
try {
res = await fetch(base + path, { ...init, headers: { "Content-Type": "application/json" }, signal: AbortSignal.timeout(8_000) });
} catch {
/* network error or timeout: retry once */
}
}
if (!res) throw new PeppaError(tr("eGov сейчас не отвечает — попробуйте ещё раз через минуту"));
const body = (await res.json().catch(() => ({}))) as T & { message?: string; error?: string };
if (!res.ok) throw new PeppaError(`eGov relay: ${body.message ?? body.error ?? `HTTP ${res.status}`}`);
return body;

View File

@ -251,6 +251,7 @@ export const help: Dict = {
"Не удалось войти через Google": "Couldn't sign in with Google",
"Не удалось войти через eGov": "Couldn't sign in with eGov",
"Не удалось создать QR eGov": "Couldn't create the eGov QR code",
"eGov сейчас не отвечает — попробуйте ещё раз через минуту": "eGov isn't responding right now — try again in a minute",
"eGov недоступен": "eGov is unavailable",
// ---- EgovSign
"Отсканируйте QR в eGov Mobile": "Scan the QR code in eGov Mobile",

View File

@ -202,6 +202,7 @@ export const help: Dict = {
"Не удалось войти через Google": "Google арқылы кіру мүмкін болмады",
"Не удалось войти через eGov": "eGov арқылы кіру мүмкін болмады",
"Не удалось создать QR eGov": "eGov QR кодын жасау мүмкін болмады",
"eGov сейчас не отвечает — попробуйте ещё раз через минуту": "eGov қазір жауап бермей тұр — бір минуттан кейін қайталап көріңіз",
"eGov недоступен": "eGov қолжетімсіз",
"Отсканируйте QR в eGov Mobile": "QR кодты eGov Mobile-да сканерлеңіз",
"QR отсканирован — подпишите в eGov Mobile": "QR сканерленді — eGov Mobile-да қол қойыңыз",

View File

@ -42,6 +42,8 @@ export class MockKazedsRelay {
readonly sessions = new Map<string, Session>();
/** Who signs the next sessions. */
signer: MockEgovSigner;
/** The next N requests answer 503, like the real relay's flaky address (PEP-194). */
failNext = 0;
private server: Server | null = null;
constructor(signer: MockEgovSigner = { iin: "900101300126", name: "ТЕСТОВ ТЕСТ" }) {
@ -63,6 +65,10 @@ export class MockKazedsRelay {
res.writeHead(code, { "Content-Type": "application/json" });
res.end(JSON.stringify(body));
};
if (this.failNext > 0) {
this.failNext--;
return send(503, { error: "Service Unavailable" });
}
if (method === "POST" && url === "/v1/egov/sessions") {
let raw = "";
for await (const chunk of req) raw += chunk;

View File

@ -35,6 +35,15 @@ describe("eGov QR", () => {
assert.ok(!core.isValidIin("900101300123"));
});
test("the relay fails once: the request is retried; fails twice: a clear message (PEP-194)", async () => {
relay.failNext = 1;
const f = await core.startEgovFlow(db, "login");
assert.match(f.qrContent, /^mobileSign:/);
relay.failNext = 2;
await assert.rejects(core.startEgovFlow(db, "login"), (e: Error) => e instanceof core.PeppaError && /eGov relay: Service Unavailable/.test(e.message));
relay.failNext = 0;
});
test("unknown IIN: the first login registers the account, the next one finds it (PEP-71)", async () => {
relay.signer = { iin: "850505400008", name: "ИВАНОВА ӘЙГЕРІМ ҚАЙРАТҚЫЗЫ" };
const f = await core.startEgovFlow(db, "login");