import { PeppaError, startEgovFlow, type EgovPurpose } from "@peppa/core"; import { NextResponse, type NextRequest } from "next/server"; import QRCode from "qrcode"; import { currentUser, EGOV_COOKIE, egovCookieOptions } from "@/lib/auth"; import { db } from "@/lib/db"; import { m } from "@peppa/shared/i18n"; /** Starts an eGov QR flow (PEP-65): `login` from the login page, `link` from Settings (needs a session). */ export async function POST(req: NextRequest) { const { purpose } = (await req.json().catch(() => ({}))) as { purpose?: EgovPurpose }; try { const user = purpose === "link" ? await currentUser() : null; const flow = await startEgovFlow(db, purpose === "link" ? "link" : "login", user?.id ?? null); const qr = await QRCode.toDataURL(flow.qrContent, { errorCorrectionLevel: "M", margin: 2, width: 280 }); const res = NextResponse.json({ qr, deeplink: flow.deeplink, expiresAt: flow.expiresAt }); 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: 424 } /* not 5xx: Cloudflare replaces those with its own page (PEP-194) */); } }