APIs and integrations
Single entry point for external LMS, training hubs and testing panel: linking participants, training events, test results, framework synchronization and public endpoints.
1. Authentication
Session + CSRF
Cookie kompetometr_session (HttpOnly) и заголовок X-CSRF-Token для изменяющих запросов. Используется SPA-кабинетом.
HMAC-SHA256
Для внешних систем: X-Kompetometr-Signature: t=...,v1=.... Подписывается timestamp + "." + raw_body.
X-BT360-Signature
Панель использует тот же формат подписи. Legacy X-Panel-Signature поддерживается на старом URL.
canonical = timestamp + "." + raw_body signature = HMAC_SHA256(LEARNING_WEBHOOK_SECRET, canonical) X-Kompetometr-Signature: t=1763300000,v1=<hex>
Секреты задаются только в env: LEARNING_WEBHOOK_SECRET, LEARNING_WEBHOOK_SECRET_PREV, PANEL_WEBHOOK_SECRET. Окно timestamp — 300 секунд. Секреты и тела запросов не логируются.
2. SSO
Login and registration go through Keycloak using OIDC Authorization Code + PKCE. The account does not store the user's password: the password and MFA remain with the IdP. Public SSO endpoints do not require a session cookie and do not accept a CSRF token.
| Method | Endpoint | Purpose |
|---|---|---|
| GET | /api/v1/auth/sso/status | Public status: enabled, provider_name, button_label; without issuer/client_id/secrets |
| GET | /api/v1/auth/sso/start?return_to=/app/… | Creates state/nonce/PKCE, sets HttpOnly state-cookie, 302 on IdP |
| GET | /api/v1/auth/sso/callback?code&state | Checks state, exchanges code, validates id_token, creates a session and 302 to the account |
| GET | /sso/realms/kompetometr/protocol/openid-connect/auth | Keycloak authorization endpoint |
Login flow
Кабинет ведёт на sso/start; создаются state, nonce и PKCE S256.
The user logs in or registers with the IdP; The password does not get into the Kompetometr.
The API checks state, code, issuer and id_token signature; email must be confirmed.
The user contacts by email; an HttpOnly session and a CSRF token are issued.
Registration
Основной путь — Keycloak self-registration. start?register=1 или prompt=register добавляет kc_action=register. После SSO пользователь может создать компанию через POST /api/v1/org/create.
Invitations
Гость проходит SSO с return_to=/app/invite/…®ister=1, затем принимает приглашение через POST /api/v1/org/invitations/{token}/accept. Email сессии должен совпасть с email приглашения.
Configuration
OIDC_ENABLED=true OIDC_ISSUER=https://kompetometr.ru/sso/realms/kompetometr OIDC_CLIENT_ID=kompetometr-lumen OIDC_REDIRECT_URI=https://kompetometr.ru/api/v1/auth/sso/callback OIDC_SCOPES="openid email profile" OIDC_AUTO_PROVISION=false OIDC_REQUIRE_EMAIL_VERIFIED=true
Секрет OIDC_CLIENT_SECRET хранится только в env. issuer сравнивается с claim iss точно; state живёт 10 минут; cookie — HttpOnly, Secure, SameSite=Lax. Ошибки возвращаются редиректом на /app/login?sso_error=<code>, без раскрытия деталей IdP.
Основные ошибки: sso_disabled, invalid_state, invalid_callback, email_unverified, user_not_found, sso_unavailable. Коды start/callback при выключенном SSO возвращают 503.
3. External integration
Базовый путь: /api/v1/integration/v1. Все запросы — POST, Content-Type: application/json, HMAC-подпись, идемпотентность по id события.
| Method | Endpoint | Purpose | Answer |
|---|---|---|---|
| POST | /participants | Привязать external_id внешней системы к пользователю по email | 201 / 200, 409 in case of conflict |
| POST | /learning-events | The course, training or test has been completed; evidence and profile recalculation | 201; 200 duplicate |
| POST | /panel-events | New panel URL, payload and signature are the same | like panel webhook |
Participant linking
POST /api/v1/integration/v1/participants
{
"external_id": "lms-user-1",
"email": "user@example.com"
}Один внешний ID — один пользователь. Повторная привязка того же пользователя к другому ID возвращает 409 participant_conflict. Для панели дополнительно работает существующая связь panel_accounts.external_id.
Training Event
POST /api/v1/integration/v1/learning-events
{
"id": "evt-2026-0001",
"type": "learning.course.completed",
"occurred_at": "2026-11-16T10:00:00Z",
"participant": {"external_id": "lms-user-1"},
"learning": {
"title": "Курс обратной связи",
"provider": "LMS",
"external_id": "course-42",
"url": "https://lms.example/courses/42"
},
"evidence": [
{"competency_code": "PER-01", "level": 3, "confidence": "medium"}
]
}Event Types
learning.course.completed→ sourcecourselearning.training.completed→ sourcetraininglearning.test.completed→ источникtest, нуженlearning.test_codeиresult.score0–100
Idempotency
Повтор с тем же id не создаёт дубль: 200 {"ok":true,"duplicate":true}. Evidence пишется в транзакции вместе с событием; при ошибке откатывается всё.
Evidence is accepted only for code from the currently published framework. Level - 0–5. After the event, the profile is recalculated, and the source is displayed in the account as “course” or “training”.
4. External synchronization mechanism
LMS/panel sends external_id + email.
The course, training or test has been completed with an HMAC signature.
Competency codes are checked against the published version of the framework.
CompetencyScorer recalculates the levels and takes a snapshot.
Ошибки: 401 invalid_signature, 404 participant_not_linked, 422 validation, 409 participant_conflict. Повторные сетевые доставки безопасны.
5. Test panel
| Mechanism | Endpoint/team | Purpose |
|---|---|---|
| Outgoing destinations | POST /api/integration/v1/participants POST /api/integration/v1/assignments | Panel: participants and assignments; platform initiates |
| Launch | POST /api/integration/v1/launch-ticket | One-time launch ticket; panel session |
| New receiver | POST /api/v1/integration/v1/panel-events | Предпочтительный URL; payload и X-BT360-Signature прежние |
| Legacy receiver | POST /api/v1/integration/panel/webhook | Backward Compatibility |
| Reconciliation | php artisan panel:reconcile | Reloading lost results and failed sessions |
События панели: assessment.session.completed, assessment.session.rescored, assessment.session.failed, session.completed, session.failed. Подпись: X-BT360-Signature: t=...,v1=...; legacy X-Panel-Signature + timestamp.
The panel is a test engine only. Organizations, roles, competencies and profiles remain in Kompetometr. The test result does not equal the level: the level is confirmed by behavior.
6. Public endpoints
| Method | Endpoint | Purpose |
|---|---|---|
| GET | /api/v1/health | Health-check, version and revision of the framework |
| GET | /api/v1/plans | Public catalog of tariffs and entitlements |
| POST | /api/v1/auth/login | Login, cookie session, CSRF |
| POST | /api/v1/auth/register-individual /api/v1/auth/register | Legacy registration; main input - SSO |
| POST | /api/v1/auth/accept-invite /api/v1/auth/forgot-password /api/v1/auth/reset-password | Invitation and restoration of access |
| GET | /api/v1/auth/sso/status /api/v1/auth/sso/start /api/v1/auth/sso/callback | OIDC SSO (Keycloak) |
| GET | /api/v1/public/participants | Catalog “Participants”: only opt-in, without email and tokens |
| GET | /api/v1/public/profiles/{token} | JSON public profile by share token |
| GET | /p/{token} | Public profile HTML, noindex/no-referrer |
| GET | /participants/ | SSR page of the “Participants” directory |
| POST | /api/v1/integration/panel/webhook | Legacy webhook panels, HMAC |
7. Cabinet API
Требуется cookie-сессия; изменяющие запросы — X-CSRF-Token. Компанейские разделы требуют company-аккаунт и роль.
User and framework
GET /api/v1/auth/meGET /api/v1/frameworkGET /api/v1/framework/competencies/{code}GET /api/v1/framework/testsGET /api/v1/me/profileGET /api/v1/me/timelineGET /api/v1/users/{id}/profilePATCH /api/v1/me/name
Diagnosis and plans
GET /api/v1/assessmentsGET /api/v1/assessments/{id}POST /api/v1/assessments/selfPOST /api/v1/assessments/{id}/launchPOST /api/v1/assessments/{id}/mock-completeGET/POST /api/v1/me/plansGET/PATCH /api/v1/me/plans/{id}POST/PATCH/DELETE /api/v1/me/plans/{id}/items/{itemId}
Public links and data
GET/POST /api/v1/me/sharesDELETE /api/v1/me/shares/{id}GET /api/v1/me/sessionsDELETE /api/v1/me/sessions/{id}POST /api/v1/me/sessions/revoke-othersGET /api/v1/me/exportGET/POST /api/v1/me/consentsGET/POST/DELETE /api/v1/me/deletion-request
Company
GET /api/v1/org/membersGET /api/v1/org/overviewGET/POST /api/v1/org/invitationsGET/POST /api/v1/org/assignmentsGET /api/v1/org/plansGET /api/v1/org/reports/team.csvGET /api/v1/org/reports/assignments.csvGET /api/v1/org/audit-events
8. Framework synchronization
FRAMEWORK_API=https://competency-tree.ru/api/v1 php api/scripts/sync_framework.php # cron production: 04:17 UTC flock -n /tmp/kompetometr-framework-sync.lock php scripts/sync_framework.php
Sync загружает manifest.json и framework.json, проверяет counts и создаёт новую framework_versions со статусом published. Повтор с тем же revision/hash идемпотентен. Старые версии сохраняются для воспроизводимости.
GET /api/v1/framework — текущая published-версия; /framework/tests — 204 теста, слои и кластеры.
External assignments, launch ticket, incoming results, nightly reconcile. The results update the evidence and profile.
Внешние события курсов/тренингов идут через /learning-events; панель — через /panel-events.
9. Limits and errors
Rate limits
- Integration events - 120/min on IP
- Panel webhook - 120/min per IP
- Public directory - 60/min per IP
- Profile export - 5/10 minutes per user
- Login - 10/min on IP + email
Error codes
401 invalid_signature— HMAC/timestamp404 participant_not_linked409 participant_conflict422 validation/invalid_evidence429+retry_after503 integration_not_configured
Формат ошибок: {"error":"code","message":"..."}. Не логируйте секреты, токены и содержимое тел в своих системах; используйте X-Request-Id для корреляции.