peppa/docs/egov-reference/signWidget.js
Асель ed49767c31 PEP-65: eGov QR login through the KazEDS relay (sign.aitu.uz)
Login page and Settings → eGov: relay session with a server-side challenge/nonce, QR + eGov Mobile
deep link, polling, one-shot completion; IIN from the signer's certificate (own DER reader),
users.egov_iin. The relay is trusted (PM decision): no own XMLDSig check. CLI peppa user egov,
mock-kazeds-relay, tests. Dev mode: /_next/static is no-store (Cloudflare cached stale chunks).

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

172 lines
6.4 KiB
JavaScript

/*
* KazEDS eGov QR sign-in widget (browser side)
*
* Usage:
* <div id="egov-login"></div>
* <script src="/signWidget.js"></script>
* <script>
* SignWidget.mount({
* container: '#egov-login',
* apiBase: '/api/egov-login',
* onSigned: async (result) => {
* // POST result to YOUR backend and validate the XML signature,
* // challenge, certificate chain, and revocation status there.
* }
* });
* </script>
*
* QR images are generated by the site's backend. No QR payload is sent to
* a third-party image service.
*/
(function (global) {
'use strict';
const DEFAULTS = {
apiBase: '/api/egov-login',
buttonText: 'Войти через eGov Mobile',
onSigned: null,
onError: null,
pollIntervalMs: 2000,
};
function mount(options) {
const config = Object.assign({}, DEFAULTS, options || {});
const container = typeof config.container === 'string'
? document.querySelector(config.container)
: config.container;
if (!container) throw new Error('SignWidget: container was not found');
container.replaceChildren();
const root = document.createElement('div');
root.className = 'kazeds-sign-widget';
root.innerHTML = `
<style>
.kazeds-sign-widget{font:14px/1.45 system-ui,-apple-system,sans-serif;color:#172033}
.kazeds-sign-widget button{border:0;border-radius:9px;padding:12px 18px;background:#009fdb;color:#fff;font-weight:650;cursor:pointer}
.kazeds-sign-widget button:disabled{opacity:.55;cursor:wait}
.kazeds-sign-widget .kw-panel{margin-top:12px;padding:16px;border:1px solid #dbe3ed;border-radius:12px;text-align:center;background:#fff}
.kazeds-sign-widget .kw-panel img{display:block;width:260px;height:260px;max-width:100%;margin:12px auto}
.kazeds-sign-widget .kw-error{color:#b42318}.kazeds-sign-widget .kw-status{color:#475467}
.kazeds-sign-widget a{color:#0676a8}
</style>
<button type="button" class="kw-start"></button>
<div class="kw-panel" hidden aria-live="polite"></div>`;
container.append(root);
const button = root.querySelector('.kw-start');
const panel = root.querySelector('.kw-panel');
button.textContent = config.buttonText;
let timer = null;
let active = false;
let requestController = null;
function showError(error) {
panel.hidden = false;
panel.replaceChildren();
const message = document.createElement('p');
message.className = 'kw-error';
message.textContent = error && error.message ? error.message : String(error || 'Login failed');
panel.append(message);
if (typeof config.onError === 'function') config.onError(error);
}
async function jsonRequest(path, options) {
const response = await fetch(config.apiBase.replace(/\/$/, '') + path, Object.assign({
credentials: 'same-origin',
headers: { 'Content-Type': 'application/json' },
}, options || {}));
const body = await response.json().catch(() => ({}));
if (!response.ok) throw new Error(body.error || `Request failed (${response.status})`);
return body;
}
async function poll(session) {
try {
while (active) {
await new Promise((resolve) => { timer = setTimeout(resolve, config.pollIntervalMs); });
if (!active) return;
const state = await jsonRequest('/' + encodeURIComponent(session.clientSessionId), {
method: 'GET',
headers: {},
});
if (state.status === 'completed') {
active = false;
button.disabled = false;
panel.replaceChildren();
const done = document.createElement('p');
done.className = 'kw-status';
done.textContent = 'Подпись получена. Проверка выполняется сайтом.';
panel.append(done);
if (typeof config.onSigned === 'function') await config.onSigned(state);
return;
}
if (state.status === 'expired' || state.status === 'rejected') {
throw new Error(state.status === 'expired' ? 'QR-код истёк. Начните заново.' : 'Подписание отменено.');
}
const status = panel.querySelector('.kw-status');
if (status) status.textContent = state.status === 'scanned'
? 'QR отсканирован. Подтвердите подписание в eGov Mobile…'
: 'Ожидание сканирования в eGov Mobile…';
}
} catch (error) {
active = false;
button.disabled = false;
showError(error);
}
}
async function start() {
if (active) return;
button.disabled = true;
panel.hidden = false;
panel.replaceChildren();
const status = document.createElement('p');
status.className = 'kw-status';
status.textContent = 'Создаём запрос…';
panel.append(status);
requestController = new AbortController();
try {
const session = await jsonRequest('/start', {
method: 'POST',
body: '{}',
signal: requestController.signal,
});
panel.replaceChildren();
const heading = document.createElement('p');
heading.className = 'kw-status';
heading.textContent = 'Откройте eGov Mobile и отсканируйте QR-код';
const image = document.createElement('img');
image.src = session.qrDataUrl;
image.alt = 'eGov QR';
const link = document.createElement('a');
link.href = session.deeplink;
link.textContent = 'Открыть eGov Mobile';
link.rel = 'noopener';
link.target = '_blank';
const progress = document.createElement('p');
progress.className = 'kw-status';
progress.textContent = 'Ожидание сканирования в eGov Mobile…';
panel.append(heading, image, link, progress);
active = true;
poll(session);
} catch (error) {
button.disabled = false;
showError(error);
}
}
button.addEventListener('click', start);
return {
destroy() {
active = false;
clearTimeout(timer);
if (requestController) requestController.abort();
container.replaceChildren();
},
start,
};
}
global.SignWidget = { mount };
})(window);