Skip to main content

s-authkit-contracts — общий язык доступа

Форма X-API-Key, скоупы семейство:*, окно допуска TOTP-кода, статус сессии-владения и канонический in-memory стенд для тестов — то, что должно пониматься ОДИНАКОВО по обе стороны любой границы между authkit-server, authkit-client, leasekit и sessionkit. Ноль зависимостей — только stdlib.

Зачем этот кит

До него форма X-API-Key существовала в трёх несовместимых видах в разных репозиториях портфеля (authkit-server: ak_<key_id>_<secret> + sha256 секрета с O(1)-поиском по key_id; atlas-backend: голый token_urlsafe(32) без префикса, поиск линейным перебором; skillery-backend webhook: HMAC-подпись тела с отдельным заголовком X-Skillery-Key-Id), а has_scope и константа шага TOTP были продублированы независимо внутри одного и того же кита. Этот кит фиксирует форму authkit-server (боевую, уже параметризованную заголовком в servicekit) как контракт — единственный, который остальные обязаны понимать одинаково — без переиздания сервисной логики.

Чем владеет

  • authkit_contracts.apikey — HEADER, PREFIX, HASH_ALGO, PresentedKey, parse_presented/format_presented, hash_secret, структурный ApiKeyRecord (Protocol).
  • authkit_contracts.scopes — has_scope(granted, required).
  • authkit_contracts.totp_window — STEP_SECONDS, DEFAULT_VALID_WINDOW, valid_counters().
  • authkit_contracts.status — Status (live/expired/blocked/ logged_out), is_usable().
  • authkit_contracts.testing — InMemoryApiKeyStore, issued_key().

Чем НЕ владеет

  • Сервисной логикой ключей (issue/verify/revoke, реальный store) — она остаётся в authkit-server, который знает про subject, expires_at, label и конкретную базу данных.
  • HTTP-проводкой (FastAPI dependency, middleware) — она в servicekit.
  • Генерацией и проверкой TOTP-кода (pyotp, base32-секрет) — генерация в totpkit (чужие сервисы: PyPI/Bitrix/GitHub), проверка в authkit-server (свой второй фактор). Здесь только число шага и формула допуска.
  • Здоровьем аккаунта во всей полноте. Status — одна ось (владение сессией прямо сейчас), а не слияние HealthState/SsoState/ AccountAuthState/AccountState/AccessState/LeaseVerdict — они отвечают на разные вопросы и намеренно не сведены в один enum.

Установка

pip install s-authkit-contracts

Импортируется как authkit_contracts. Требуется Python 3.11+.

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

from authkit_contracts import (
    format_presented, parse_presented, hash_secret,
    has_scope, Status, is_usable, InMemoryApiKeyStore, issued_key,
)

# Собрать и разобрать предъявляемую строку.
presented = format_presented("a1b2c3", "секрет")
parsed = parse_presented(presented)          # PresentedKey(key_id='a1b2c3', secret='секрет')
hash_secret(parsed.secret)                    # версионированный sha256

# Скоупы: семейство:* покрывает любое право семейства.
has_scope(["posts:*"], "posts:read")          # True
has_scope(["posts:read"], "posts:write")      # False

# Статус сессии-владения.
is_usable(Status.LIVE)                        # True
is_usable(Status.EXPIRED)                     # False

# Тестовый стенд.
store = InMemoryApiKeyStore()
plaintext = issued_key(store, "totp:read")    # готовая строка для X-API-Key

Разработка

uv sync
uv run pytest -q
uv run ruff check .
uv run --with import-linter lint-imports

Metadata

Release files for s-authkit-contracts 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for s-authkit-contracts 0.1.0
File Size Uploaded Provenance Actions
s_authkit_contracts-0.1.0.tar.gz 23.7 kB Without provenance Details for s_authkit_contracts-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for s-authkit-contracts 0.1.0
File Interpreter ABI Platform Actions
s_authkit_contracts-0.1.0-py3-none-any.whl Python 3 none any Details for s_authkit_contracts-0.1.0-py3-none-any.whl

Total release size: 38.4 kB

Release files / s_authkit_contracts-0.1.0.tar.gz

Download URL s_authkit_contracts-0.1.0.tar.gz
Size 23.7 kB
Tags Source
SHA-256 checksum
How to use checksums
d2980c8722a0e829f6bbb33d1971e89232e44ad4b6cf84731388d4191a5611ef
BLAKE2b-256 checksum
How to use checksums
f0be4d881243e7752302b02e4b4ca243f093e482c8f15a725cd9b3eab0f28a47
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.9.30 {"installer":{"name":"uv","version":"0.9.30","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Debian GNU/Linux","version":"12","id":"bookworm","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / s_authkit_contracts-0.1.0-py3-none-any.whl

Download URL s_authkit_contracts-0.1.0-py3-none-any.whl
Size 14.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
1e247e557066cc7587a8e40f21d4b1362a5ff564296b7226986c566206cc9f1d
BLAKE2b-256 checksum
How to use checksums
7807d058ec53173bb0a63f7cca1fcd079ac0ea322313998b58228c9b7d5e627e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.9.30 {"installer":{"name":"uv","version":"0.9.30","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Debian GNU/Linux","version":"12","id":"bookworm","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for s-authkit-contracts 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page