go-mirea

module
v0.4.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 14, 2026 License: MIT

README

go-mirea

Go Reference CI

Async Go client for Пульса МИРЭА. Порт pymirea.

Зачем: если пишешь Telegram-бот, сервис или CLI для МИРЭА на Go — это избавит от необходимости разбирать Keycloak-флоу и protobuf вручную. Сессии, зашифрованные через go-mirea и через pymirea, полностью совместимы — можно держать оба языка в одной БД.

Статус

v0.4.0 — feature-complete, паритет с pymirea:

  • auth — login через Keycloak SSO + PKCE + 2FA (email_code / MAX / TOTP), refresh tokens, verify session
  • session — extract QR token, mark attendance через HTTP + gRPC SelfApproveAttendance
  • crypto — Fernet-совместимое шифрование cookies (wire-compat с pymirea)
  • breaker — circuit breaker + registry для защиты от flaky МИРЭА
  • grpcweb — низкоуровневые примитивы (varint, framing, unary Call, proto helpers)
  • acs — события турникетов (HumanPassService.GetHumanAcsEvents)
  • grades — БРС, детали посещаемости, расписание занятий
  • esports — киберзона (login + booking REST API)

170 test cases, race-detector clean, CI на Go 1.23 + 1.24.

Известные ограничения:

  • auth.CompleteRequiredActions (~5% edge case после max_account_config) — TODO
  • esports OAuth2 consent page (некоторые юзеры) — TODO
  • Авто-резолв humanID для ACS через UserService.GetMeInfo — TODO

Установка

go get github.com/silverhans/go-mirea@v0.4.0

Быстрый старт

package main

import (
    "context"
    "fmt"
    "log"

    "github.com/silverhans/go-mirea/auth"
    "github.com/silverhans/go-mirea/session"
)

func main() {
    ctx := context.Background()
    a := auth.New()

    result, err := a.Login(ctx, "ivanov.i@edu.mirea.ru", "password123")
    if err != nil {
        log.Fatalf("network error: %v", err)
    }

    // 2FA?
    if !result.Success && result.Challenge != nil {
        fmt.Print("Enter code sent to your email: ")
        var code string
        fmt.Scanln(&code)
        result, err = a.CompleteOTP(ctx, result.Challenge, code)
        if err != nil {
            log.Fatal(err)
        }
    }

    if !result.Success {
        log.Fatalf("login failed: %s", result.Message)
    }

    // Mark attendance via QR
    api := session.NewAPI(session.WithCookies(result.Cookies))
    mark, _ := api.MarkAttendance(ctx, "https://pulse.mirea.ru/selfapprove?token=abc-123")
    fmt.Println(mark.Message)
}

Шифрование сессий (wire-compat с pymirea)

import "github.com/silverhans/go-mirea/crypto"

sc, _ := crypto.New(os.Getenv("SESSION_KEYS"))
blob, _ := sc.EncryptSession(result.Cookies)

// ... save blob to DB ...

cookies, _ := sc.DecryptSession(blob)
// Same blob can be decrypted by pymirea with the same SESSION_KEYS

Архитектура

crypto/    — Fernet encryption + key rotation (wire-compat с pymirea)
breaker/   — circuit breaker state machine + Registry
grpcweb/   — gRPC-Web framing + protobuf wire-format primitives
auth/      — Keycloak SSO login + 2FA + refresh + verify
session/   — QR extraction + mark attendance (HTTP + gRPC)
acs/       — события турникетов (HumanPassService)
grades/    — БРС, детали посещаемости, расписание занятий
esports/   — киберзона (login + booking REST)
examples/  — CLI: cli-mark, cli-schedule

Все модули покрыты тестами на TDD: 170 test cases, CI проверяет каждый PR.

Примеры

См. examples/ — две runnable CLI:

  • examples/cli-mark — отметка через QR (HTTP или gRPC)
  • examples/cli-schedule — расписание на сегодня

Лицензия

MIT © silverhans

Directories

Path Synopsis
Package acs implements the MIREA Pulse access-control-system events API (turnstile entries/exits per day).
Package acs implements the MIREA Pulse access-control-system events API (turnstile entries/exits per day).
Package auth implements the MIREA Keycloak SSO login flow.
Package auth implements the MIREA Keycloak SSO login flow.
Package breaker provides a minimal circuit breaker for flaky upstream services (like MIREA's Keycloak endpoint).
Package breaker provides a minimal circuit breaker for flaky upstream services (like MIREA's Keycloak endpoint).
Package crypto provides Fernet-based encryption for MIREA session cookies.
Package crypto provides Fernet-based encryption for MIREA session cookies.
Package esports implements the MIREA киберзона booking API (esports.mirea.ru).
Package esports implements the MIREA киберзона booking API (esports.mirea.ru).
examples
cli-mark command
cli-mark — CLI to log in and mark attendance with a QR-code URL or token.
cli-mark — CLI to log in and mark attendance with a QR-code URL or token.
cli-schedule command
cli-schedule — CLI to print today's lessons for the logged-in student.
cli-schedule — CLI to print today's lessons for the logged-in student.
Package grades implements the MIREA Pulse БРС (Балльно-Рейтинговая Система) API: subject scores + attendance details.
Package grades implements the MIREA Pulse БРС (Балльно-Рейтинговая Система) API: subject scores + attendance details.
Package grpcweb implements the minimum gRPC-Web primitives needed to talk to pulse.mirea.ru: message framing, varint codec, unary Call helper.
Package grpcweb implements the minimum gRPC-Web primitives needed to talk to pulse.mirea.ru: message framing, varint codec, unary Call helper.
Package session implements the Pulse attendance API surface (QR-token extraction + mark_attendance).
Package session implements the Pulse attendance API surface (QR-token extraction + mark_attendance).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL