From 2f6ee065cfac127312c8594b5fd3e4f2db4944a4 Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Tue, 17 Nov 2026 19:35:16 +0500 Subject: [PATCH] =?UTF-8?q?PEP-200:=20=D0=B2=D1=85=D0=BE=D0=B4=20=D1=87?= =?UTF-8?q?=D0=B5=D1=80=D0=B5=D0=B7=20eGov=20=E2=80=94=20=D0=BF=D0=BE?= =?UTF-8?q?=D0=B2=D1=82=D0=BE=D1=80=20=D0=B7=D0=B0=D0=BF=D1=80=D0=BE=D1=81?= =?UTF-8?q?=D0=B0=20=D0=BA=20relay=20=D1=87=D0=B5=D1=80=D0=B5=D0=B7=20?= =?UTF-8?q?=D0=B0=D0=B4=D1=80=D0=B5=D1=81=D0=B0=20=D0=B7=D0=B0=D0=BF=D0=B0?= =?UTF-8?q?=D1=81=D0=BD=D0=BE=D0=B3=D0=BE=20DNS?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Системный DNS Mac Studio отдаёт для sign.aitu.uz недоступные адреса Cloudflare; если relay не ответил, запрос повторяется через адреса от PEPPA_FALLBACK_DNS (по умолчанию 1.1.1.1) с тем же именем хоста. Co-Authored-By: Claude Opus 5.5 --- packages/core/src/egov.ts | 11 +++- packages/core/src/fallback-fetch.ts | 83 +++++++++++++++++++++++++++++ packages/core/src/index.ts | 1 + packages/testkit/test/egov.test.ts | 20 +++++++ 4 files changed, 114 insertions(+), 1 deletion(-) create mode 100644 packages/core/src/fallback-fetch.ts diff --git a/packages/core/src/egov.ts b/packages/core/src/egov.ts index 4ff7bb7a..94ee65b1 100644 --- a/packages/core/src/egov.ts +++ b/packages/core/src/egov.ts @@ -12,6 +12,7 @@ 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"; @@ -38,13 +39,21 @@ 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 | null = null; + 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 }; diff --git a/packages/core/src/fallback-fetch.ts b/packages/core/src/fallback-fetch.ts new file mode 100644 index 00000000..a376b488 --- /dev/null +++ b/packages/core/src/fallback-fetch.ts @@ -0,0 +1,83 @@ +// Some Cloudflare addresses are unreachable from the Peppa host, while the system resolver keeps +// handing them out (sign.aitu.uz → 188.114.96.3/97.3, PEP-200). When a request gets no response at +// all, it is repeated through the addresses another resolver gives (PEPPA_FALLBACK_DNS, default +// 1.1.1.1), keeping the host name for TLS (SNI) and the Host header. No system settings are touched. +import { Resolver } from "node:dns/promises"; +import { lookup as systemLookup } from "node:dns/promises"; +import http from "node:http"; +import https from "node:https"; + +export interface FallbackResponse { + status: number; + ok: boolean; + json(): Promise; +} + +type Resolve = (host: string) => Promise; + +let mockResolve: Resolve | null = null; +/** Tests: replace the fallback resolver (null restores the real one). */ +export function mockFallbackResolver(fn: Resolve | null): void { + mockResolve = fn; +} + +async function fallbackAddresses(host: string): Promise { + if (mockResolve) return mockResolve(host); + const servers = (process.env.PEPPA_FALLBACK_DNS ?? "1.1.1.1").split(",").map((s) => s.trim()).filter(Boolean); + if (!servers.length || servers[0] === "off") return []; + const r = new Resolver({ timeout: 3_000, tries: 1 }); + r.setServers(servers); + const ips = await r.resolve4(host).catch(() => [] as string[]); + const system = new Set((await systemLookup(host, { all: true, family: 4 }).catch(() => [])).map((a) => a.address)); + // Addresses the system already gave were just tried; put them last. + return [...ips.filter((ip) => !system.has(ip)), ...ips.filter((ip) => system.has(ip))]; +} + +function requestVia(url: URL, ip: string, init: { method?: string; body?: string; headers?: Record }, timeoutMs: number): Promise { + const mod = url.protocol === "http:" ? http : https; + return new Promise((resolve, reject) => { + const req = mod.request( + url, + { + method: init.method ?? "GET", + headers: init.headers, + timeout: timeoutMs, + lookup: (_h, opts, cb) => { + if ((opts as { all?: boolean }).all) (cb as (e: null, a: { address: string; family: number }[]) => void)(null, [{ address: ip, family: 4 }]); + else cb(null, ip, 4); + }, + }, + (res) => { + const chunks: Buffer[] = []; + res.on("data", (c: Buffer) => chunks.push(c)); + res.on("end", () => { + const text = Buffer.concat(chunks).toString("utf8"); + const status = res.statusCode ?? 0; + resolve({ status, ok: status >= 200 && status < 300, json: async () => JSON.parse(text) }); + }); + res.on("error", reject); + }, + ); + req.on("timeout", () => req.destroy(new Error("timeout"))); + req.on("error", reject); + if (init.body) req.write(init.body); + req.end(); + }); +} + +/** The same request through the fallback resolver's addresses; null when none answered. */ +export async function fetchViaFallbackDns( + target: string, + init: { method?: string; body?: string; headers?: Record } = {}, + timeoutMs = 8_000, +): Promise { + const url = new URL(target); + for (const ip of await fallbackAddresses(url.hostname)) { + try { + return await requestVia(url, ip, init, timeoutMs); + } catch { + /* next address */ + } + } + return null; +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 91e5a8d2..5c85f2d2 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -90,3 +90,4 @@ export * from "./feedback.ts"; export * from "./bench.ts"; export * from "./untrusted.ts"; export * from "./egress.ts"; +export * from "./fallback-fetch.ts"; diff --git a/packages/testkit/test/egov.test.ts b/packages/testkit/test/egov.test.ts index 47c6be6e..143e7128 100644 --- a/packages/testkit/test/egov.test.ts +++ b/packages/testkit/test/egov.test.ts @@ -44,6 +44,26 @@ describe("eGov QR", () => { relay.failNext = 0; }); + test("the system resolver gives an unreachable address: the fallback resolver's address works (PEP-200)", async () => { + const real = process.env.KAZEDS_RELAY_BASE!; + const u = new URL(real); + u.hostname = "mock-relay.invalid"; + process.env.KAZEDS_RELAY_BASE = u.toString(); + const asked: string[] = []; + core.mockFallbackResolver(async (host) => (asked.push(host), ["127.0.0.1"])); + try { + const f = await core.startEgovFlow(db, "login"); + assert.match(f.qrContent, /^mobileSign:/); + assert.ok(asked.includes("mock-relay.invalid")); + // No fallback address either: the clear message stays. + core.mockFallbackResolver(async () => []); + await assert.rejects(core.startEgovFlow(db, "login"), (e: Error) => e instanceof core.PeppaError && /не отвечает/.test(e.message)); + } finally { + core.mockFallbackResolver(null); + process.env.KAZEDS_RELAY_BASE = real; + } + }); + 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");