peppa/packages/core/src/egov.ts
peppa-bot acb6e3fb81
All checks were successful
peppa/lint lint: success за 1с
peppa/typecheck typecheck: success за 46с
peppa/build build: success за 34с
peppa/test test: success за 1325с
peppa-ci / ci (pull_request) Successful in 24m11s
PEP-224: статус функций из мониторинга (сведено с main после PEP-225)
Функция → мониторинги (core/feature-status.ts), серая кнопка входа через eGov и статус MCP,
отказ startEgovFlow, журнал и сообщения в канал. После переезда живых обновлений на
WebSocket (PEP-225): область `features` в LIVE_PLAIN_SCOPES, открыта без входа (SSE и
WebSocket с `anonymous: true` — только открытые области), смотрится по таймеру вместе с
`observe`, смена сбрасывает кэш статусов.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 15:00:03 +00:00

438 lines
20 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 { assertFeatureAvailable } from "./feature-status.ts";
import { m as tr } from "@peppa/shared/i18n";
import { randomBytes, randomInt, randomUUID } from "node:crypto";
import { and, eq, gte, inArray, sql } from "drizzle-orm";
import { events, projects, 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 { logEvent } from "./audit.ts";
import { platformProjectKey } from "./platform-channel.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;
}
/** Whether the last successful relay call needed the fallback resolver (for the success event). */
let lastViaFallback = false;
const flowKey = (handle: string) => `egov.flow:${hashToken(handle)}`;
/** PEP-211: why a login step failed — a stable code for counting, words for the journal. */
export type EgovFailCode =
| "flow_expired"
| "challenge_mismatch"
| "no_certificate"
| "no_iin"
| "not_allowed"
| "relay_down"
| "relay_http"
| "not_signed"
| "rejected"
| "iin_taken"
| "other";
export type EgovStep = "start" | "status" | "complete";
/** A PeppaError that carries the failure code (the user text stays as before). */
class EgovError extends PeppaError {
code: EgovFailCode;
relayStatus: number | null;
viaFallback: boolean;
constructor(message: string, code: EgovFailCode, extra: { relayStatus?: number; viaFallback?: boolean } = {}) {
super(message);
this.code = code;
this.relayStatus = extra.relayStatus ?? null;
this.viaFallback = extra.viaFallback ?? false;
}
}
export const EGOV_FAIL_REASON: Record<EgovFailCode, string> = {
flow_expired: "сеанс истёк или не найден",
challenge_mismatch: "подписан не тот документ (challenge/nonce не сошлись)",
no_certificate: "в подписи нет сертификата",
no_iin: "в сертификате нет ИИН",
not_allowed: "ИИН не привязан или нет доступа",
relay_down: "relay не ответил",
relay_http: "relay ответил ошибкой",
not_signed: "документ ещё не подписан",
rejected: "подписание отменено в eGov",
iin_taken: "ИИН уже привязан к другой учётке",
other: "другая причина",
};
async function relay<T>(path: string, init?: RequestInit): Promise<T> {
let viaFallback = false;
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) {
viaFallback = true;
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 EgovError(tr("eGov сейчас не отвечает — попробуйте ещё раз через минуту"), "relay_down", { viaFallback });
const body = (await res.json().catch(() => ({}))) as T & { message?: string; error?: string };
if (!res.ok) throw new EgovError(`eGov relay: ${body.message ?? body.error ?? `HTTP ${res.status}`}`, "relay_http", { relayStatus: res.status, viaFallback });
lastViaFallback = viaFallback;
return body;
}
/**
* PEP-211: one journal event per failed or successful login step, in the platform project. No IIN,
* document or signature goes in — only the step, the reason, the purpose and a hash of the flow.
* Never throws: the journal must not break a login.
*/
export async function logEgovEvent(
db: Db,
e: { ok: true; step: EgovStep; purpose?: EgovPurpose; handle?: string; userId?: number | null; viaFallback?: boolean } | { ok: false; step: EgovStep; error: unknown; purpose?: EgovPurpose; handle?: string; userId?: number | null; code?: EgovFailCode },
): Promise<void> {
try {
const [p] = await db.select({ id: projects.id }).from(projects).where(eq(projects.key, platformProjectKey()));
if (!p) return;
const base = { step: e.step, purpose: e.purpose ?? null, flow: e.handle ? hashToken(e.handle).slice(0, 12) : null, userId: e.userId ?? null };
if (e.ok) {
await logEvent(db, { projectId: p.id, type: "egov_login_ok", payload: { ...base, viaFallback: e.viaFallback ?? false } });
return;
}
const err = e.error instanceof EgovError ? e.error : null;
const code = e.code ?? err?.code ?? "other";
await logEvent(db, {
projectId: p.id,
type: "egov_login_failed",
payload: {
...base,
code,
reason: EGOV_FAIL_REASON[code],
relayStatus: err?.relayStatus ?? null,
viaFallback: err?.viaFallback ?? false,
message: e.error instanceof PeppaError ? e.error.message.slice(0, 200) : null,
},
});
} catch {
/* best effort */
}
}
/** Login and failure counts for the last `hours` hours: «Входы за сутки: N, неудачных M (по причинам)». */
export async function egovLoginSummary(db: Db, hours = 24, now = new Date()): Promise<{ total: number; failed: number; byReason: { code: string; reason: string; n: number }[] }> {
const since = new Date(now.getTime() - hours * 3600_000);
const rows = await db
.select({ type: events.type, code: sql<string | null>`json_extract(${events.payload}, '$.code')`, n: sql<number>`count(*)` })
.from(events)
.where(and(inArray(events.type, ["egov_login_ok", "egov_login_failed"]), gte(events.createdAt, since)))
.groupBy(events.type, sql`json_extract(${events.payload}, '$.code')`);
let total = 0;
let failed = 0;
const byReason: { code: string; reason: string; n: number }[] = [];
for (const r of rows) {
const n = Number(r.n);
total += n;
if (r.type === "egov_login_failed") {
failed += n;
const code = (r.code ?? "other") as EgovFailCode;
byReason.push({ code, reason: EGOV_FAIL_REASON[code] ?? code, n });
}
}
byReason.sort((a, b) => b.n - a.n);
return { total, failed, byReason };
}
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> {
try {
return await startEgovFlowInner(db, purpose, userId);
} catch (error) {
await logEgovEvent(db, { ok: false, step: "start", error, purpose, userId });
throw error;
}
}
async function startEgovFlowInner(db: Db, purpose: EgovPurpose, userId: number | null): Promise<EgovStart> {
if (purpose === "link" && !userId) throw new PeppaError(tr("Привязать eGov можно только после входа"));
// PEP-224: eGov is known to be down — say so now instead of a QR that never signs.
assertFeatureAvailable("egov_login");
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";
try {
return (await relay<{ status: EgovStatus }>(`/egov/${encodeURIComponent(flow.relaySessionId)}/status`)).status;
} catch (error) {
await logEgovEvent(db, { ok: false, step: "status", error, purpose: flow.purpose, handle, userId: flow.userId });
throw error;
}
}
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<EgovResult> {
const flow = await loadFlow(db, handle);
try {
const r = await completeEgovFlowInner(db, handle, flow);
// A login is counted by the caller once the account is known to be allowed in (`logEgovEvent`).
if (r.purpose === "link") await logEgovEvent(db, { ok: true, step: "complete", purpose: "link", handle, userId: r.user.id, viaFallback: lastViaFallback });
return r;
} catch (error) {
await logEgovEvent(db, { ok: false, step: "complete", error, purpose: flow?.purpose, handle, userId: flow?.userId });
throw error;
}
}
async function completeEgovFlowInner(db: Db, handle: string, flow: Flow | null): Promise<EgovResult> {
if (!flow) throw new EgovError(tr("QR-код истёк — начните заново"), "flow_expired");
await deleteSetting(db, flowKey(handle));
const s = await relay<{ status: EgovStatus; signedDocuments?: SignedDocument[] }>(`/egov/${encodeURIComponent(flow.relaySessionId)}/status`);
if (s.status !== "completed") throw new EgovError(s.status === "rejected" ? "Подписание отменено" : "Документ ещё не подписан", s.status === "rejected" ? "rejected" : "not_signed");
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<User> {
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<string, string> = {
а: "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-<last 4 of IIN>". */
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(`<challenge>${flow.challenge}</challenge>`) || !xml.includes(`<nonce>${flow.nonce}</nonce>`)) {
throw new EgovError(tr("Подписан не тот документ — начните заново"), "challenge_mismatch");
}
const cert = /<(?:\w+:)?X509Certificate>\s*([A-Za-z0-9+/=\s]+?)\s*<\/(?:\w+:)?X509Certificate>/.exec(xml)?.[1];
if (!cert) throw new EgovError(tr("В подписи нет сертификата"), "no_certificate");
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 EgovError(tr("В сертификате нет ИИН"), "no_iin");
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(tr("Неверный ИИН"));
if (iin) {
const [other] = await db.select().from(users).where(eq(users.egovIin, iin));
if (other && other.id !== userId) throw new EgovError(tr("Этот ИИН уже привязан к другой учётке"), "iin_taken");
}
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)}`;