// 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 — 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): 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(); /** 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 { this.server = createServer((req, res) => void this.handle(req.method ?? "GET", req.url ?? "/", req, res)); await new Promise((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 { await new Promise((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>/, "other") : s.documentXml; const signed = doc.replace( "", `MOCK_NOT_A_SIGNATURE` + `${mockCertificate(s.signer)}`, ); 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}`); }