PEP-200: вход через eGov — повтор запроса к relay через адреса запасного DNS
Системный DNS Mac Studio отдаёт для sign.aitu.uz недоступные адреса Cloudflare; если relay не ответил, запрос повторяется через адреса от PEPPA_FALLBACK_DNS (по умолчанию 1.1.1.1) с тем же именем хоста. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
7423b0e544
commit
2f6ee065cf
@ -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<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
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 };
|
||||
|
||||
83
packages/core/src/fallback-fetch.ts
Normal file
83
packages/core/src/fallback-fetch.ts
Normal file
@ -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<unknown>;
|
||||
}
|
||||
|
||||
type Resolve = (host: string) => Promise<string[]>;
|
||||
|
||||
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<string[]> {
|
||||
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<string, string> }, timeoutMs: number): Promise<FallbackResponse> {
|
||||
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<string, string> } = {},
|
||||
timeoutMs = 8_000,
|
||||
): Promise<FallbackResponse | null> {
|
||||
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;
|
||||
}
|
||||
@ -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";
|
||||
|
||||
@ -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");
|
||||
|
||||
Loading…
Reference in New Issue
Block a user