// eGov QR login (PEP-65) through the KazEDS relay (sign.aitu.uz): Peppa asks eGov Mobile to sign a
// short-lived , 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 { m as tr } from "@peppa/shared/i18n";
import { randomBytes, randomInt, randomUUID } from "node:crypto";
import { eq, sql } 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";
import { announceNewUser } from "./new-users.ts";
import { fetchViaFallbackDns, type FallbackResponse } from "./fallback-fetch.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(path: string, init?: RequestInit): Promise {
const base = loadEnv().KAZEDS_RELAY_BASE.replace(/\/$/, "");
// The relay sometimes hangs on one of its addresses: one quick retry (PEP-194).
let res: Response | FallbackResponse | 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 */
}
// No answer at all: the system resolver may point at an unreachable address (PEP-200).
if (!res) {
res = await fetchViaFallbackDns(base + path, {
method: init?.method,
body: typeof init?.body === "string" ? init.body : undefined,
headers: { "Content-Type": "application/json" },
});
}
}
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;
}
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 {
if (purpose === "link" && !userId) throw new PeppaError(tr("Привязать 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: `${challenge}${nonce}` }],
}),
});
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 {
if (!handle) return null;
const flow = await getSetting(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 {
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; /** PEP-71: the account was registered by this login. */ created: boolean }
| { 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 (PEP-71: registering one for an unknown IIN), or links it to the
* flow's account.
*/
export async function completeEgovFlow(db: Db, handle: string): Promise {
const flow = await loadFlow(db, handle);
if (!flow) throw new PeppaError(tr("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));
const created = !user;
const account = user ?? (await registerEgovUser(db, identity));
await db.update(users).set({ lastLoginAt: new Date() }).where(eq(users.id, account.id));
return { purpose: "login", user: account, identity, created };
}
/**
* PEP-71: eGov is the only way in, so an unknown IIN gets its own account on the first login — a
* Peppa account without Gitea (negative gitea_id, no password), login made from the name in the
* certificate. Access to projects comes from invitations; agents without a subscription pool do
* not run on this machine's login (`mayUseMachineLogin`).
*/
export async function registerEgovUser(db: Db, identity: EgovIdentity): Promise {
const base = egovLoginBase(identity);
for (let n = 1; n < 1000; n++) {
const suffix = n === 1 ? "" : `-${n}`;
const login = base.slice(0, 39 - suffix.length).replace(/[._-]+$/, "") + suffix;
const [taken] = await db.select({ id: users.id }).from(users).where(sql`lower(${users.login}) = ${login}`);
if (taken) continue;
for (let i = 0; i < 5; i++) {
const [row] = await db
.insert(users)
.values({ giteaId: -1 - randomInt(2 ** 47), login, name: displayName(identity.name), egovIin: identity.iin, egovLinkedAt: new Date() })
.onConflictDoNothing()
.returning();
if (row) {
await announceNewUser(db, row, "egov");
return row;
}
// Lost a race: the same IIN was registered meanwhile — that account is the answer.
const [same] = await db.select().from(users).where(eq(users.egovIin, identity.iin));
if (same) return same;
}
}
throw new PeppaError(tr("Не удалось создать пользователя"));
}
const TRANSLIT: Record = {
а: "a", б: "b", в: "v", г: "g", д: "d", е: "e", ё: "e", ж: "zh", з: "z", и: "i", й: "i", к: "k", л: "l", м: "m", н: "n", о: "o", п: "p", р: "r", с: "s",
т: "t", у: "u", ф: "f", х: "kh", ц: "ts", ч: "ch", ш: "sh", щ: "shch", ъ: "", ы: "y", ь: "", э: "e", ю: "yu", я: "ya",
ә: "a", ғ: "g", қ: "k", ң: "n", ө: "o", ұ: "u", ү: "u", һ: "h", і: "i",
};
/** "ИВАНОВА АСЕЛЬ" → "asel.ivanova"; no usable name → "user-". */
export function egovLoginBase(identity: EgovIdentity): string {
const words = (identity.name ?? "")
.toLowerCase()
.split(/\s+/)
.map((w) => [...w].map((c) => TRANSLIT[c] ?? (/[a-z0-9]/.test(c) ? c : "")).join(""))
.filter(Boolean);
// NCA certificates: "SURNAME GIVEN [PATRONYMIC]" — given name first reads better as a login.
const parts = words.length >= 2 ? [words[1]!, words[0]!] : words;
const login = parts.join(".").slice(0, 39);
return /^[a-z0-9][a-z0-9._-]{1,38}$/.test(login) ? login : `user-${identity.iin.slice(8)}`;
}
/** "ИВАНОВА АСЕЛЬ" → "Асель Иванова" for the UI. */
function displayName(name: string | null): string | null {
const words = (name ?? "").trim().split(/\s+/).filter(Boolean).map((w) => w[0]!.toUpperCase() + w.slice(1).toLowerCase());
if (!words.length) return null;
return (words.length >= 2 ? [words[1], words[0], ...words.slice(2)] : words).join(" ");
}
/** 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(`${flow.challenge}`) || !xml.includes(`${flow.nonce}`)) {
throw new PeppaError(tr("Подписан не тот документ — начните заново"));
}
const cert = /<(?:\w+:)?X509Certificate>\s*([A-Za-z0-9+/=\s]+?)\s*<\/(?:\w+:)?X509Certificate>/.exec(xml)?.[1];
if (!cert) throw new PeppaError(tr("В подписи нет сертификата"));
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(tr("В сертификате нет ИИН"));
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 = {
"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 {
if (iin !== null && !isValidIin(iin)) throw new PeppaError(tr("Неверный ИИН"));
if (iin) {
const [other] = await db.select().from(users).where(eq(users.egovIin, iin));
if (other && other.id !== userId) throw new PeppaError(tr("Этот ИИН уже привязан к другой учётке"));
}
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(tr("Пользователь не найден"));
return user;
}
/** "9001****0123" — enough to recognise your own IIN on screen. */
export const maskIin = (iin: string) => `${iin.slice(0, 4)}****${iin.slice(8)}`;