/* * Minimal Express adapter between a site's browser widget and KazEDS Relay. * Requires Node 20+, Express, and qrcode: * npm install express qrcode * * Mount this router only on the site that will verify the result. It returns * the signed XML to that site's browser; it does not authenticate a user. * The site MUST verify the XMLDSig, the exact challenge, certificate chain, * validity/revocation, and apply its own account/linking policy before login. */ const crypto = require('node:crypto'); const express = require('express'); const QRCode = require('qrcode'); const RELAY_BASE = (process.env.KAZEDS_RELAY_BASE || 'https://sign.aitu.uz/relay/v1').replace(/\/$/, ''); const ORGANISATION_NAME = process.env.EGOV_ORGANISATION_NAME || 'Вход на сайт'; const ORGANISATION_BIN = process.env.EGOV_ORGANISATION_BIN || '000000000000'; const SESSION_TTL_MS = 5 * 60 * 1000; const sessions = new Map(); async function relay(path, init) { const response = await fetch(RELAY_BASE + path, Object.assign({ headers: { 'Content-Type': 'application/json' }, }, init || {})); const body = await response.json().catch(() => ({})); if (!response.ok) throw new Error(body.message || body.error || `KazEDS Relay returned ${response.status}`); return body; } function makeRouter(options) { const settings = options || {}; const router = express.Router(); // POST /api/egov-login/start router.post('/start', express.json({ limit: '2kb' }), async (_req, res) => { try { const clientSessionId = crypto.randomUUID(); const challenge = crypto.randomBytes(32).toString('base64url'); // Keep this exact value in server memory; compare it after owner-side // XMLDSig verification. Do not trust a challenge returned by the browser. const challengeXml = `${challenge}${clientSessionId}`; const relaySession = await relay('/egov/sessions', { method: 'POST', body: JSON.stringify({ description: `Авторизация: ${ORGANISATION_NAME}`, organisation: { nameRu: ORGANISATION_NAME, nameKz: ORGANISATION_NAME, nameEn: ORGANISATION_NAME, bin: ORGANISATION_BIN }, signMethod: 'XML', documentsToSign: [{ id: 1, nameRu: `Вход на ${ORGANISATION_NAME}`, documentXml: challengeXml }], }), }); sessions.set(clientSessionId, { relaySessionId: relaySession.session_id, challenge, nonce: clientSessionId, expiresAt: Date.now() + SESSION_TTL_MS, signedDocuments: null, }); const qrDataUrl = await QRCode.toDataURL(relaySession.qr_content, { errorCorrectionLevel: 'H', margin: 2, width: 280 }); res.status(201).json({ clientSessionId, qrDataUrl, deeplink: relaySession.deeplink, expiresAt: relaySession.expires_at }); } catch (error) { res.status(502).json({ error: error.message || 'Could not create eGov QR session' }); } }); // GET /api/egov-login/:clientSessionId router.get('/:clientSessionId', async (req, res) => { const entry = sessions.get(req.params.clientSessionId); if (!entry) return res.status(404).json({ error: 'Login session not found' }); if (Date.now() >= entry.expiresAt) { sessions.delete(req.params.clientSessionId); return res.json({ status: 'expired' }); } try { const state = await relay(`/egov/${encodeURIComponent(entry.relaySessionId)}/status`, { method: 'GET' }); if (state.status === 'completed') { // Keep the signed content and expected challenge on the server. The // browser receives only a random handle and cannot replace either. entry.signedDocuments = state.signedDocuments; return res.json({ status: 'completed', verificationHandle: req.params.clientSessionId }); } return res.json({ status: state.status, expires_in: state.expires_in }); } catch (error) { return res.status(502).json({ error: error.message || 'Could not read eGov session status' }); } }); // POST /api/egov-login/complete { verificationHandle } // The relying site supplies its own verifier/account policy via onComplete. router.post('/complete', express.json({ limit: '2kb' }), async (req, res) => { const handle = req.body && req.body.verificationHandle; const entry = typeof handle === 'string' ? sessions.get(handle) : null; if (!entry || !entry.signedDocuments) return res.status(404).json({ error: 'Completed login flow not found' }); if (Date.now() >= entry.expiresAt) { sessions.delete(handle); return res.status(410).json({ error: 'Login flow expired' }); } if (typeof settings.onComplete !== 'function') { return res.status(501).json({ error: 'Configure the relying site onComplete verifier before using this endpoint' }); } try { const result = await settings.onComplete({ challenge: entry.challenge, nonce: entry.nonce, signedDocuments: entry.signedDocuments, request: req, }); sessions.delete(handle); return res.json(result || { authenticated: true }); } catch (error) { sessions.delete(handle); return res.status(401).json({ error: error.message || 'Signature verification failed' }); } }); return router; } module.exports = { makeRouter }; // Optional standalone demo server: `node signWidget.server.js` if (require.main === module) { const app = express(); app.use('/api/egov-login', makeRouter()); const port = Number(process.env.PORT || 3102); app.listen(port, () => console.log(`KazEDS eGov widget adapter listening on :${port}`)); }