API v1 — maʼlumotnoma
Bu hujjat — har endpointning aniq tavsifi. Boshlash uchun qo'llanma — README.md; xatolar — errors.md; mashina o'qiydigan shartnoma — GET /api/v1/openapi.json (repo da openapi-integrators.json; kod bilan bir xil ekanini CI tekshiradi).
Manzil: https://muhrdor.uz. Hamma so'rov va javob — JSON (Content-Type: application/json), UTF-8. Vaqtlar — ISO 8601, UTC (2026-09-30T10:15:00Z). Baytlar — base64 (*_b64) yoki hex (*_hex).
0. Umumiy qoidalar
Kirish. Xizmat akkaunti (client_id + client_secret, panel «API kalitlari») tokenga almashtiriladi; keyin har so'rovda Authorization: Bearer <access_token>. API tokeni faqat shu hujjatdagi endpointlarni ochadi; boshqa har qanday /api/v1/* → 401 unauthorized.
Huquq. Xizmat akkaunti imzolash uchun kalit egasi imzolagan huquq akti kerak (panel «Huquqlar → Huquq berish → Xizmat akkaunti»). Akt saytlarni va hujjat turlarini nomlaydi; aktdan tashqari har urinish rad etiladi va egasining jurnaliga tushadi.
Xato shakli. Har xato:
{"error": {"code": "policy_denied", "reason": "SYSTEM_NOT_ALLOWED", "message_uz": "…",
"request_id": "…", "detail": "hujjat=didox.uz/xml:report, sayt=didox.uz, ruxsat=my.soliq.uz"}}code barqaror (dasturda shunga tayaning), reason — aniqlashtirish (policy_denied uchun sabab; invalid_request uchun maydon yo'li), message_uz — odam uchun (parse qilinmaydi), request_id — murojaatda ko'rsating, detail — faqat identifikatorlar, hech qachon hujjat mazmuni. retryable faqat signing_failed da.
Chegaralar.
| Nima | Chegara | Oshsa |
|---|---|---|
| Token so'rovi | 30 ta berilgan token/soat va 30 ta noto'g'ri secret/soat — har client_id ga; 100/soat — har IP | 429 too_many_requests |
| Imzolash | daqiqasiga 600 hujjat (so'rov emas), har xizmat akkaunti | 429 + Retry-After (soniya) |
| Bitta so'rov | 200 hujjat, jami 5 MiB (dekodlangan) | 422 invalid_request / document_too_large |
| Token muddati | 1 soat | 401 unauthorized → yangi token |
| Idempotentlik oynasi | 10 daqiqa | — |
1. Token
POST /api/v1/token
Xizmat akkauntining bearer tokeni (OAuth 2.0 client_credentials shakli, JSON tanada). Avtorizatsiya sarlavhasi kerak emas.
So'rov:
| Maydon | Tur | Talab | Izoh |
|---|---|---|---|
grant_type | string | majburiy | faqat "client_credentials" |
client_id | string | majburiy | sa_ + 24 hex |
client_secret | string | majburiy | 1..128 belgi |
Javob 200:
{"access_token": "…43 belgi…", "token_type": "Bearer", "expires_in": 3600}Xatolar: 401 invalid_client (noto'g'ri juftlik; akkaunt yoki mas'ul shaxs o'chirilgan; secret token berilayotgan paytda rotatsiya qilingan), 422 invalid_request (shakl), 429.
Eslatmalar: refresh token yo'q — muddati tugagach yangisini oling; har so'rovga token olmang. Rotatsiya yoki o'chirish barcha tokenlarni darhol o'ldiradi. Har berilgan token mas'ul shaxs jurnalida auth.login {client: "api"} sifatida.
2. Mijozning o'zi
GET /api/v1/client/me
Javob 200:
| Maydon | Izoh |
|---|---|
client_id | akkaunt identifikatori |
name | mas'ul shaxs bergan nom |
org_id | mas'ul shaxsning tashkiloti (akkauntning o'z jurnali shu zanjirda) |
owner_name | mas'ul shaxs ismi (bo'sh bo'lishi mumkin) |
owner_pinfl | mas'ul shaxsning JShShIRi (o'z sertifikati bilan tasdiqlangan bo'lsa; aks holda null) |
expires_at | shu tokenning muddati |
GET /api/v1/client/credentials
Akkaunt imzolashi mumkin bo'lgan kalitlar — har amaldagi akt uchun bitta yozuv (bekor qilingan, muddati o'tgan va hali boshlanmagan aktlar ko'rsatilmaydi). Javob 200: {"credentials": [ … ]}, har element:
| Maydon | Izoh |
|---|---|
credential_id | imzolashda credential_id sifatida |
access | doim "grant" |
grant_ref | akt xeshi (sign.by_grant da ham shu) |
systems | akt saytlari, masalan ["my.soliq.uz"] |
doc_kinds | akt hujjat turlari, masalan ["hisobot", "login"] |
valid_from, valid_to | akt davri (null — chegarasiz) |
label, status | kalit nomi va holati (active bo'lsa imzolaydi) |
org_id, org_name, org_kind | kalit tashkiloti (personal | legal) |
owner_user_id | kalit egasi |
certificate_b64, serial, serial_hex, not_before, not_after, subject_attrs | sertifikat (DER, base64), seriya (o'nlik va hex), muddat, subyekt atributlari [[oid, qiymat], …] |
single_key, single_key_mode | yagona kalit holati (unverified bo'lsa sayt hujjatlari imzolanmaydi — egasi kabinet tekshiruvini o'tkazsin) |
profile, origin | algoritm profili; hsm | imported |
Ro'yxat ma'lumot uchun: hujjat o'tadimi — imzolash paytida aktning o'zi bo'yicha hal bo'ladi.
2a. Ilovani rozilik bilan ulash (ADR-0067)
Sir ko'chirish o'rniga: foydalanuvchi panelda rozilik beradi, ilova token oladi. Ilovani operator ro'yxatga oladi (client_id, client_secret, qaytish manzillari, sayt va hujjat turlari). Oqim — OAuth 2.0 authorization code + PKCE (S256).
1. Foydalanuvchini yuborish (brauzerda):
https://muhrdor.uz/panel/#/ilovalar/ulash?client_id=app_…&redirect_uri=<URL-kodlangan>
&state=<tasodifiy>&code_challenge=<base64url(sha256(code_verifier))>&code_challenge_method=S256code_verifier — 43–128 belgi (A-Z a-z 0-9 - . _ ~), ilovada saqlanadi. Foydalanuvchi kalitlarni va muddatni tanlaydi; qaytadi: redirect_uri?code=…&state=… yoki rad etsa ?error=access_denied&state=…. state ni tekshiring. Kod 5 daqiqa, bir martalik.
2. POST /api/v1/oauth/token — kodni almashtirish:
{"grant_type": "authorization_code", "client_id": "app_…", "client_secret": "as_…",
"code": "…", "code_verifier": "…", "redirect_uri": "https://…"}Javob 200:
{"access_token": "…", "token_type": "Bearer", "expires_in": 3600, "refresh_token": "…",
"connection_id": "…", "owner_pinfl": "30101990000000", "owner_name": "KARIMOVA AZIZA"}3. Yangilash — {"grant_type": "refresh_token", "client_id", "client_secret", "refresh_token"} → xuddi shu javob. Refresh token bir martalik: javobdagi yangisini saqlang, eskisini tashlang. 90 kun ishlatilmasa o'ladi. Ishlatib bo'lingan token qayta kelsa ulanish butunlay bekor qilinadi — ikki jarayon bir tokenni parallel yangilamasin.
4. Token bilan hozirgi API o'zgarishsiz: /client/me, /client/credentials, /signatures/sign — faqat rozilikda tanlangan kalitlar, ilova ro'yxatidagi sayt va tur.
GET /api/v1/client/access
Faqat ulanish tokeni bilan. Kim ulangan va u ilova saytlari uchun qaysi kalitlardan foydalana oladi: o'z kalitlari (access: "owner") va unga amaldagi akt bilan berilganlar (access: "grant", grant_ref, systems, doc_kinds, valid_to). Har chaqiruvda yangidan o'qiladi — bekor qilingan akt keyingi so'rovda yo'q.
{"owner_pinfl": "30101990000000", "owner_name": "KARIMOVA AZIZA", "app": "app_…",
"credentials": [{"credential_id": "…", "access": "grant", "org_name": "STONELINE MCHJ",
"grant_ref": "…", "systems": ["xtrace.aslbelgisi.uz"], "doc_kinds": ["login"], "valid_to": null}]}Bu ro'yxat — «kimga nima ko'rsatish mumkin» uchun. U imzolash huquqi emas: ulanish faqat o'z aktlari bilan imzolaydi (/client/credentials).
POST /api/v1/oauth/verify
Imzoni ilovaning o'z siri bilan tekshirish — kirish hali hech kim ulanmasidan oldin keladi, ilovada token bo'lmaydi. Javob POST /api/v1/signatures/verify niki bilan aynan bir xil (6-bo'lim); hech narsa imzolanmaydi.
{"client_id": "app_…", "client_secret": "as_…", "pkcs7_b64": "<attached PKCS#7>"}Chegara: ilova boshiga soatiga 3000. Kirish uchun qoida: verified, mazmun — o'zingiz bergan bir martalik so'rov, platform_key: true, by_owner: true; checks.revocation revoked yoki suspended bo'lsa rad eting (good va not_checked o'tadi — chaqirib olingan sertifikat bilan platforma o'zi imzolamaydi).
Xatolar: 401 invalid_client — ilova siri noto'g'ri; 400 authorization_invalid — kod yoki token yaroqsiz, reason: code, code_expired, code_verifier, redirect_uri, refresh_token, refresh_expired, connection_revoked (foydalanuvchi uzgan yoki token qayta ishlatilgan — «qayta ulang» deb ko'rsating); 403 connection_required — client/access ni qo'lda ochilgan akkaunt tokeni bilan so'rab bo'lmaydi; uzilgandan keyin access token — 401.
3. Imzolash
POST /api/v1/signatures/sign
Sarlavhalar: Authorization, Content-Type: application/json, Idempotency-Key (xizmat akkaunti uchun majburiy: 8..64 belgi A-Z a-z 0-9 . _ -; har yangi so'rovga yangi).
So'rov:
| Maydon | Tur | Talab | Izoh |
|---|---|---|---|
credential_id | string | majburiy | client/credentials dan |
site | string | amalda majburiy | hujjat qaysi sayt uchun (my.soliq.uz, didox.uz, …); aktda bo'lishi shart, bo'sh — rad |
documents | array | 1..200 | quyida |
page_url | string | ixtiyoriy | https://<site>/… — jurnalga havola sifatida; query tashlanadi; boshqa host — 422 |
confirm_token | string | shaxs sessiyasida, siyosat so'rasa (serverda MUHRDOR_CONFIRMATION=on bo'lsa; standart off — preview confirm: null qaytaradi) | preview bergan tasdiq tokeni (ADR-0061); xizmat akkauntiga tegishli emas |
documents[i]:
| Maydon | Tur | Sukut | Izoh |
|---|---|---|---|
content_b64 | string | — | hujjat baytlari (base64) |
detached | bool | true | true — PKCS#7 da kontent yo'q; false — kontent ichida (attached) |
append_to_b64 | string | — | ikkinchi imzo: mavjud attached PKCS#7; imzolanadigan kontent undan olinadi (content_b64 e'tiborsiz), natija — ikki imzoli PKCS#7 |
external_ref | string | — | sizning identifikatoringiz: ≤64, A-Z a-z 0-9 . _ : / -; javobda qaytadi va jurnalda saqlanadi (shaxsiy ma'lumot yozmang) |
Javob 200: {"results": [ … ]} — har hujjat uchun, index bo'yicha:
| Maydon | Muvaffaqiyat | Rad |
|---|---|---|
index | ✔ | ✔ |
external_ref | ✔ | ✔ |
audit_ref | ✔ (sign.requested yozuvi xeshi) | ✔ (rad yozuvi ham jurnalda) |
doc_class | ✔ (my.soliq.uz/hisobot, didox.uz/factura, xml:<ildiz>, …) | — |
pkcs7_b64 | ✔ DER PKCS#7 (E-IMZO shakli, CA zanjiri bilan) | — |
signature_hex | ✔ xom imzo | — |
signer_serial, signer_serial_hex | ✔ sertifikat seriyasi | — |
error | null | {code, reason, message_uz, request_id, detail} |
Holat kodi. Bir hujjatli so'rovda xato — xatoning o'z HTTP holati (403, 422, 502…). Ko'p hujjatli so'rovda — 200 va har elementda alohida natija yoki error; har hujjat alohida siyosat qarori — biri rad etilsa, boshqalari imzolanadi.
Idempotentlik. Xuddi shu kalit + xuddi shu tana (confirm_token hisobga olinmaydi), 10 daqiqa ichida → birinchi javob (imzo va jurnal yozuvi qaytarilmaydi). Boshqa tana → 422 idempotency_mismatch. Birinchisi hali bajarilayotgan bo'lsa → 409 request_in_progress (bir soniyadan keyin qayta). Xato bilan tugagan so'rov kalitni bo'shatadi. Server imzodan keyin, javobni saqlashdan oldin yiqilsa — kalit 10 daqiqa band, keyingi qayta yuborish ikkinchi imzo bo'ladi (errors.md).
Siyosat (403 policy_denied). Xizmat akkauntida sayt ishonchi yo'q: site akt systems ida bo'lishi va hujjat turi akt doc_kinds ida bo'lishi shart. Tuzilma turlari (xml:<ildiz>, json:<xesh>) faqat aktda aniq nomlangan bo'lsa. Sabablar — errors.md (NO_GRANT, SYSTEM_NOT_ALLOWED, DOC_KIND_NOT_ALLOWED, UNCLASSIFIED_CONTENT, EXPIRED, GRANT_REVOKED, CONSTRAINT_VIOLATED, SINGLE_KEY_UNVERIFIED, …). Platforma aktlari ({"type":"grant",…}) → 422 invalid_request reason: "platform act".
Hujjat turlari (adapterlar).
| Sayt | doc_class turlari |
|---|---|
my.soliq.uz | hisobot, login |
didox.uz | factura, qabul, hujjat, login |
xt-xarid.uz | hash32 |
my.it-park.uz | login |
| boshqa XML/JSON | xml:<ildiz element> / json:<xesh> — akt nomlasa |
Jurnal. Kalit tashkiloti zanjirida: sign.requested {client:"api"} → hsm.sign → sign.completed {client:"api", external_ref?}; rad — sign.denied {client:"api"}. Kalit boshqa tashkilotniki bo'lsa, akkaunt tashkiloti zanjirida sign.by_grant. Mazmun saqlanmaydi: kontent va imzolangan atributlar xeshi, tur, sayt, page_url, hujjat raqami/davri (maydon xaritasidan, summasiz), external_ref, akt havolasi.
POST /api/v1/signatures/preview
ADR-0061. Xuddi sign tanasi (credential_id, site, documents; page_url siz) — javob imzosiz: hujjatlar tasnifi va siyosat qarori. HSM ga tegilmaydi, jurnalga yozilmaydi, bir martalik akt sarflanmaydi; byudjet sign bilan bir xil (hujjat soni).
Javob 200:
| Maydon | Izoh |
|---|---|
allowed | siyosat ruxsat beradimi |
reason, reason_uz, detail | rad bo'lsa — sabab (errors.md jadvali) |
confirm | null yoki {reason, reason_uz, token} — shaxsning tasdig'i kerak: ONE_SHOT (bir martalik akt), BULK (10 dan ko'p hujjat), UNCLASSIFIED_DOC (tuzilma turi, akt *), NEW_SITE_FOR_KEY (kalit shu saytda 30 kunda imzolamagan). token 120 soniya, bir martalik, aynan shu hujjatlarga bog'langan — sign ga confirm_token sifatida |
documents[i] | index, doc_class, generic, size, sha256_prefix, doc_ref — ko'rsatish uchun, mazmunsiz |
key | {label, org_name} |
site | so'rovdagi sayt |
Xizmat akkaunti uchun confirm har doim null — mashina so'ralmaydi; sign tokensiz ishlaydi. Shaxs sessiyasida confirm bor ekan, tokensiz sign → 409 confirmation_required (reason: CONFIRMATION_REQUIRED); boshqa hujjat bilan yoki ikkinchi marta yuborilgan token ham shu javobni oladi.
GET /api/v1/signatures/{audit_ref}?credential_id=<kalit>
Saqlangan natija — audit_ref bo'yicha, faqat shu akkaunt imzolagan bo'lsa. credential_id kalit tashkilotining zanjirini tanlaydi (berilmasa — akkauntning o'z tashkiloti; akt bilan imzo odatda kalit tashkilotida).
Javob 200:
| Maydon | Izoh |
|---|---|
audit_ref | so'rov yozuvi |
completed_ref | sign.completed yozuvi xeshi |
pkcs7_sha256 | PKCS#7 xeshi (faylning o'zi saqlanmaydi — .p7b ni o'zingiz saqlang) |
signature_b64, signed_attrs_der_b64 | imzo va imzolangan atributlar (DER) |
signer_serial, signer_serial_hex | sertifikat seriyasi |
404 not_found — boshqa imzolovchining yozuvi yoki noto'g'ri audit_ref/credential_id.
POST /api/v1/signatures/pkcs7-info
PKCS#7 ni o'qish (tekshiruvsiz): kim, qachon imzolagan. So'rov {"pkcs7_b64": "…"}. Javob:
{"attached": true, "signers": [{"serial_hex": "5a3f…", "subject_x500": "cn=…,serialnumber=…", "signing_time": "2026-09-30T10:15:00+00:00"}]}subject_x500 — E-IMZO uslubidagi k=v,… qator (kichik harflar). 422 cms_invalid — o'qilmadi.
POST /api/v1/signatures/verify
Attached PKCS#7 ni tekshirish: kontent xeshi, imzo, sertifikatning ishonchli markazgacha zanjiri va muddati. Hech narsa imzolanmaydi; akt kerak emas — istalgan xizmat akkaunti tokeni. Soatiga 600 so'rov (429). So'rov {"pkcs7_b64": "…"}. Javob 200:
{
"verified": true,
"reason": null,
"content_b64": "bXVocmRvci1sb2dpbjpzYXl0LnV6OjdmOWMyZTRh",
"signing_time": "2026-11-12T10:15:00Z",
"signer": {
"serial_hex": "5a3f…", "common_name": "KARIMOVA AZIZA", "given_name": "AZIZA",
"surname": "KARIMOVA", "pinfl": "30101990000000", "stir": null, "org_name": null,
"not_before": "2026-01-10T00:00:00Z", "not_after": "2028-01-10T00:00:00Z",
"subject_x500": "cn=…,serialnumber=…", "certificate_b64": "MIID…"
},
"checks": {"digest": true, "signature": true, "certificate": true,
"revocation": "good", "revocation_checked_at": "2026-11-10T03:31:07Z"},
"platform_key": true,
"by_owner": true
}| Maydon | Izoh |
|---|---|
verified | uchala tekshiruv (digest, signature, certificate) o'tdi va sertifikat bekor qilingani ma'lum emas. false bo'lsa signer ga ishonmang |
reason | detached (ichida kontent yo'q), multiple_signers, no_certificate, unsupported_algorithm, digest_mismatch, bad_signature, unknown_issuer, expired, bad_certificate, revoked, suspended |
content_b64 | imzolangan kontent — o'zingiz bergan nonce bilan solishtiring |
signing_time | imzolovchining o'z da'vosi; ishonchli vaqt emas |
signer.stir | korxona sertifikatida bor, jismoniy shaxsnikida null |
checks.revocation | sertifikatning markazdagi holati. CRL/OCSP ishlatilmaydi; Muhrdordagi kalit uchun egasining ERI kabinetidan oxirgi tekshiruvda o'qilgan holat: good, revoked, suspended, expired. Boshqa hollarda not_checked (Muhrdordan tashqari kalit yoki kabinet hali o'qilmagan) |
checks.revocation_checked_at | kabinet oxirgi o'qilgan vaqt. Kabinet 7 kunda bir qayta o'qiladi, ya'ni holat shuncha eski bo'lishi mumkin |
platform_key | kalit Muhrdorda saqlanadi |
by_owner | faqat platform_key uchun: true — kalit egasining o'zi imzolagan; false — akt bo'yicha boshqa shaxs yoki xizmat akkaunti; null — jurnalda yo'q. Kim ekani aytilmaydi |
422 cms_invalid — bu PKCS#7 emas. Jurnalga yozilmaydi.
POST /api/v1/signatures/attach-timestamp
Saytning TSA (RFC 3161) tokenini imzoga qo'shish. So'rov: pkcs7_b64, signer_serial_hex (qaysi imzolovchiga), token_b64. Javob: {"pkcs7_b64": "…"} — id-aa-timeStampToken imzolanmagan atribut sifatida. Kalit ishlatilmaydi, jurnal yozuvi yo'q. 422 signer_not_found, 422 cms_invalid.
4. Shartnoma
GET /api/v1/openapi.json
Ochiq (tokensiz). OpenAPI 3.1, faqat yuqoridagi 7 ta operatsiya. Repo dagi nusxasi docs/api/openapi-integrators.json — kod o'zgarsa CI uni yangilashni talab qiladi.
5. Oqim qisqacha
token ──► client/credentials ──► sign (Idempotency-Key) ──► .p7b saqlash │ │ └── 401 bo'lsa yangi token └── tarmoq uzilsa: XUDDI SHU kalit bilan qayta
Tayyor misol: examples/muhrdor_sign.py (faqat standart kutubxona; partiyalar, kalitni saqlab qayta yuborish, Retry-After).
6. Versiya va o'zgarishlar
/api/v1 — barqaror: maydonlar qo'shilishi mumkin, olib tashlanmaydi va ma'nosi o'zgarmaydi; code lar o'zgarmaydi. Katta o'zgarish — yangi prefiks. O'zgarishlar docs/decisions/ (ADR) va docs/STATUS.md da.
Этот документ — точное описание каждого endpoint. Руководство для начала — README.md; ошибки — errors.md; машиночитаемый контракт — GET /api/v1/openapi.json (в репозитории openapi-integrators.json; совпадение с кодом проверяет CI).
Адрес: https://muhrdor.uz. Все запросы и ответы — JSON (Content-Type: application/json), UTF-8. Время — ISO 8601, UTC (2026-09-30T10:15:00Z). Байты — base64 (*_b64) или hex (*_hex).
0. Общие правила
Вход. Сервисный аккаунт (client_id + client_secret, панель «API-ключи») обменивается на токен; затем в каждом запросе Authorization: Bearer <access_token>. Токен API открывает только endpoint'ы из этого документа; любой другой /api/v1/* → 401 unauthorized.
Право. Чтобы сервисный аккаунт подписывал, нужен акт о предоставлении права, подписанный владельцем ключа (панель «Права → Выдать право → Сервисный аккаунт»). Акт называет сайты и типы документов; любая попытка вне акта отклоняется и попадает в журнал владельца.
Форма ошибки. Каждая ошибка:
{"error": {"code": "policy_denied", "reason": "SYSTEM_NOT_ALLOWED", "message_uz": "…",
"request_id": "…", "detail": "hujjat=didox.uz/xml:report, sayt=didox.uz, ruxsat=my.soliq.uz"}}code стабилен (опирайтесь на него в программе), reason — уточнение (для policy_denied — причина; для invalid_request — путь к полю), message_uz — для человека (не парсится), request_id — указывайте при обращении, detail — только идентификаторы, никогда не содержимое документа. retryable только у signing_failed.
Лимиты.
| Что | Лимит | При превышении |
|---|---|---|
| Запрос токена | 30 выданных токенов/час и 30 неверных secret/час — на каждый client_id; 100/час — на каждый IP | 429 too_many_requests |
| Подписание | 600 документов в минуту (не запросов), на каждый сервисный аккаунт | 429 + Retry-After (секунды) |
| Один запрос | 200 документов, всего 5 MiB (декодированных) | 422 invalid_request / document_too_large |
| Срок токена | 1 час | 401 unauthorized → новый токен |
| Окно идемпотентности | 10 минут | — |
1. Токен
POST /api/v1/token
Bearer-токен сервисного аккаунта (форма OAuth 2.0 client_credentials, в JSON-теле). Заголовок авторизации не нужен.
Запрос:
| Поле | Тип | Требование | Примечание |
|---|---|---|---|
grant_type | string | обязательно | только "client_credentials" |
client_id | string | обязательно | sa_ + 24 hex |
client_secret | string | обязательно | 1..128 символов |
Ответ 200:
{"access_token": "…43 belgi…", "token_type": "Bearer", "expires_in": 3600}Ошибки: 401 invalid_client (неверная пара; аккаунт или ответственное лицо отключены; secret ротирован в момент выдачи токена), 422 invalid_request (форма), 429.
Примечания: refresh token нет — по истечении срока получите новый; не получайте токен на каждый запрос. Ротация или отключение сразу аннулируют все токены. Каждый выданный токен — в журнале ответственного лица как auth.login {client: "api"}.
2. Сам клиент
GET /api/v1/client/me
Ответ 200:
| Поле | Примечание |
|---|---|
client_id | идентификатор аккаунта |
name | название, данное ответственным лицом |
org_id | организация ответственного лица (собственный журнал аккаунта — в этой цепочке) |
owner_name | имя ответственного лица (может быть пустым) |
owner_pinfl | ПИНФЛ ответственного лица (если подтверждён собственным сертификатом; иначе null) |
expires_at | срок действия этого токена |
GET /api/v1/client/credentials
Ключи, которыми аккаунт может подписывать, — одна запись на каждый действующий акт (отозванные, истёкшие и ещё не начавшиеся акты не показываются). Ответ 200: {"credentials": [ … ]}, каждый элемент:
| Поле | Примечание |
|---|---|
credential_id | при подписании — как credential_id |
access | всегда "grant" |
grant_ref | хеш акта (он же в sign.by_grant) |
systems | сайты акта, например ["my.soliq.uz"] |
doc_kinds | типы документов акта, например ["hisobot", "login"] |
valid_from, valid_to | период акта (null — без ограничения) |
label, status | название и состояние ключа (подписывает, если active) |
org_id, org_name, org_kind | организация ключа (personal | legal) |
owner_user_id | владелец ключа |
certificate_b64, serial, serial_hex, not_before, not_after, subject_attrs | сертификат (DER, base64), серийный номер (десятичный и hex), срок, атрибуты субъекта [[oid, qiymat], …] |
single_key, single_key_mode | состояние единственного ключа (при unverified документы сайтов не подписываются — владелец должен пройти проверку в кабинете) |
profile, origin | профиль алгоритма; hsm | imported |
Список — для сведения: пройдёт ли документ, решается в момент подписания по самому акту.
2a. Подключение приложения по согласию (ADR-0067)
Вместо копирования секрета: пользователь даёт согласие в панели, приложение получает токен. Приложение регистрирует оператор (client_id, client_secret, адреса возврата, сайты и типы документов). Процесс — OAuth 2.0 authorization code + PKCE (S256).
1. Направить пользователя (в браузере):
https://muhrdor.uz/panel/#/ilovalar/ulash?client_id=app_…&redirect_uri=<URL-kodlangan>
&state=<tasodifiy>&code_challenge=<base64url(sha256(code_verifier))>&code_challenge_method=S256code_verifier — 43–128 символов (A-Z a-z 0-9 - . _ ~), хранится в приложении. Пользователь выбирает ключи и срок; возвращается: redirect_uri?code=…&state=… или при отказе ?error=access_denied&state=…. Проверьте state. Код — 5 минут, одноразовый.
2. POST /api/v1/oauth/token — обмен кода:
{"grant_type": "authorization_code", "client_id": "app_…", "client_secret": "as_…",
"code": "…", "code_verifier": "…", "redirect_uri": "https://…"}Ответ 200:
{"access_token": "…", "token_type": "Bearer", "expires_in": 3600, "refresh_token": "…",
"connection_id": "…", "owner_pinfl": "30101990000000", "owner_name": "KARIMOVA AZIZA"}3. Обновление — {"grant_type": "refresh_token", "client_id", "client_secret", "refresh_token"} → тот же ответ. Refresh token одноразовый: сохраните новый из ответа, старый выбросьте. Если не использовать 90 дней — перестаёт действовать. Если использованный токен придёт повторно, подключение отзывается полностью — два процесса не должны обновлять один токен параллельно.
4. С токеном текущий API без изменений: /client/me, /client/credentials, /signatures/sign — только ключи, выбранные при согласии, сайты и типы из регистрации приложения.
GET /api/v1/client/access
Только с токеном подключения. Кто подключён и какими ключами он может пользоваться для сайтов приложения: свои ключи (access: "owner") и выданные ему действующим актом (access: "grant", grant_ref, systems, doc_kinds, valid_to). При каждом вызове читается заново — отозванного акта в следующем запросе уже нет.
{"owner_pinfl": "30101990000000", "owner_name": "KARIMOVA AZIZA", "app": "app_…",
"credentials": [{"credential_id": "…", "access": "grant", "org_name": "STONELINE MCHJ",
"grant_ref": "…", "systems": ["xtrace.aslbelgisi.uz"], "doc_kinds": ["login"], "valid_to": null}]}Этот список — для «кому что можно показать». Это не право подписи: подключение подписывает только своими актами (/client/credentials).
POST /api/v1/oauth/verify
Проверка подписи с собственным секретом приложения — вход происходит до того, как кто-либо подключился, токена у приложения ещё нет. Ответ в точности совпадает с ответом POST /api/v1/signatures/verify (раздел 6); ничего не подписывается.
{"client_id": "app_…", "client_secret": "as_…", "pkcs7_b64": "<attached PKCS#7>"}Лимит: 3000 в час на приложение. Правило для входа: verified, содержимое — выданный вами одноразовый запрос, platform_key: true, by_owner: true; если checks.revocation — revoked или suspended, отклоняйте (good и not_checked проходят — отозванным сертификатом платформа сама не подписывает).
Ошибки: 401 invalid_client — неверный секрет приложения; 400 authorization_invalid — код или токен недействителен, reason: code, code_expired, code_verifier, redirect_uri, refresh_token, refresh_expired, connection_revoked (пользователь отключил или токен использован повторно — покажите «подключитесь заново»); 403 connection_required — client/access нельзя запрашивать с токеном аккаунта, созданного вручную; после отключения access token — 401.
3. Подписание
POST /api/v1/signatures/sign
Заголовки: Authorization, Content-Type: application/json, Idempotency-Key (для сервисного аккаунта обязателен: 8..64 символа A-Z a-z 0-9 . _ -; для каждого нового запроса новый).
Запрос:
| Поле | Тип | Требование | Примечание |
|---|---|---|---|
credential_id | string | обязательно | из client/credentials |
site | string | фактически обязательно | для какого сайта документ (my.soliq.uz, didox.uz, …); должен быть в акте, пустой — отказ |
documents | array | 1..200 | ниже |
page_url | string | необязательно | https://<site>/… — в журнал как ссылка; query отбрасывается; другой host — 422 |
confirm_token | string | в сессии человека, если требует политика (если на сервере MUHRDOR_CONFIRMATION=on; по умолчанию off — preview возвращает confirm: null) | токен подтверждения, выданный preview (ADR-0061); к сервисному аккаунту не относится |
documents[i]:
| Поле | Тип | По умолчанию | Примечание |
|---|---|---|---|
content_b64 | string | — | байты документа (base64) |
detached | bool | true | true — в PKCS#7 нет контента; false — контент внутри (attached) |
append_to_b64 | string | — | вторая подпись: существующий attached PKCS#7; подписываемый контент берётся из него (content_b64 игнорируется), результат — PKCS#7 с двумя подписями |
external_ref | string | — | ваш идентификатор: ≤64, A-Z a-z 0-9 . _ : / -; возвращается в ответе и сохраняется в журнале (не пишите персональные данные) |
Ответ 200: {"results": [ … ]} — для каждого документа, по index:
| Поле | Успех | Отказ |
|---|---|---|
index | ✔ | ✔ |
external_ref | ✔ | ✔ |
audit_ref | ✔ (хеш записи sign.requested) | ✔ (запись об отказе тоже в журнале) |
doc_class | ✔ (my.soliq.uz/hisobot, didox.uz/factura, xml:<ildiz>, …) | — |
pkcs7_b64 | ✔ DER PKCS#7 (форма E-IMZO, с цепочкой CA) | — |
signature_hex | ✔ сырая подпись | — |
signer_serial, signer_serial_hex | ✔ серийный номер сертификата | — |
error | null | {code, reason, message_uz, request_id, detail} |
Код состояния. В запросе с одним документом ошибка — собственный HTTP-статус ошибки (403, 422, 502…). В запросе с несколькими документами — 200 и в каждом элементе отдельный результат или error; каждый документ — отдельное решение политики — если один отклонён, остальные подписываются.
Идемпотентность. Тот же ключ + то же тело (confirm_token не учитывается), в течение 10 минут → первый ответ (подпись и запись журнала не повторяются). Другое тело → 422 idempotency_mismatch. Если первый ещё выполняется → 409 request_in_progress (повторите через секунду). Запрос, завершившийся ошибкой, освобождает ключ. Если сервер упадёт после подписи, но до сохранения ответа, — ключ занят 10 минут, следующая повторная отправка станет второй подписью (errors.md).
Политика (403 policy_denied). У сервисного аккаунта нет доверия к сайтам: site должен быть в systems акта, а тип документа — в doc_kinds акта. Структурные типы (xml:<ildiz>, json:<xesh>) — только если явно названы в акте. Причины — errors.md (NO_GRANT, SYSTEM_NOT_ALLOWED, DOC_KIND_NOT_ALLOWED, UNCLASSIFIED_CONTENT, EXPIRED, GRANT_REVOKED, CONSTRAINT_VIOLATED, SINGLE_KEY_UNVERIFIED, …). Акты платформы ({"type":"grant",…}) → 422 invalid_request reason: "platform act".
Типы документов (адаптеры).
| Сайт | Типы doc_class |
|---|---|
my.soliq.uz | hisobot, login |
didox.uz | factura, qabul, hujjat, login |
xt-xarid.uz | hash32 |
my.it-park.uz | login |
| другой XML/JSON | xml:<ildiz element> / json:<xesh> — если назван в акте |
Журнал. В цепочке организации ключа: sign.requested {client:"api"} → hsm.sign → sign.completed {client:"api", external_ref?}; отказ — sign.denied {client:"api"}. Если ключ принадлежит другой организации, в цепочке организации аккаунта — sign.by_grant. Содержимое не хранится: хеш контента и подписанных атрибутов, тип, сайт, page_url, номер/период документа (из карты полей, без сумм), external_ref, ссылка на акт.
POST /api/v1/signatures/preview
ADR-0061. То же тело, что у sign (credential_id, site, documents; без page_url), — ответ без подписи: классификация документов и решение политики. HSM не затрагивается, в журнал не пишется, одноразовый акт не расходуется; бюджет тот же, что у sign (число документов).
Ответ 200:
| Поле | Примечание |
|---|---|
allowed | разрешает ли политика |
reason, reason_uz, detail | при отказе — причина (таблица в errors.md) |
confirm | null или {reason, reason_uz, token} — нужно подтверждение человека: ONE_SHOT (одноразовый акт), BULK (больше 10 документов), UNCLASSIFIED_DOC (структурный тип, акт *), NEW_SITE_FOR_KEY (ключ не подписывал на этом сайте 30 дней). token — 120 секунд, одноразовый, привязан именно к этим документам — в sign как confirm_token |
documents[i] | index, doc_class, generic, size, sha256_prefix, doc_ref — для показа, без содержимого |
key | {label, org_name} |
site | сайт из запроса |
Для сервисного аккаунта confirm всегда null — машину не спрашивают; sign работает без токена. Пока в сессии человека есть confirm, sign без токена → 409 confirmation_required (reason: CONFIRMATION_REQUIRED); токен, отправленный с другим документом или во второй раз, получает тот же ответ.
GET /api/v1/signatures/{audit_ref}?credential_id=<kalit>
Сохранённый результат — по audit_ref, только если подписал этот аккаунт. credential_id выбирает цепочку организации ключа (если не указан — собственная организация аккаунта; подпись по акту обычно в организации ключа).
Ответ 200:
| Поле | Примечание |
|---|---|
audit_ref | запись запроса |
completed_ref | хеш записи sign.completed |
pkcs7_sha256 | хеш PKCS#7 (сам файл не хранится — .p7b сохраняйте сами) |
signature_b64, signed_attrs_der_b64 | подпись и подписанные атрибуты (DER) |
signer_serial, signer_serial_hex | серийный номер сертификата |
404 not_found — запись другого подписанта или неверный audit_ref/credential_id.
POST /api/v1/signatures/pkcs7-info
Чтение PKCS#7 (без проверки): кто и когда подписал. Запрос {"pkcs7_b64": "…"}. Ответ:
{"attached": true, "signers": [{"serial_hex": "5a3f…", "subject_x500": "cn=…,serialnumber=…", "signing_time": "2026-09-30T10:15:00+00:00"}]}subject_x500 — строка k=v,… в стиле E-IMZO (строчные буквы). 422 cms_invalid — не прочитано.
POST /api/v1/signatures/verify
Проверка attached PKCS#7: хеш контента, подпись, цепочка сертификата до доверенного центра и срок действия. Ничего не подписывается; акт не нужен — токен любого сервисного аккаунта. 600 запросов в час (429). Запрос {"pkcs7_b64": "…"}. Ответ 200:
{
"verified": true,
"reason": null,
"content_b64": "bXVocmRvci1sb2dpbjpzYXl0LnV6OjdmOWMyZTRh",
"signing_time": "2026-11-12T10:15:00Z",
"signer": {
"serial_hex": "5a3f…", "common_name": "KARIMOVA AZIZA", "given_name": "AZIZA",
"surname": "KARIMOVA", "pinfl": "30101990000000", "stir": null, "org_name": null,
"not_before": "2026-01-10T00:00:00Z", "not_after": "2028-01-10T00:00:00Z",
"subject_x500": "cn=…,serialnumber=…", "certificate_b64": "MIID…"
},
"checks": {"digest": true, "signature": true, "certificate": true,
"revocation": "good", "revocation_checked_at": "2026-11-10T03:31:07Z"},
"platform_key": true,
"by_owner": true
}| Поле | Примечание |
|---|---|
verified | все три проверки (digest, signature, certificate) пройдены, и об отзыве сертификата не известно. При false не доверяйте signer |
reason | detached (внутри нет контента), multiple_signers, no_certificate, unsupported_algorithm, digest_mismatch, bad_signature, unknown_issuer, expired, bad_certificate, revoked, suspended |
content_b64 | подписанный контент — сравните с выданным вами nonce |
signing_time | заявление самого подписанта; не доверенное время |
signer.stir | есть в сертификате компании, у физического лица — null |
checks.revocation | состояние сертификата в центре. CRL/OCSP не используются; для ключа в Muhrdor — состояние, прочитанное при последней проверке из кабинета ЭЦП владельца: good, revoked, suspended, expired. В остальных случаях not_checked (ключ вне Muhrdor или кабинет ещё не прочитан) |
checks.revocation_checked_at | время последнего чтения кабинета. Кабинет перечитывается раз в 7 дней, то есть состояние может быть настолько устаревшим |
platform_key | ключ хранится в Muhrdor |
by_owner | только для platform_key: true — подписал сам владелец ключа; false — другое лицо или сервисный аккаунт по акту; null — в журнале нет. Кто именно, не сообщается |
422 cms_invalid — это не PKCS#7. В журнал не пишется.
POST /api/v1/signatures/attach-timestamp
Добавление токена TSA (RFC 3161) сайта к подписи. Запрос: pkcs7_b64, signer_serial_hex (какому подписанту), token_b64. Ответ: {"pkcs7_b64": "…"} — id-aa-timeStampToken как неподписанный атрибут. Ключ не используется, записи в журнале нет. 422 signer_not_found, 422 cms_invalid.
4. Контракт
GET /api/v1/openapi.json
Открытый (без токена). OpenAPI 3.1, только 7 операций выше. Копия в репозитории — docs/api/openapi-integrators.json; при изменении кода CI требует её обновить.
5. Процесс кратко
token ──► client/credentials ──► sign (Idempotency-Key) ──► .p7b saqlash │ │ └── 401 bo'lsa yangi token └── tarmoq uzilsa: XUDDI SHU kalit bilan qayta
Готовый пример: examples/muhrdor_sign.py (только стандартная библиотека; пакеты, повторная отправка с сохранением ключа, Retry-After).
6. Версия и изменения
/api/v1 — стабилен: поля могут добавляться, но не удаляются и не меняют смысл; значения code не меняются. Крупное изменение — новый префикс. Изменения — в docs/decisions/ (ADR) и docs/STATUS.md.
This document is the exact description of every endpoint. The getting-started guide is README.md; errors are in errors.md; the machine-readable contract is GET /api/v1/openapi.json (in the repository: openapi-integrators.json; CI checks that it matches the code).
Address: https://muhrdor.uz. Every request and answer is JSON (Content-Type: application/json), UTF-8. Times are ISO 8601, UTC (2026-09-30T10:15:00Z). Bytes are base64 (*_b64) or hex (*_hex).
0. General rules
Sign-in. A service account (client_id + client_secret, panel "API keys") is exchanged for a token; then every request carries Authorization: Bearer <access_token>. An API token opens only the endpoints in this document; any other /api/v1/* → 401 unauthorized.
Permission. To sign, a service account needs a grant act signed by the key owner (panel "Permissions → Grant permission → Service account"). The act names the sites and document kinds; every attempt outside the act is refused and goes into the owner's journal.
Error shape. Every error:
{"error": {"code": "policy_denied", "reason": "SYSTEM_NOT_ALLOWED", "message_uz": "…",
"request_id": "…", "detail": "hujjat=didox.uz/xml:report, sayt=didox.uz, ruxsat=my.soliq.uz"}}code is stable (program against it), reason is a refinement (the reason for policy_denied; the field path for invalid_request), message_uz is for a person (do not parse it), request_id — quote it when you write to support, detail — identifiers only, never document content. retryable is on signing_failed only.
Limits.
| What | Limit | When exceeded |
|---|---|---|
| Token request | 30 issued tokens/hour and 30 wrong secrets/hour — per client_id; 100/hour — per IP | 429 too_many_requests |
| Signing | 600 documents a minute (not requests), per service account | 429 + Retry-After (seconds) |
| One request | 200 documents, 5 MiB in all (decoded) | 422 invalid_request / document_too_large |
| Token lifetime | 1 hour | 401 unauthorized → a new token |
| Idempotency window | 10 minutes | — |
1. Token
POST /api/v1/token
A service account's bearer token (the OAuth 2.0 client_credentials shape, in a JSON body). No authorization header is needed.
Request:
| Field | Type | Required | Note |
|---|---|---|---|
grant_type | string | required | only "client_credentials" |
client_id | string | required | sa_ + 24 hex |
client_secret | string | required | 1..128 characters |
Answer 200:
{"access_token": "…43 belgi…", "token_type": "Bearer", "expires_in": 3600}Errors: 401 invalid_client (wrong pair; the account or its responsible person is disabled; the secret was rotated while the token was being issued), 422 invalid_request (shape), 429.
Notes: there is no refresh token — get a new one when it expires; do not fetch a token per request. A rotation or disabling kills all tokens at once. Every issued token is in the responsible person's journal as auth.login {client: "api"}.
2. The client itself
GET /api/v1/client/me
Answer 200:
| Field | Note |
|---|---|
client_id | the account's identifier |
name | the name given by the responsible person |
org_id | the responsible person's organisation (the account's own journal is in this chain) |
owner_name | the responsible person's name (may be empty) |
owner_pinfl | the responsible person's PINFL (if confirmed with their own certificate; otherwise null) |
expires_at | when this token expires |
GET /api/v1/client/credentials
The keys the account can sign with — one entry per live act (revoked, expired and not-yet-started acts are not shown). Answer 200: {"credentials": [ … ]}, each element:
| Field | Note |
|---|---|
credential_id | used as credential_id when signing |
access | always "grant" |
grant_ref | the act's hash (the same in sign.by_grant) |
systems | the act's sites, for example ["my.soliq.uz"] |
doc_kinds | the act's document kinds, for example ["hisobot", "login"] |
valid_from, valid_to | the act's period (null — unbounded) |
label, status | the key's name and status (it signs when active) |
org_id, org_name, org_kind | the key's organisation (personal | legal) |
owner_user_id | the key owner |
certificate_b64, serial, serial_hex, not_before, not_after, subject_attrs | the certificate (DER, base64), serial (decimal and hex), validity, subject attributes [[oid, qiymat], …] |
single_key, single_key_mode | the single-key status (when unverified, site documents are not signed — the owner must run the portal check) |
profile, origin | the algorithm profile; hsm | imported |
The list is informational: whether a document passes is decided at signing time by the act itself.
2a. Connecting an application by consent (ADR-0067)
Instead of copying a secret: the user consents in the panel and the application gets a token. The application is registered by the operator (client_id, client_secret, return addresses, sites and document kinds). The flow is OAuth 2.0 authorization code + PKCE (S256).
1. Send the user (in the browser):
https://muhrdor.uz/panel/#/ilovalar/ulash?client_id=app_…&redirect_uri=<URL-kodlangan>
&state=<tasodifiy>&code_challenge=<base64url(sha256(code_verifier))>&code_challenge_method=S256code_verifier — 43–128 characters (A-Z a-z 0-9 - . _ ~), kept in the application. The user chooses the keys and the period, and comes back: redirect_uri?code=…&state=…, or on refusal ?error=access_denied&state=…. Check state. The code lives 5 minutes and is single-use.
2. POST /api/v1/oauth/token — exchange the code:
{"grant_type": "authorization_code", "client_id": "app_…", "client_secret": "as_…",
"code": "…", "code_verifier": "…", "redirect_uri": "https://…"}Answer 200:
{"access_token": "…", "token_type": "Bearer", "expires_in": 3600, "refresh_token": "…",
"connection_id": "…", "owner_pinfl": "30101990000000", "owner_name": "KARIMOVA AZIZA"}3. Refreshing — {"grant_type": "refresh_token", "client_id", "client_secret", "refresh_token"} → the same answer. The refresh token is single-use: keep the new one from the answer, discard the old one. Unused for 90 days, it dies. If a used token arrives again, the connection is revoked entirely — two processes must not refresh one token in parallel.
4. With the token the current API is unchanged: /client/me, /client/credentials, /signatures/sign — only the keys chosen at consent, the sites and kinds of the application's registration.
GET /api/v1/client/access
With a connection token only. Who is connected and which keys they can use for the application's sites: their own keys (access: "owner") and those given to them by a live act (access: "grant", grant_ref, systems, doc_kinds, valid_to). It is read afresh on every call — a revoked act is gone on the next request.
{"owner_pinfl": "30101990000000", "owner_name": "KARIMOVA AZIZA", "app": "app_…",
"credentials": [{"credential_id": "…", "access": "grant", "org_name": "STONELINE MCHJ",
"grant_ref": "…", "systems": ["xtrace.aslbelgisi.uz"], "doc_kinds": ["login"], "valid_to": null}]}This list is for "what may be shown to whom". It is not a right to sign: a connection signs only with its own acts (/client/credentials).
POST /api/v1/oauth/verify
Verifying a signature with the application's own secret — sign-in comes before anyone has connected, so the application has no token. The answer is exactly that of POST /api/v1/signatures/verify (section 6); nothing is signed.
{"client_id": "app_…", "client_secret": "as_…", "pkcs7_b64": "<attached PKCS#7>"}Limit: 3000 an hour per application. The rule for sign-in: verified, the content is the one-time challenge you issued, platform_key: true, by_owner: true; refuse when checks.revocation is revoked or suspended (good and not_checked pass — the platform itself does not sign with a revoked certificate).
Errors: 401 invalid_client — the application's secret is wrong; 400 authorization_invalid — the code or token is invalid, reason: code, code_expired, code_verifier, redirect_uri, refresh_token, refresh_expired, connection_revoked (the user disconnected or a token was reused — show "connect again"); 403 connection_required — client/access cannot be requested with the token of a manually created account; after disconnection the access token gets 401.
3. Signing
POST /api/v1/signatures/sign
Headers: Authorization, Content-Type: application/json, Idempotency-Key (required for a service account: 8..64 characters of A-Z a-z 0-9 . _ -; a new one for each new request).
Request:
| Field | Type | Required | Note |
|---|---|---|---|
credential_id | string | required | from client/credentials |
site | string | required in practice | the site the document is for (my.soliq.uz, didox.uz, …); the act must name it, empty — refused |
documents | array | 1..200 | below |
page_url | string | optional | https://<site>/… — goes into the journal as a reference; the query is dropped; another host — 422 |
confirm_token | string | in a person's session, when the policy asks (when the server has MUHRDOR_CONFIRMATION=on; the default is off — preview returns confirm: null) | the confirmation token issued by preview (ADR-0061); does not apply to a service account |
documents[i]:
| Field | Type | Default | Note |
|---|---|---|---|
content_b64 | string | — | the document's bytes (base64) |
detached | bool | true | true — no content inside the PKCS#7; false — content embedded (attached) |
append_to_b64 | string | — | a second signature: an existing attached PKCS#7; the content to sign is taken from it (content_b64 is ignored), the result is a PKCS#7 with two signatures |
external_ref | string | — | your own identifier: ≤64, A-Z a-z 0-9 . _ : / -; echoed back and kept in the journal (do not put personal data in it) |
Answer 200: {"results": [ … ]} — one per document, by index:
| Field | Success | Refusal |
|---|---|---|
index | ✔ | ✔ |
external_ref | ✔ | ✔ |
audit_ref | ✔ (hash of the sign.requested entry) | ✔ (the refusal entry is in the journal too) |
doc_class | ✔ (my.soliq.uz/hisobot, didox.uz/factura, xml:<ildiz>, …) | — |
pkcs7_b64 | ✔ DER PKCS#7 (the E-IMZO shape, with the CA chain) | — |
signature_hex | ✔ the raw signature | — |
signer_serial, signer_serial_hex | ✔ the certificate serial | — |
error | null | {code, reason, message_uz, request_id, detail} |
Status code. In a request of one document an error answers with the error's own HTTP status (403, 422, 502…). In a request of several documents — 200 and each element has its own result or error; each document is a separate policy decision — if one is refused, the others are signed.
Idempotency. The same key + the same body (confirm_token is not counted), within 10 minutes → the first answer (the signature and the journal entry are not repeated). A different body → 422 idempotency_mismatch. If the first is still running → 409 request_in_progress (retry in a second). A request that ended in an error frees the key. If the server dies after signing but before it stores the answer, the key stays busy for 10 minutes and the next retry is a second signature (errors.md).
Policy (403 policy_denied). A service account has no site trust: site must be in the act's systems and the document kind in the act's doc_kinds. Structural kinds (xml:<ildiz>, json:<xesh>) pass only when the act names them explicitly. Reasons — errors.md (NO_GRANT, SYSTEM_NOT_ALLOWED, DOC_KIND_NOT_ALLOWED, UNCLASSIFIED_CONTENT, EXPIRED, GRANT_REVOKED, CONSTRAINT_VIOLATED, SINGLE_KEY_UNVERIFIED, …). Platform acts ({"type":"grant",…}) → 422 invalid_request reason: "platform act".
Document kinds (adapters).
| Site | doc_class kinds |
|---|---|
my.soliq.uz | hisobot, login |
didox.uz | factura, qabul, hujjat, login |
xt-xarid.uz | hash32 |
my.it-park.uz | login |
| other XML/JSON | xml:<ildiz element> / json:<xesh> — when the act names it |
Journal. In the chain of the key's organisation: sign.requested {client:"api"} → hsm.sign → sign.completed {client:"api", external_ref?}; a refusal — sign.denied {client:"api"}. If the key belongs to another organisation, sign.by_grant in the chain of the account's organisation. Content is not stored: hashes of the content and of the signed attributes, the kind, the site, page_url, the document's number/period (from the field map, no amounts), external_ref, the act reference.
POST /api/v1/signatures/preview
ADR-0061. The same body as sign (credential_id, site, documents; without page_url) — the answer has no signature: the documents' classification and the policy decision. The HSM is not touched, nothing is written to the journal, a one-shot act is not spent; the budget is the same as for sign (the number of documents).
Answer 200:
| Field | Note |
|---|---|
allowed | whether the policy allows it |
reason, reason_uz, detail | on refusal — the reason (the table in errors.md) |
confirm | null or {reason, reason_uz, token} — the person's confirmation is needed: ONE_SHOT (a one-shot act), BULK (more than 10 documents), UNCLASSIFIED_DOC (a structural kind, act *), NEW_SITE_FOR_KEY (the key has not signed on this site in 30 days). token lives 120 seconds, is single-use and bound to exactly these documents — pass it to sign as confirm_token |
documents[i] | index, doc_class, generic, size, sha256_prefix, doc_ref — for display, without content |
key | {label, org_name} |
site | the site from the request |
For a service account confirm is always null — a machine is not asked; sign works without a token. While confirm is present in a person's session, sign without a token → 409 confirmation_required (reason: CONFIRMATION_REQUIRED); a token sent with a different document or a second time gets the same answer.
GET /api/v1/signatures/{audit_ref}?credential_id=<kalit>
The stored result — by audit_ref, only if this account signed it. credential_id selects the chain of the key's organisation (if omitted — the account's own organisation; a signature under an act is usually in the key's organisation).
Answer 200:
| Field | Note |
|---|---|
audit_ref | the request entry |
completed_ref | hash of the sign.completed entry |
pkcs7_sha256 | the PKCS#7 hash (the file itself is not stored — keep your .p7b) |
signature_b64, signed_attrs_der_b64 | the signature and the signed attributes (DER) |
signer_serial, signer_serial_hex | the certificate serial |
404 not_found — another signer's entry or a wrong audit_ref/credential_id.
POST /api/v1/signatures/pkcs7-info
Reading a PKCS#7 (without verification): who signed and when. Request {"pkcs7_b64": "…"}. Answer:
{"attached": true, "signers": [{"serial_hex": "5a3f…", "subject_x500": "cn=…,serialnumber=…", "signing_time": "2026-09-30T10:15:00+00:00"}]}subject_x500 — a k=v,… string in the E-IMZO style (lower case). 422 cms_invalid — could not be read.
POST /api/v1/signatures/verify
Verifying an attached PKCS#7: the content hash, the signature, the certificate's chain to a trusted authority and its validity. Nothing is signed; no act is needed — any service account's token. 600 requests an hour (429). Request {"pkcs7_b64": "…"}. Answer 200:
{
"verified": true,
"reason": null,
"content_b64": "bXVocmRvci1sb2dpbjpzYXl0LnV6OjdmOWMyZTRh",
"signing_time": "2026-11-12T10:15:00Z",
"signer": {
"serial_hex": "5a3f…", "common_name": "KARIMOVA AZIZA", "given_name": "AZIZA",
"surname": "KARIMOVA", "pinfl": "30101990000000", "stir": null, "org_name": null,
"not_before": "2026-01-10T00:00:00Z", "not_after": "2028-01-10T00:00:00Z",
"subject_x500": "cn=…,serialnumber=…", "certificate_b64": "MIID…"
},
"checks": {"digest": true, "signature": true, "certificate": true,
"revocation": "good", "revocation_checked_at": "2026-11-10T03:31:07Z"},
"platform_key": true,
"by_owner": true
}| Field | Note |
|---|---|
verified | all three checks (digest, signature, certificate) passed and the certificate is not known to be revoked. When false, do not trust signer |
reason | detached (no content inside), multiple_signers, no_certificate, unsupported_algorithm, digest_mismatch, bad_signature, unknown_issuer, expired, bad_certificate, revoked, suspended |
content_b64 | the signed content — compare it with the nonce you issued |
signing_time | the signer's own claim; not a trusted time |
signer.stir | present in a company certificate, null in an individual's |
checks.revocation | the certificate's status at the authority. CRL/OCSP are not used; for a key in Muhrdor it is the status read at the last check from the owner's e-signature portal: good, revoked, suspended, expired. Otherwise not_checked (a key outside Muhrdor, or the portal has not been read yet) |
checks.revocation_checked_at | when the portal was last read. The portal is re-read once in 7 days, so the status may be that old |
platform_key | the key is kept in Muhrdor |
by_owner | for platform_key only: true — the key owner signed it themselves; false — another person or a service account under an act; null — not in the journal. Who it was is not said |
422 cms_invalid — this is not a PKCS#7. Nothing is written to the journal.
POST /api/v1/signatures/attach-timestamp
Adding the site's TSA (RFC 3161) token to a signature. Request: pkcs7_b64, signer_serial_hex (which signer), token_b64. Answer: {"pkcs7_b64": "…"} — id-aa-timeStampToken as an unsigned attribute. No key is used, there is no journal entry. 422 signer_not_found, 422 cms_invalid.
4. Contract
GET /api/v1/openapi.json
Open (no token). OpenAPI 3.1, only the 7 operations above. The copy in the repository is docs/api/openapi-integrators.json — when the code changes, CI requires it to be updated.
5. The flow in short
token ──► client/credentials ──► sign (Idempotency-Key) ──► .p7b saqlash │ │ └── 401 bo'lsa yangi token └── tarmoq uzilsa: XUDDI SHU kalit bilan qayta
A ready example: examples/muhrdor_sign.py (standard library only; batches, retrying with the key kept, Retry-After).
6. Version and changes
/api/v1 is stable: fields may be added, are never removed and do not change meaning; code values do not change. A major change means a new prefix. Changes are in docs/decisions/ (ADR) and docs/STATUS.md.