peppa/packages/core/src/egov.ts
Асель ed49767c31 PEP-65: eGov QR login through the KazEDS relay (sign.aitu.uz)
Login page and Settings → eGov: relay session with a server-side challenge/nonce, QR + eGov Mobile
deep link, polling, one-shot completion; IIN from the signer's certificate (own DER reader),
users.egov_iin. The relay is trusted (PM decision): no own XMLDSig check. CLI peppa user egov,
mock-kazeds-relay, tests. Dev mode: /_next/static is no-store (Cloudflare cached stale chunks).

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

218 lines
9.8 KiB
TypeScript
Raw 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.

// eGov QR login (PEP-65) through the KazEDS relay (sign.aitu.uz): Peppa asks eGov Mobile to sign a
// short-lived <auth><challenge/><nonce/></auth>, reads the signed XML from the relay itself and takes
// the signer's IIN from the certificate. The XMLDSig itself is not verified here — the relay is
// trusted (PM decision, see openspec design); the challenge and nonce never leave the server.
import { randomBytes, randomUUID } from "node:crypto";
import { eq } from "drizzle-orm";
import { users, type Db } from "@peppa/db";
import { loadEnv } from "@peppa/shared";
import { hashToken } from "./crypto.ts";
import { PeppaError } from "./errors.ts";
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
import { getUser, type User } from "./users.ts";
export const EGOV_FLOW_TTL_MS = 5 * 60_000;
export type EgovPurpose = "login" | "link";
export type EgovStatus = "pending" | "scanned" | "completed" | "expired" | "rejected";
interface Flow {
purpose: EgovPurpose;
/** The account being linked (purpose "link"). */
userId: number | null;
relaySessionId: string;
challenge: string;
nonce: string;
expiresAt: number;
}
interface SignedDocument {
id: number;
nameRu?: string;
documentXml: string;
}
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) });
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;
}
export interface EgovStart {
/** Opaque handle: kept by the browser in an httpOnly cookie, never in a URL. */
handle: string;
/** What the QR encodes (eGov Mobile scans it). */
qrContent: string;
/** Opens eGov Mobile on the same phone. */
deeplink: string;
expiresAt: number;
}
/** Starts a signing session in the relay for a login or for linking `userId`'s IIN. */
export async function startEgovFlow(db: Db, purpose: EgovPurpose, userId: number | null = null): Promise<EgovStart> {
if (purpose === "link" && !userId) throw new PeppaError("Привязать eGov можно только после входа");
const env = loadEnv();
const nonce = randomUUID();
const challenge = randomBytes(32).toString("base64url");
const org = env.EGOV_ORGANISATION_NAME;
const s = await relay<{ session_id: string; qr_content: string; deeplink: string; expires_at?: string }>("/egov/sessions", {
method: "POST",
body: JSON.stringify({
description: purpose === "link" ? `Привязка eGov: ${org}` : `Авторизация: ${org}`,
organisation: { nameRu: org, nameKz: org, nameEn: org, bin: env.EGOV_ORGANISATION_BIN },
signMethod: "XML",
documentsToSign: [{ id: 1, nameRu: `Вход в ${org}`, documentXml: `<auth><challenge>${challenge}</challenge><nonce>${nonce}</nonce></auth>` }],
}),
});
const relayExpiry = s.expires_at ? Date.parse(s.expires_at) : NaN;
const expiresAt = Math.min(Date.now() + EGOV_FLOW_TTL_MS, Number.isFinite(relayExpiry) ? relayExpiry : Infinity);
const handle = randomBytes(24).toString("base64url");
const flow: Flow = { purpose, userId, relaySessionId: s.session_id, challenge, nonce, expiresAt };
await setSetting(db, flowKey(handle), flow);
return { handle, qrContent: s.qr_content, deeplink: s.deeplink, expiresAt };
}
async function loadFlow(db: Db, handle: string): Promise<Flow | null> {
if (!handle) return null;
const flow = await getSetting<Flow>(db, flowKey(handle));
if (flow && Date.now() >= flow.expiresAt) {
await deleteSetting(db, flowKey(handle));
return null;
}
return flow;
}
/** Relay status of a flow; "expired" once the flow is gone or past its TTL. */
export async function egovFlowStatus(db: Db, handle: string): Promise<EgovStatus> {
const flow = await loadFlow(db, handle);
if (!flow) return "expired";
const s = await relay<{ status: EgovStatus }>(`/egov/${encodeURIComponent(flow.relaySessionId)}/status`);
return s.status;
}
export interface EgovIdentity {
iin: string;
name: string | null;
}
export type EgovResult = { purpose: "login"; user: User; identity: EgovIdentity } | { purpose: "link"; user: User; identity: EgovIdentity };
/**
* Finishes a signed flow (one-shot: the flow is removed whatever happens): checks that the
* signed XML carries this flow's challenge and nonce, reads the signer's IIN, then logs in the
* account the IIN is linked to, or links it to the flow's account.
*/
export async function completeEgovFlow(db: Db, handle: string): Promise<EgovResult> {
const flow = await loadFlow(db, handle);
if (!flow) throw new PeppaError("QR-код истёк — начните заново");
await deleteSetting(db, flowKey(handle));
const s = await relay<{ status: EgovStatus; signedDocuments?: SignedDocument[] }>(`/egov/${encodeURIComponent(flow.relaySessionId)}/status`);
if (s.status !== "completed") throw new PeppaError(s.status === "rejected" ? "Подписание отменено" : "Документ ещё не подписан");
const identity = verifySigned(s.signedDocuments ?? [], flow);
if (flow.purpose === "link") {
const user = await linkEgovIin(db, flow.userId!, identity.iin);
return { purpose: "link", user, identity };
}
const [user] = await db.select().from(users).where(eq(users.egovIin, identity.iin));
if (!user) throw new PeppaError("Этот ИИН не привязан к Пеппе — войдите через Gitea и привяжите eGov в «Настройках»");
return { purpose: "login", user, identity };
}
/** The trust check (relay trusted): our challenge and nonce are in the signed XML; signer from the certificate. */
function verifySigned(docs: SignedDocument[], flow: Flow): EgovIdentity {
const xml = docs[0]?.documentXml ?? "";
if (!xml.includes(`<challenge>${flow.challenge}</challenge>`) || !xml.includes(`<nonce>${flow.nonce}</nonce>`)) {
throw new PeppaError("Подписан не тот документ — начните заново");
}
const cert = /<(?:\w+:)?X509Certificate>\s*([A-Za-z0-9+/=\s]+?)\s*<\/(?:\w+:)?X509Certificate>/.exec(xml)?.[1];
if (!cert) throw new PeppaError("В подписи нет сертификата");
const subject = certificateSubject(Buffer.from(cert.replace(/\s+/g, ""), "base64"));
const iin = /^IIN(\d{12})$/.exec(subject.serialNumber ?? "")?.[1];
if (!iin || !isValidIin(iin)) throw new PeppaError("В сертификате нет ИИН");
const name = subject.commonName ?? ([subject.surname, subject.givenName].filter(Boolean).join(" ") || null);
return { iin, name };
}
export interface CertSubject {
serialNumber?: string;
commonName?: string;
surname?: string;
givenName?: string;
}
const SUBJECT_OIDS: Record<string, keyof CertSubject> = {
"550405": "serialNumber", // 2.5.4.5
"550403": "commonName", // 2.5.4.3
"550404": "surname", // 2.5.4.4
"55042a": "givenName", // 2.5.4.42
};
/**
* Subject fields of an X.509 certificate (DER), read by walking the ASN.1 tree. node:crypto's
* X509Certificate is not used: it may refuse the GOST keys of NCA RK, and only the names matter.
* The issuer comes before the subject in the certificate, so the last value of each field wins.
*/
export function certificateSubject(der: Buffer): CertSubject {
const out: CertSubject = {};
const walk = (start: number, end: number) => {
let i = start;
while (i < end) {
const tag = der[i]!;
let len = der[i + 1]!;
let off = i + 2;
if (len & 0x80) {
const n = len & 0x7f;
if (n === 0 || n > 4) return;
len = 0;
for (let k = 0; k < n; k++) len = len * 256 + der[off + k]!;
off += n;
}
const next = off + len;
if (next > end) return;
if (tag === 0x30 && len > 2 && der[off] === 0x06) {
// SEQUENCE { OID, value }: an AttributeTypeAndValue when the OID is a name attribute.
const oidLen = der[off + 1]!;
const field = SUBJECT_OIDS[der.subarray(off + 2, off + 2 + oidLen).toString("hex")];
const v = off + 2 + oidLen;
if (field && v + 2 <= next) {
out[field] = der.subarray(v + 2, v + 2 + der[v + 1]!).toString(der[v] === 0x1e ? "utf16le" : "utf8");
}
}
if (tag & 0x20) walk(off, next); // constructed: descend
i = next;
}
};
walk(0, der.length);
return out;
}
/** IIN control digit (the same algorithm as BIN). */
export function isValidIin(iin: string): boolean {
if (!/^\d{12}$/.test(iin)) return false;
const d = [...iin].map(Number);
const sum = (w: number[]) => w.reduce((a, x, i) => a + x * d[i]!, 0) % 11;
let c = sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);
if (c === 10) c = sum([3, 4, 5, 6, 7, 8, 9, 10, 11, 1, 2]);
return c !== 10 && c === d[11];
}
/** Links an IIN to an account (or unlinks with null). One account per IIN. */
export async function linkEgovIin(db: Db, userId: number, iin: string | null): Promise<User> {
if (iin !== null && !isValidIin(iin)) throw new PeppaError("Неверный ИИН");
if (iin) {
const [other] = await db.select().from(users).where(eq(users.egovIin, iin));
if (other && other.id !== userId) throw new PeppaError("Этот ИИН уже привязан к другой учётке");
}
await db.update(users).set({ egovIin: iin, egovLinkedAt: iin ? new Date() : null }).where(eq(users.id, userId));
const user = await getUser(db, userId);
if (!user) throw new PeppaError("Пользователь не найден");
return user;
}
/** "9001****0123" — enough to recognise your own IIN on screen. */
export const maskIin = (iin: string) => `${iin.slice(0, 4)}****${iin.slice(8)}`;