litestar-oauth-server 0.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,42 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ .eggs/
6
+
7
+ # Build artifacts
8
+ /dist/
9
+ /build/
10
+ /site/
11
+ /public/
12
+
13
+ # uv / venv
14
+ .venv/
15
+ uv.lock.bak
16
+
17
+ # Tool caches
18
+ .pytest_cache/
19
+ .ruff_cache/
20
+ .pyright/
21
+ .mypy_cache/
22
+ .moon/cache/
23
+
24
+ # Editor
25
+ .vscode/
26
+ .idea/
27
+ *.swp
28
+
29
+ # Local session logs
30
+ logs/
31
+
32
+ # Personal, machine-specific agent overrides (AGENTS.md is tracked)
33
+ AGENTS.local.md
34
+ CLAUDE.local.md
35
+
36
+ # Claude Code: per-machine local settings + worktrees are local; .claude/settings.json IS tracked.
37
+ .claude/settings.local.json
38
+ .claude/worktrees/
39
+
40
+ # Local agent wiring: names cabildo-issues-mcp, which is not a dependency of this
41
+ # package. docs/issues/ IS tracked — the register is plain markdown anyone can read.
42
+ .mcp.json
@@ -0,0 +1,18 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ### Added
11
+
12
+ - Authorization server: authorization code flow with PKCE (S256), refresh token rotation with
13
+ reuse detection, revocation, dynamic client registration, resource indicators.
14
+ - Litestar plugin `LitestarOAuth`: RFC 8414 and RFC 9728 metadata, `/oauth/register`,
15
+ `/oauth/token`, `/oauth/revoke`.
16
+ - `bearer_guard` and `verified_token` for protected routes, with `WWW-Authenticate` on 401.
17
+ - Per-token `binding` (tenant) and scopes the user can narrow on the consent screen.
18
+ - In-memory stores and the `ClientStore`, `CodeStore` and `TokenStore` protocols.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jorge Cardona
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,113 @@
1
+ Metadata-Version: 2.5
2
+ Name: litestar-oauth-server
3
+ Version: 0.0.1
4
+ Summary: An OAuth 2.1 authorization server plugin for Litestar: PKCE, client registration, token and refresh, with MCP-ready metadata
5
+ Project-URL: Homepage, https://gitlab.com/cardona-oss/litestar-oauth-server
6
+ Project-URL: Repository, https://gitlab.com/cardona-oss/litestar-oauth-server
7
+ Project-URL: Documentation, https://cardona-oss.gitlab.io/litestar-oauth-server/
8
+ Project-URL: Changelog, https://gitlab.com/cardona-oss/litestar-oauth-server/-/blob/main/CHANGELOG.md
9
+ Project-URL: Issues, https://gitlab.com/cardona-oss/litestar-oauth-server/-/issues
10
+ Author-email: Jorge Cardona <jorgeecardona@gmail.com>
11
+ License-Expression: MIT
12
+ License-File: LICENSE
13
+ Keywords: authorization-server,litestar,mcp,oauth,oauth2,pkce,plugin
14
+ Classifier: Development Status :: 4 - Beta
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Software Development :: Libraries
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.12
22
+ Requires-Dist: litestar>=2.23
23
+ Provides-Extra: docs
24
+ Requires-Dist: mkdocs-llmstxt>=0.5; extra == 'docs'
25
+ Requires-Dist: mkdocs-material>=9.5; extra == 'docs'
26
+ Requires-Dist: mkdocs>=1.6; extra == 'docs'
27
+ Requires-Dist: mkdocstrings[python]>=0.27; extra == 'docs'
28
+ Description-Content-Type: text/markdown
29
+
30
+ # litestar-oauth-server
31
+
32
+ [![pipeline status](https://gitlab.com/cardona-oss/litestar-oauth-server/badges/main/pipeline.svg)](https://gitlab.com/cardona-oss/litestar-oauth-server/-/pipelines)
33
+ [![PyPI version](https://img.shields.io/pypi/v/litestar-oauth-server.svg)](https://pypi.org/project/litestar-oauth-server/)
34
+ [![Python versions](https://img.shields.io/pypi/pyversions/litestar-oauth-server.svg)](https://pypi.org/project/litestar-oauth-server/)
35
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://gitlab.com/cardona-oss/litestar-oauth-server/-/blob/main/LICENSE)
36
+
37
+ An OAuth 2.1 authorization server plugin for Litestar: PKCE, client registration, token and refresh, with MCP-ready metadata
38
+
39
+ ## Install
40
+
41
+ ```bash
42
+ pip install litestar-oauth-server
43
+ ```
44
+
45
+ Requires Python 3.12+.
46
+
47
+ ## Quickstart
48
+
49
+ ```python
50
+ from litestar import Litestar, Request, get
51
+ from litestar_oauth_server import (
52
+ AuthorizationServer, LitestarOAuth, OAuthConfig, bearer_guard, in_memory_stores, verified_token,
53
+ )
54
+
55
+ RESOURCE = "https://api.example.com/mcp"
56
+
57
+ server = AuthorizationServer(
58
+ config=OAuthConfig(
59
+ issuer="https://api.example.com",
60
+ authorization_endpoint="https://app.example.com/oauth/authorize", # your consent page
61
+ resources=(RESOURCE,),
62
+ scopes_supported=("things:read", "things:write"),
63
+ ),
64
+ stores=in_memory_stores(), # use stores on your own database in production
65
+ )
66
+
67
+ @get("/mcp", guards=[bearer_guard(server, RESOURCE, scope="things:read")])
68
+ async def things(request: Request) -> str:
69
+ token = verified_token(request) # subject, binding, scopes
70
+ return f"hello {token.subject}, pinned to {token.binding}"
71
+
72
+ app = Litestar([things], plugins=[LitestarOAuth(server)])
73
+ ```
74
+
75
+ Your consent page signs the user in with your own login, then calls
76
+ `server.approve(request, Approval(subject=..., scopes=..., binding=...))` and sends the browser to
77
+ the URL it returns. See `examples/basic.py`.
78
+
79
+ ## Why litestar-oauth-server
80
+
81
+ Adding "Connect to Claude", a CLI login or a third-party integration to a Litestar API needs an
82
+ OAuth 2.1 authorization server: PKCE, client registration, token and refresh, discovery documents.
83
+ This library provides that part and leaves the login, the consent screen and the database to your
84
+ app. It is the server side an MCP connector needs, and it works the same for any other client.
85
+
86
+ ## Key features
87
+
88
+ - Authorization code flow with PKCE (S256 only), public clients, refresh token rotation.
89
+ - Server metadata (RFC 8414), protected resource metadata (RFC 9728), dynamic client registration
90
+ (RFC 7591), revocation (RFC 7009), resource indicators (RFC 8707).
91
+ - A `binding` on every token: the tenant chosen on the consent screen. The token never crosses it.
92
+ - Narrow scopes: the user approves a subset of what the client asked for (read-only first).
93
+ - Code and refresh token are single use; a reused refresh token revokes its whole family.
94
+ - A bearer guard that answers 401 with `WWW-Authenticate: Bearer resource_metadata=...`.
95
+ - Frozen dataclasses throughout; storage is three small protocols you implement on your database.
96
+
97
+ ## Links
98
+
99
+ - **Documentation:** https://cardona-oss.gitlab.io/litestar-oauth-server/
100
+ - **Source:** https://gitlab.com/cardona-oss/litestar-oauth-server
101
+ - **Issues:** https://gitlab.com/cardona-oss/litestar-oauth-server/-/issues
102
+ - **PyPI:** https://pypi.org/project/litestar-oauth-server/
103
+ - **Changelog:** [CHANGELOG.md](https://gitlab.com/cardona-oss/litestar-oauth-server/-/blob/main/CHANGELOG.md)
104
+
105
+ ## Contributing
106
+
107
+ Developer setup, the dev loop, and the release process live in
108
+ [CONTRIBUTING.md](https://gitlab.com/cardona-oss/litestar-oauth-server/-/blob/main/CONTRIBUTING.md). In short: `uv sync && make install-hooks`, then
109
+ `make check` runs the same gate CI runs.
110
+
111
+ ## License
112
+
113
+ MIT © 2026 Jorge Cardona (see [LICENSE](https://gitlab.com/cardona-oss/litestar-oauth-server/-/blob/main/LICENSE)).
@@ -0,0 +1,84 @@
1
+ # litestar-oauth-server
2
+
3
+ [![pipeline status](https://gitlab.com/cardona-oss/litestar-oauth-server/badges/main/pipeline.svg)](https://gitlab.com/cardona-oss/litestar-oauth-server/-/pipelines)
4
+ [![PyPI version](https://img.shields.io/pypi/v/litestar-oauth-server.svg)](https://pypi.org/project/litestar-oauth-server/)
5
+ [![Python versions](https://img.shields.io/pypi/pyversions/litestar-oauth-server.svg)](https://pypi.org/project/litestar-oauth-server/)
6
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://gitlab.com/cardona-oss/litestar-oauth-server/-/blob/main/LICENSE)
7
+
8
+ An OAuth 2.1 authorization server plugin for Litestar: PKCE, client registration, token and refresh, with MCP-ready metadata
9
+
10
+ ## Install
11
+
12
+ ```bash
13
+ pip install litestar-oauth-server
14
+ ```
15
+
16
+ Requires Python 3.12+.
17
+
18
+ ## Quickstart
19
+
20
+ ```python
21
+ from litestar import Litestar, Request, get
22
+ from litestar_oauth_server import (
23
+ AuthorizationServer, LitestarOAuth, OAuthConfig, bearer_guard, in_memory_stores, verified_token,
24
+ )
25
+
26
+ RESOURCE = "https://api.example.com/mcp"
27
+
28
+ server = AuthorizationServer(
29
+ config=OAuthConfig(
30
+ issuer="https://api.example.com",
31
+ authorization_endpoint="https://app.example.com/oauth/authorize", # your consent page
32
+ resources=(RESOURCE,),
33
+ scopes_supported=("things:read", "things:write"),
34
+ ),
35
+ stores=in_memory_stores(), # use stores on your own database in production
36
+ )
37
+
38
+ @get("/mcp", guards=[bearer_guard(server, RESOURCE, scope="things:read")])
39
+ async def things(request: Request) -> str:
40
+ token = verified_token(request) # subject, binding, scopes
41
+ return f"hello {token.subject}, pinned to {token.binding}"
42
+
43
+ app = Litestar([things], plugins=[LitestarOAuth(server)])
44
+ ```
45
+
46
+ Your consent page signs the user in with your own login, then calls
47
+ `server.approve(request, Approval(subject=..., scopes=..., binding=...))` and sends the browser to
48
+ the URL it returns. See `examples/basic.py`.
49
+
50
+ ## Why litestar-oauth-server
51
+
52
+ Adding "Connect to Claude", a CLI login or a third-party integration to a Litestar API needs an
53
+ OAuth 2.1 authorization server: PKCE, client registration, token and refresh, discovery documents.
54
+ This library provides that part and leaves the login, the consent screen and the database to your
55
+ app. It is the server side an MCP connector needs, and it works the same for any other client.
56
+
57
+ ## Key features
58
+
59
+ - Authorization code flow with PKCE (S256 only), public clients, refresh token rotation.
60
+ - Server metadata (RFC 8414), protected resource metadata (RFC 9728), dynamic client registration
61
+ (RFC 7591), revocation (RFC 7009), resource indicators (RFC 8707).
62
+ - A `binding` on every token: the tenant chosen on the consent screen. The token never crosses it.
63
+ - Narrow scopes: the user approves a subset of what the client asked for (read-only first).
64
+ - Code and refresh token are single use; a reused refresh token revokes its whole family.
65
+ - A bearer guard that answers 401 with `WWW-Authenticate: Bearer resource_metadata=...`.
66
+ - Frozen dataclasses throughout; storage is three small protocols you implement on your database.
67
+
68
+ ## Links
69
+
70
+ - **Documentation:** https://cardona-oss.gitlab.io/litestar-oauth-server/
71
+ - **Source:** https://gitlab.com/cardona-oss/litestar-oauth-server
72
+ - **Issues:** https://gitlab.com/cardona-oss/litestar-oauth-server/-/issues
73
+ - **PyPI:** https://pypi.org/project/litestar-oauth-server/
74
+ - **Changelog:** [CHANGELOG.md](https://gitlab.com/cardona-oss/litestar-oauth-server/-/blob/main/CHANGELOG.md)
75
+
76
+ ## Contributing
77
+
78
+ Developer setup, the dev loop, and the release process live in
79
+ [CONTRIBUTING.md](https://gitlab.com/cardona-oss/litestar-oauth-server/-/blob/main/CONTRIBUTING.md). In short: `uv sync && make install-hooks`, then
80
+ `make check` runs the same gate CI runs.
81
+
82
+ ## License
83
+
84
+ MIT © 2026 Jorge Cardona (see [LICENSE](https://gitlab.com/cardona-oss/litestar-oauth-server/-/blob/main/LICENSE)).
@@ -0,0 +1,63 @@
1
+ """A Litestar API with an OAuth server and one protected endpoint.
2
+
3
+ Run it with: uv run litestar --app examples.basic:app run
4
+
5
+ The consent page is the host app's job. Here a plain endpoint stands in for it: it receives the
6
+ user's decision and returns the redirect URL carrying the code. In a real app this sits behind
7
+ your own login, and ``subject`` and ``binding`` come from the signed-in user.
8
+ """
9
+
10
+ from dataclasses import dataclass
11
+ from typing import Any
12
+
13
+ from litestar import Litestar, Request, get, post
14
+
15
+ from litestar_oauth_server import (
16
+ Approval,
17
+ AuthorizationRequest,
18
+ AuthorizationServer,
19
+ LitestarOAuth,
20
+ OAuthConfig,
21
+ bearer_guard,
22
+ in_memory_stores,
23
+ verified_token,
24
+ )
25
+
26
+ RESOURCE = "http://localhost:8000/api"
27
+
28
+ server = AuthorizationServer(
29
+ config=OAuthConfig(
30
+ issuer="http://localhost:8000",
31
+ authorization_endpoint="http://localhost:8000/consent",
32
+ resources=(RESOURCE,),
33
+ scopes_supported=("notes:read", "notes:write"),
34
+ resource_name="Notes",
35
+ ),
36
+ stores=in_memory_stores(), # replace with stores on your own database
37
+ )
38
+
39
+
40
+ @dataclass(frozen=True, slots=True)
41
+ class ConsentDecision:
42
+ request: AuthorizationRequest
43
+ scopes: tuple[str, ...]
44
+ company_id: str
45
+
46
+
47
+ @post("/consent", status_code=200)
48
+ async def consent(data: ConsentDecision) -> dict[str, str]:
49
+ # Real app: require a signed-in user, check they may grant access to ``company_id``.
50
+ redirect = await server.approve(
51
+ data.request,
52
+ Approval(subject="user-1", scopes=data.scopes, binding=f"company:{data.company_id}"),
53
+ )
54
+ return {"redirect": redirect}
55
+
56
+
57
+ @get("/api", guards=[bearer_guard(server, RESOURCE, scope="notes:read")], sync_to_thread=False)
58
+ def notes(request: Request[Any, Any, Any]) -> dict[str, str]:
59
+ token = verified_token(request)
60
+ return {"subject": token.subject, "company": token.binding}
61
+
62
+
63
+ app = Litestar([consent, notes], plugins=[LitestarOAuth(server)])
@@ -0,0 +1,116 @@
1
+ [project]
2
+ name = "litestar-oauth-server"
3
+ dynamic = ["version"] # the single source of truth is __version__ in src/litestar_oauth_server/__init__.py (see [tool.hatch.version])
4
+ description = "An OAuth 2.1 authorization server plugin for Litestar: PKCE, client registration, token and refresh, with MCP-ready metadata"
5
+ readme = "README.md"
6
+ requires-python = ">=3.12"
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ authors = [{ name = "Jorge Cardona", email = "jorgeecardona@gmail.com" }]
10
+ keywords = ["litestar", "oauth", "oauth2", "pkce", "mcp", "authorization-server", "plugin"]
11
+ classifiers = [
12
+ "Development Status :: 4 - Beta",
13
+ "Intended Audience :: Developers",
14
+ "Programming Language :: Python :: 3",
15
+ "Programming Language :: Python :: 3.12",
16
+ "Programming Language :: Python :: 3.13",
17
+ "Topic :: Software Development :: Libraries",
18
+ "Typing :: Typed",
19
+ ]
20
+ dependencies = [
21
+ "litestar>=2.23",
22
+ ]
23
+
24
+ [project.optional-dependencies]
25
+ # docs are an *extra* (not a uv dependency-group) so Read the Docs can install them via pip
26
+ docs = [
27
+ "mkdocs>=1.6",
28
+ "mkdocs-material>=9.5",
29
+ "mkdocstrings[python]>=0.27",
30
+ "mkdocs-llmstxt>=0.5",
31
+ ]
32
+
33
+ [project.urls]
34
+ Homepage = "https://gitlab.com/cardona-oss/litestar-oauth-server"
35
+ Repository = "https://gitlab.com/cardona-oss/litestar-oauth-server"
36
+ Documentation = "https://cardona-oss.gitlab.io/litestar-oauth-server/"
37
+ Changelog = "https://gitlab.com/cardona-oss/litestar-oauth-server/-/blob/main/CHANGELOG.md"
38
+ Issues = "https://gitlab.com/cardona-oss/litestar-oauth-server/-/issues"
39
+
40
+ [build-system]
41
+ requires = ["hatchling"]
42
+ build-backend = "hatchling.build"
43
+
44
+ [tool.hatch.version]
45
+ # The version lives as __version__ in the package itself; hatchling reads it (by regex, no import) so
46
+ # pyproject and the runtime never disagree. scripts/bump-version rewrites that literal.
47
+ path = "src/litestar_oauth_server/__init__.py"
48
+
49
+ [tool.hatch.build.targets.wheel]
50
+ packages = ["src/litestar_oauth_server"]
51
+
52
+ [tool.hatch.build.targets.sdist]
53
+ include = ["src", "tests", "examples", "README.md", "CHANGELOG.md", "LICENSE"]
54
+
55
+ [tool.uv]
56
+ # The version is dynamic (hatchling reads __version__ from the file below), so uv must watch it too:
57
+ # declaring cache-keys REPLACES uv's defaults, so pyproject.toml is listed explicitly alongside it.
58
+ # Without __init__.py here, bumping the version would not trigger an editable reinstall.
59
+ cache-keys = [{ file = "pyproject.toml" }, { file = "src/litestar_oauth_server/__init__.py" }]
60
+
61
+ [dependency-groups]
62
+ dev = ["ruff>=0.6", "pyright[nodejs]>=1.1.390", "pytest>=8", "httpx>=0.27"]
63
+
64
+ [tool.pytest.ini_options]
65
+ testpaths = ["tests"]
66
+ addopts = "-q"
67
+ pythonpath = ["."]
68
+
69
+ [tool.ruff]
70
+ line-length = 100
71
+ target-version = "py312"
72
+ src = ["src", "tests"]
73
+
74
+ [tool.ruff.lint]
75
+ select = ["ALL"]
76
+ # The canonical base ignore list shared across the oss/ libraries. E501 (line length) is handled by
77
+ # the formatter; COM812/ISC001 conflict with the formatter; D1/D401 relax docstring presence/mood;
78
+ # TRY003/EM101/EM102 allow inline exception messages; CPY001 drops the copyright-header demand;
79
+ # PLC0415 allows non-top-level imports; TC001/TC002/TC003 don't force type-only import blocks.
80
+ ignore = [
81
+ "E501",
82
+ "COM812",
83
+ "ISC001",
84
+ "D1",
85
+ "D401",
86
+ "TRY003",
87
+ "EM101",
88
+ "EM102",
89
+ "CPY001",
90
+ "PLC0415",
91
+ "TC001",
92
+ "TC002",
93
+ "TC003",
94
+ ]
95
+
96
+ [tool.ruff.lint.pydocstyle]
97
+ convention = "pep257"
98
+
99
+ [tool.ruff.lint.per-file-ignores]
100
+ # Tests may assert (S101), use magic values (PLR2004), take unused fixtures (ARG), pass Any to typed
101
+ # calls (ANN401), and group assertions pytest would otherwise split (PT018).
102
+ "tests/**/*.py" = ["S101", "S105", "S106", "PLR2004", "ARG", "ANN401", "PT018"]
103
+
104
+ # Examples are scripts, not a package.
105
+ "examples/**/*.py" = ["INP001"]
106
+
107
+ [tool.ruff.lint.isort]
108
+ known-first-party = ["litestar_oauth_server"]
109
+
110
+ [tool.pyright]
111
+ include = ["src", "tests", "examples"]
112
+ extraPaths = ["src"]
113
+ pythonVersion = "3.12"
114
+ typeCheckingMode = "strict"
115
+ venvPath = "."
116
+ venv = ".venv"
@@ -0,0 +1,57 @@
1
+ """An OAuth 2.1 authorization server plugin for Litestar."""
2
+
3
+ from litestar_oauth_server.models import (
4
+ Approval,
5
+ AuthorizationRequest,
6
+ CodeRecord,
7
+ GrantSummary,
8
+ OAuthClient,
9
+ OAuthError,
10
+ TokenKind,
11
+ TokenRecord,
12
+ TokenRequest,
13
+ TokenResponse,
14
+ VerifiedToken,
15
+ )
16
+ from litestar_oauth_server.plugin import (
17
+ LitestarOAuth,
18
+ bearer_guard,
19
+ protected_resource_metadata_url,
20
+ verified_token,
21
+ )
22
+ from litestar_oauth_server.server import AuthorizationServer, OAuthConfig
23
+ from litestar_oauth_server.stores import (
24
+ ClientStore,
25
+ CodeStore,
26
+ Stores,
27
+ TokenStore,
28
+ in_memory_stores,
29
+ )
30
+
31
+ __version__ = "0.0.1" # the single source of truth; pyproject reads it via [tool.hatch.version]
32
+
33
+ __all__ = [
34
+ "Approval",
35
+ "AuthorizationRequest",
36
+ "AuthorizationServer",
37
+ "ClientStore",
38
+ "CodeRecord",
39
+ "CodeStore",
40
+ "GrantSummary",
41
+ "LitestarOAuth",
42
+ "OAuthClient",
43
+ "OAuthConfig",
44
+ "OAuthError",
45
+ "Stores",
46
+ "TokenKind",
47
+ "TokenRecord",
48
+ "TokenRequest",
49
+ "TokenResponse",
50
+ "TokenStore",
51
+ "VerifiedToken",
52
+ "__version__",
53
+ "bearer_guard",
54
+ "in_memory_stores",
55
+ "protected_resource_metadata_url",
56
+ "verified_token",
57
+ ]
@@ -0,0 +1,155 @@
1
+ """The data model: every value that crosses the library is a frozen dataclass.
2
+
3
+ Nothing here knows about Litestar or about a database. The stores in ``stores.py`` persist
4
+ these records; the server in ``server.py`` creates and checks them.
5
+
6
+ Vocabulary:
7
+
8
+ - **subject**: the signed-in user who approved the client (the host app's user id, as a string).
9
+ - **binding**: the tenant the token is pinned to, chosen on the consent screen and opaque to
10
+ this library (for example ``"company:7f3a..."``). A token never crosses its binding; the host
11
+ app reads it from the verified token and applies it.
12
+ - **resource**: the canonical URI of the API the token is for (RFC 8707). A token is only valid
13
+ at its own resource.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from dataclasses import dataclass
19
+ from datetime import datetime
20
+ from enum import StrEnum
21
+
22
+
23
+ class TokenKind(StrEnum):
24
+ ACCESS = "access"
25
+ REFRESH = "refresh"
26
+
27
+
28
+ @dataclass(frozen=True, slots=True)
29
+ class OAuthClient:
30
+ """A registered public client (no secret; PKCE is the proof of possession)."""
31
+
32
+ client_id: str
33
+ client_name: str
34
+ redirect_uris: tuple[str, ...]
35
+ created_at: datetime
36
+
37
+
38
+ @dataclass(frozen=True, slots=True)
39
+ class AuthorizationRequest:
40
+ """What the client sent to the authorization endpoint, as the consent page forwards it."""
41
+
42
+ client_id: str
43
+ redirect_uri: str
44
+ code_challenge: str
45
+ code_challenge_method: str
46
+ state: str = ""
47
+ resource: str = ""
48
+ scope: str = ""
49
+
50
+
51
+ @dataclass(frozen=True, slots=True)
52
+ class Approval:
53
+ """The user's decision on the consent screen.
54
+
55
+ ``scopes`` is what the user agreed to; it may be narrower than what the client asked for.
56
+ """
57
+
58
+ subject: str
59
+ scopes: tuple[str, ...]
60
+ binding: str = ""
61
+
62
+
63
+ @dataclass(frozen=True, slots=True)
64
+ class CodeRecord:
65
+ """A single-use authorization code, stored by hash."""
66
+
67
+ code_hash: str
68
+ client_id: str
69
+ redirect_uri: str
70
+ code_challenge: str
71
+ subject: str
72
+ binding: str
73
+ scopes: tuple[str, ...]
74
+ resource: str
75
+ expires_at: datetime
76
+
77
+
78
+ @dataclass(frozen=True, slots=True)
79
+ class TokenRecord:
80
+ """An access or refresh token, stored by hash. ``family_id`` ties a refresh chain together."""
81
+
82
+ token_hash: str
83
+ kind: TokenKind
84
+ family_id: str
85
+ client_id: str
86
+ subject: str
87
+ binding: str
88
+ scopes: tuple[str, ...]
89
+ resource: str
90
+ created_at: datetime
91
+ expires_at: datetime
92
+ used_at: datetime | None = None
93
+ revoked_at: datetime | None = None
94
+
95
+
96
+ @dataclass(frozen=True, slots=True)
97
+ class VerifiedToken:
98
+ """The result of checking a bearer token at a resource."""
99
+
100
+ subject: str
101
+ binding: str
102
+ scopes: tuple[str, ...]
103
+ client_id: str
104
+ resource: str
105
+ expires_at: datetime
106
+
107
+ def has_scope(self, scope: str) -> bool:
108
+ return scope in self.scopes
109
+
110
+
111
+ @dataclass(frozen=True, slots=True)
112
+ class TokenRequest:
113
+ """The form fields of a token endpoint request (RFC 6749 section 4.1.3 and 6)."""
114
+
115
+ grant_type: str = ""
116
+ code: str = ""
117
+ redirect_uri: str = ""
118
+ client_id: str = ""
119
+ code_verifier: str = ""
120
+ resource: str = ""
121
+ refresh_token: str = ""
122
+
123
+
124
+ @dataclass(frozen=True, slots=True)
125
+ class TokenResponse:
126
+ """The token endpoint success body (RFC 6749 section 5.1), snake_case on the wire."""
127
+
128
+ access_token: str
129
+ token_type: str
130
+ expires_in: int
131
+ scope: str
132
+ refresh_token: str
133
+
134
+
135
+ @dataclass(frozen=True, slots=True)
136
+ class GrantSummary:
137
+ """One connected client, for a "connected apps" page where the user can revoke access."""
138
+
139
+ family_id: str
140
+ client_id: str
141
+ client_name: str
142
+ binding: str
143
+ scopes: tuple[str, ...]
144
+ resource: str
145
+ created_at: datetime
146
+
147
+
148
+ class OAuthError(Exception):
149
+ """An RFC 6749 error: ``error`` is a registry value such as ``invalid_grant``."""
150
+
151
+ def __init__(self, error: str, description: str, status: int = 400) -> None:
152
+ super().__init__(f"{error}: {description}")
153
+ self.error = error
154
+ self.description = description
155
+ self.status = status