peppa/packages/testkit/src/mock-kazeds-relay.ts
peppa-bot 324c2139b8 PEP-194: вход через eGov — повтор запроса к сервису подписи и понятная ошибка
Сервис подписи sign.aitu.uz иногда висит на одном из адресов; ответ 502
Cloudflare подменял своей страницей, и на экране входа было
«Unexpected token <… is not valid JSON».

- relay: таймаут 8 с, один повтор при сетевой ошибке или 5xx
- маршруты start/status отвечают 424 (не 5xx — Cloudflare не подменяет)
- страница входа: непонятный ответ → «eGov сейчас не отвечает…»,
  опрос статуса переживает до 5 сбоев подряд
- мок: failNext, тест повтора

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

116 lines
5.9 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.

// Mock KazEDS relay (PEP-65) for tests and checks without a phone: POST /v1/egov/sessions and
// GET /v1/egov/:id/status with the relay's JSON shapes. The "phone" scans on the 1st poll and
// signs on the 3rd; the signed XML echoes the document and carries a FAKE certificate whose
// subject has SERIALNUMBER=IIN<iin> — not a signature, only the plumbing is exercised.
// Standalone: `mock-kazeds-relay [port]` (MOCK_EGOV_IIN, MOCK_EGOV_NAME).
import { randomUUID } from "node:crypto";
import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net";
export interface MockEgovSigner {
iin: string;
name: string;
/** The phone declines to sign. */
reject?: boolean;
/** The phone signs some other document (challenge replaced). */
tamper?: boolean;
}
interface Session {
documentXml: string;
polls: number;
signer: MockEgovSigner;
expiresAt: number;
}
const der = (tag: number, body: Buffer) => {
const len = body.length < 0x80 ? Buffer.from([body.length]) : body.length < 0x100 ? Buffer.from([0x81, body.length]) : Buffer.from([0x82, body.length >> 8, body.length & 0xff]);
return Buffer.concat([Buffer.from([tag]), len, body]);
};
const attr = (oidHex: string, value: string, tag = 0x0c) =>
der(0x31, der(0x30, Buffer.concat([der(0x06, Buffer.from(oidHex, "hex")), der(tag, Buffer.from(value, "utf8"))])));
/** A certificate-shaped DER blob: issuer and subject names only (enough for Peppa's subject reader). */
export function mockCertificate(signer: Pick<MockEgovSigner, "iin" | "name">): string {
const issuer = der(0x30, Buffer.concat([attr("550403", "MOCK NCA RK (not a CA)"), attr("550406", "KZ", 0x13)]));
const subject = der(0x30, Buffer.concat([attr("550403", signer.name), attr("550405", `IIN${signer.iin}`, 0x13), attr("550406", "KZ", 0x13)]));
const tbs = der(0x30, Buffer.concat([der(0x02, Buffer.from([1])), issuer, subject]));
return der(0x30, tbs).toString("base64");
}
export class MockKazedsRelay {
readonly sessions = new Map<string, Session>();
/** Who signs the next sessions. */
signer: MockEgovSigner;
/** The next N requests answer 503, like the real relay's flaky address (PEP-194). */
failNext = 0;
private server: Server | null = null;
constructor(signer: MockEgovSigner = { iin: "900101300126", name: "ТЕСТОВ ТЕСТ" }) {
this.signer = signer;
}
async start(port = 0): Promise<string> {
this.server = createServer((req, res) => void this.handle(req.method ?? "GET", req.url ?? "/", req, res));
await new Promise<void>((r) => this.server!.listen(port, "127.0.0.1", r));
return `http://127.0.0.1:${(this.server.address() as AddressInfo).port}/v1`;
}
async stop(): Promise<void> {
await new Promise<void>((r) => (this.server ? this.server.close(() => r()) : r()));
}
private async handle(method: string, url: string, req: import("node:http").IncomingMessage, res: import("node:http").ServerResponse) {
const send = (code: number, body: unknown) => {
res.writeHead(code, { "Content-Type": "application/json" });
res.end(JSON.stringify(body));
};
if (this.failNext > 0) {
this.failNext--;
return send(503, { error: "Service Unavailable" });
}
if (method === "POST" && url === "/v1/egov/sessions") {
let raw = "";
for await (const chunk of req) raw += chunk;
const body = JSON.parse(raw || "{}") as { signMethod?: string; organisation?: { bin?: string }; documentsToSign?: Array<{ documentXml?: string }> };
const xml = body.documentsToSign?.[0]?.documentXml;
if (body.signMethod !== "XML" || !xml || !/^\d{12}$/.test(body.organisation?.bin ?? "")) {
return send(400, { error: "Bad request", message: "signMethod XML, organisation.bin and documentsToSign[0].documentXml are required" });
}
const id = randomUUID();
const expiresAt = Date.now() + 5 * 60_000;
this.sessions.set(id, { documentXml: xml, polls: 0, signer: { ...this.signer }, expiresAt });
return send(201, {
session_id: id,
qr_content: `mobileSign:https://sign.aitu.uz/mock/mgovSign/${id}`,
deeplink: `https://m.egov.kz/mobileSign?link=${encodeURIComponent(`https://sign.aitu.uz/mock/mgovSign/${id}`)}`,
expires_at: new Date(expiresAt).toISOString(),
});
}
const m = /^\/v1\/egov\/([^/]+)\/status$/.exec(url);
if (method === "GET" && m) {
const s = this.sessions.get(decodeURIComponent(m[1]!));
if (!s) return send(404, { error: "Not found", message: "Session not found" });
const expiresIn = Math.max(0, Math.round((s.expiresAt - Date.now()) / 1000));
if (expiresIn === 0) return send(200, { status: "expired", expires_in: 0 });
s.polls += 1;
if (s.polls < 3) return send(200, { status: s.polls === 1 ? "scanned" : "pending", expires_in: expiresIn });
if (s.signer.reject) return send(200, { status: "rejected", expires_in: expiresIn });
const doc = s.signer.tamper ? s.documentXml.replace(/<challenge>[^<]*<\/challenge>/, "<challenge>other</challenge>") : s.documentXml;
const signed = doc.replace(
"</auth>",
`<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#"><ds:SignatureValue>MOCK_NOT_A_SIGNATURE</ds:SignatureValue>` +
`<ds:KeyInfo><ds:X509Data><ds:X509Certificate>${mockCertificate(s.signer)}</ds:X509Certificate></ds:X509Data></ds:KeyInfo></ds:Signature></auth>`,
);
return send(200, { status: "completed", expires_in: expiresIn, signedDocuments: [{ id: 1, nameRu: "Mock (not signed)", documentXml: signed }] });
}
send(404, { error: "Not found" });
}
}
if (import.meta.main) {
const relay = new MockKazedsRelay({ iin: process.env.MOCK_EGOV_IIN ?? "900101300126", name: process.env.MOCK_EGOV_NAME ?? "ТЕСТОВ ТЕСТ" });
const url = await relay.start(Number(process.argv[2] ?? process.env.MOCK_PORT ?? 3103));
console.log(`mock-kazeds-relay (TEST ONLY, fake signatures): KAZEDS_RELAY_BASE=${url}`);
}