aiohttp-tiny-mcp 0.5.6__tar.gz → 0.5.8__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.
Files changed (62) hide show
  1. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/PKG-INFO +1 -1
  2. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/pyproject.toml +1 -1
  3. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/pyproject.toml.orig +1 -1
  4. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/__init__.py +9 -0
  5. aiohttp_tiny_mcp-0.5.8/src/aiohttp_tiny_mcp/client/callback.py +113 -0
  6. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/client/http.py +62 -10
  7. aiohttp_tiny_mcp-0.5.8/src/aiohttp_tiny_mcp/client/loopback.py +107 -0
  8. aiohttp_tiny_mcp-0.5.8/src/aiohttp_tiny_mcp/client/oauth.py +674 -0
  9. aiohttp_tiny_mcp-0.5.8/src/aiohttp_tiny_mcp/client/oauth_helpers.py +96 -0
  10. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/protocol/adapter.py +16 -1
  11. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/protocol/models.py +11 -0
  12. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/protocol/v2024_11_05.py +2 -2
  13. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/protocol/v2025_03_26.py +2 -2
  14. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/protocol/v2025_11_25.py +1 -1
  15. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/protocol/v2026_07_28.py +1 -1
  16. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/server/exchange.py +2 -2
  17. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/server/http.py +47 -11
  18. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/server/specs.py +11 -1
  19. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/server/sse.py +4 -2
  20. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/server/stdio.py +7 -5
  21. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/transport/sse.py +3 -2
  22. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/LICENSE +0 -0
  23. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/README.md +0 -0
  24. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/auth/__init__.py +0 -0
  25. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/auth/jwt.py +0 -0
  26. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/client/__init__.py +0 -0
  27. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/client/base.py +0 -0
  28. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/client/stdio.py +0 -0
  29. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/console/__init__.py +0 -0
  30. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/console/console.css +0 -0
  31. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/console/console.js +0 -0
  32. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/console/index.html +0 -0
  33. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/console/oauth-callback.html +0 -0
  34. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/extensions/__init__.py +0 -0
  35. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/extensions/skills.py +0 -0
  36. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/oauth/__init__.py +0 -0
  37. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/oauth/github.py +0 -0
  38. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/oauth/provider.py +0 -0
  39. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/oauth/server.py +0 -0
  40. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/oauth/tokens.py +0 -0
  41. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/protocol/__init__.py +0 -0
  42. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/protocol/core.py +0 -0
  43. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/protocol/schema.py +0 -0
  44. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/protocol/selection.py +0 -0
  45. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/protocol/v2025_06_18.py +0 -0
  46. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/py.typed +0 -0
  47. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/server/__init__.py +0 -0
  48. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/server/dispatcher.py +0 -0
  49. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/server/registry.py +0 -0
  50. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/server/request_state.py +0 -0
  51. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/server/subscriptions.py +0 -0
  52. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/server/tasks.py +0 -0
  53. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/storage/__init__.py +0 -0
  54. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/storage/hub.py +0 -0
  55. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/storage/namespaces.py +0 -0
  56. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/storage/postgres.py +0 -0
  57. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/storage/redis.py +0 -0
  58. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/storage/sessions.py +0 -0
  59. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/storage/sqlite.py +0 -0
  60. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/testing.py +0 -0
  61. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/transport/__init__.py +0 -0
  62. {aiohttp_tiny_mcp-0.5.6 → aiohttp_tiny_mcp-0.5.8}/src/aiohttp_tiny_mcp/transport/metadata.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aiohttp-tiny-mcp
3
- Version: 0.5.6
3
+ Version: 0.5.8
4
4
  Summary: Remote MCP server and client library for aiohttp
5
5
  License-Expression: Apache-2.0
6
6
  License-File: LICENSE
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "aiohttp-tiny-mcp"
3
- version = "0.5.6"
3
+ version = "0.5.8"
4
4
  description = "Remote MCP server and client library for aiohttp"
5
5
  readme = "README.md"
6
6
  license = "Apache-2.0"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "aiohttp-tiny-mcp"
3
- version = "0.5.6"
3
+ version = "0.5.8"
4
4
  description = "Remote MCP server and client library for aiohttp"
5
5
  readme = "README.md"
6
6
  license = "Apache-2.0"
@@ -14,7 +14,10 @@ from .auth import (
14
14
  principal_from_claims,
15
15
  )
16
16
  from .client.base import ClientError, Elicitor
17
+ from .client.callback import OAuthCallback
17
18
  from .client.http import Client
19
+ from .client.loopback import LoopbackCallback
20
+ from .client.oauth import AuthorizationRequired, OAuth, OAuthError, RegistrationRequired
18
21
  from .client.stdio import StdioClient
19
22
  from .extensions import Extension
20
23
  from .protocol.core import (
@@ -55,6 +58,12 @@ from .transport.sse import SSEResponse
55
58
 
56
59
  __all__ = [
57
60
  "AdapterSet",
61
+ "OAuth",
62
+ "OAuthError",
63
+ "OAuthCallback",
64
+ "LoopbackCallback",
65
+ "AuthorizationRequired",
66
+ "RegistrationRequired",
58
67
  "Answer",
59
68
  "AnswerAction",
60
69
  "AudioContent",
@@ -0,0 +1,113 @@
1
+ """OAuth callbacks for an existing aiohttp application."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import hmac
7
+ from collections.abc import Sequence
8
+
9
+ from aiohttp import web
10
+ from yarl import URL
11
+
12
+ from .oauth import AuthorizationAttempt, OAuth
13
+ from .oauth_helpers import OAuthError
14
+
15
+ SUCCESS_HTML = """<!doctype html>
16
+ <html lang="en"><meta charset="utf-8"><title>Authorization complete</title>
17
+ <h1>Authorization complete</h1><p>You can close this window.</p></html>"""
18
+
19
+
20
+ class OAuthCallback:
21
+ """Mount a local or remote callback for one OAuth account context.
22
+
23
+ The application must authenticate the user before calling ``begin`` and
24
+ keep each user's context separate. The external HTTPS ``auth.redirect_uri``
25
+ can differ from the listener address behind a trusted reverse proxy.
26
+ """
27
+
28
+ def __init__(self, auth: OAuth, *, success_html: str = SUCCESS_HTML) -> None:
29
+ self.auth = auth
30
+ self.success_html = success_html
31
+ self.attempt: AuthorizationAttempt | None = None
32
+ self.outcome: asyncio.Future[Exception | None] | None = None
33
+
34
+ def routes(self) -> list[web.RouteDef]:
35
+ """Return the GET route at the path of the configured redirect URI."""
36
+ return [web.get(URL(self.auth.redirect_uri).path, self.handle)]
37
+
38
+ def setup(self, app: web.Application) -> None:
39
+ """Mount the callback on an existing application."""
40
+ app.add_routes(self.routes())
41
+
42
+ async def begin(self, *, scopes: Sequence[str] | None = None) -> AuthorizationAttempt:
43
+ """Prepare the URL to which the application redirects its signed-in user."""
44
+ self.cancel()
45
+ self.attempt = await self.auth.begin(scopes=scopes)
46
+ self.outcome = asyncio.get_running_loop().create_future()
47
+ return self.attempt
48
+
49
+ async def wait(self) -> None:
50
+ """Wait for token acquisition and persistence, or raise their error."""
51
+ if self.outcome is None:
52
+ raise RuntimeError("Start an authorization attempt first.")
53
+ error = await asyncio.shield(self.outcome)
54
+ if error is not None:
55
+ raise error
56
+
57
+ def cancel(self) -> None:
58
+ """Cancel a pending callback without changing existing credentials."""
59
+ if self.attempt is not None:
60
+ self.auth.cancel(self.attempt)
61
+ self.attempt = None
62
+ if self.outcome is not None and not self.outcome.done():
63
+ self.outcome.set_result(OAuthError("Authorization was cancelled."))
64
+
65
+ async def handle(self, request: web.Request) -> web.Response:
66
+ """Exchange the callback code before sending the result page."""
67
+ attempt, outcome = self.attempt, self.outcome
68
+ states = request.query.getall("state", [])
69
+ expected_state = URL(attempt.url).query["state"] if attempt is not None else ""
70
+ if (
71
+ attempt is None
72
+ or outcome is None
73
+ or outcome.done()
74
+ or len(states) != 1
75
+ or not hmac.compare_digest(states[0].encode(), expected_state.encode())
76
+ ):
77
+ return self.response(False, "No matching authorization attempt.")
78
+ self.attempt = None
79
+ # Use the configured public URI, not an untrusted Host or Forwarded header.
80
+ callback_url = self.auth.redirect_uri + "?" + request.rel_url.raw_query_string
81
+ try:
82
+ await self.auth.complete(attempt, callback_url)
83
+ except asyncio.CancelledError:
84
+ if not outcome.done():
85
+ outcome.set_result(OAuthError("The callback request was cancelled."))
86
+ raise
87
+ except Exception as error:
88
+ if not outcome.done():
89
+ outcome.set_result(error)
90
+ return self.response(False, "Authorization failed. Return to the application.")
91
+ if outcome.done():
92
+ return self.response(False, "Authorization was cancelled.")
93
+ outcome.set_result(None)
94
+ return self.response(True, self.success_html)
95
+
96
+ @staticmethod
97
+ def response(success: bool, text: str) -> web.Response:
98
+ return web.Response(
99
+ status=200 if success else 400,
100
+ text=text,
101
+ content_type="text/html" if success else "text/plain",
102
+ headers={
103
+ "Cache-Control": "no-store",
104
+ "Referrer-Policy": "no-referrer",
105
+ "Content-Security-Policy": (
106
+ "default-src 'none'; style-src 'unsafe-inline'; "
107
+ "img-src data: https:; frame-ancestors 'none'"
108
+ ),
109
+ },
110
+ )
111
+
112
+
113
+ __all__ = ["OAuthCallback", "SUCCESS_HTML"]
@@ -5,6 +5,7 @@ from __future__ import annotations
5
5
  import json
6
6
  import logging
7
7
  from collections.abc import AsyncIterator, Callable, Mapping
8
+ from contextlib import asynccontextmanager
8
9
  from typing import Any
9
10
 
10
11
  import aiohttp
@@ -14,6 +15,7 @@ from aiohttp_tiny_mcp.protocol.models import Implementation
14
15
  from aiohttp_tiny_mcp.transport.sse import read_sse
15
16
 
16
17
  from .base import BaseClient, Elicitor
18
+ from .oauth import OAuth, OAuthError
17
19
 
18
20
  ANSWER_METHOD = "elicitation/create"
19
21
 
@@ -42,6 +44,7 @@ class Client(BaseClient):
42
44
  *,
43
45
  client_info: Implementation | None = None,
44
46
  session: aiohttp.ClientSession | None = None,
47
+ auth: OAuth | None = None,
45
48
  on_ask: Elicitor | None = None,
46
49
  on_notification: Callable[[Mapping[str, Any]], Any] | None = None,
47
50
  log_level: str | None = None,
@@ -56,15 +59,64 @@ class Client(BaseClient):
56
59
  self.base_url = base_url
57
60
  self.session = session
58
61
  self.owns_session = session is None
62
+ self.auth = auth
63
+ if auth is not None:
64
+ auth.check_endpoint(base_url)
59
65
  #: The id of the last event read from the notification stream.
60
66
  self.last_event_id: str | None = None
61
67
  self.session_id: str | None = None
62
68
 
63
69
  async def __aenter__(self) -> Client:
70
+ self.check_auth()
64
71
  if self.owns_session:
65
72
  self.session = aiohttp.ClientSession()
66
73
  return self
67
74
 
75
+ def check_auth(self) -> None:
76
+ if self.auth is not None:
77
+ self.auth.check_endpoint(self.base_url)
78
+ if self.auth is not None and self.session is not None:
79
+ if "Authorization" in self.session.headers or self.session.auth is not None:
80
+ raise ValueError("OAuth cannot be combined with session Authorization or auth.")
81
+
82
+ @asynccontextmanager
83
+ async def http_request(
84
+ self, method: str, *, headers: dict[str, str], **kwargs: Any
85
+ ) -> AsyncIterator[aiohttp.ClientResponse]:
86
+ assert self.session is not None, "use 'async with Client(...) as client:'"
87
+ if self.auth is None:
88
+ async with self.session.request(
89
+ method, self.base_url, headers=headers, **kwargs
90
+ ) as resp:
91
+ yield resp
92
+ return
93
+ self.check_auth()
94
+ token = await self.auth.token()
95
+ for attempt in range(2):
96
+ async with self.session.request(
97
+ method,
98
+ self.base_url,
99
+ headers={**headers, "Authorization": f"Bearer {token}"},
100
+ allow_redirects=False,
101
+ **kwargs,
102
+ ) as resp:
103
+ if 300 <= resp.status < 400:
104
+ raise OAuthError("Authenticated MCP requests must not follow redirects.")
105
+ if resp.status in {401, 403}:
106
+ challenge = self.auth.observe(resp.headers.getall("WWW-Authenticate", []))
107
+ if resp.status == 403:
108
+ if challenge.get("error") != "insufficient_scope":
109
+ raise OAuthError("The MCP server denied access (HTTP 403).")
110
+ raise self.auth.authorization_required()
111
+ if attempt:
112
+ await self.auth.invalidate(token)
113
+ raise self.auth.authorization_required()
114
+ else:
115
+ yield resp
116
+ return
117
+ # Release the response before refreshing, including with a one-slot connector.
118
+ token = await self.auth.token(rejected=token)
119
+
68
120
  async def __aexit__(self, *exc: object) -> None:
69
121
  if self.owns_session and self.session is not None:
70
122
  await self.session.close()
@@ -100,8 +152,8 @@ class Client(BaseClient):
100
152
  assert self.session is not None, "use 'async with Client(...) as client:'"
101
153
  tool = self.tool_definitions.get(name) if name is not None else None
102
154
  params = envelope.get("params")
103
- async with self.session.post(
104
- self.base_url, json=envelope, headers=self.headers(method, name, params, tool)
155
+ async with self.http_request(
156
+ "POST", json=envelope, headers=self.headers(method, name, params, tool)
105
157
  ) as resp:
106
158
  if not self.lost_session(resp):
107
159
  self.adopt(resp)
@@ -110,8 +162,8 @@ class Client(BaseClient):
110
162
  return
111
163
  # Retry once on a fresh session; a second 404 is reported as any other reply.
112
164
  await self.reopen()
113
- async with self.session.post(
114
- self.base_url, json=envelope, headers=self.headers(method, name, params, tool)
165
+ async with self.http_request(
166
+ "POST", json=envelope, headers=self.headers(method, name, params, tool)
115
167
  ) as resp:
116
168
  self.adopt(resp)
117
169
  async for frame in frames(resp):
@@ -126,15 +178,15 @@ class Client(BaseClient):
126
178
  async def send_notification(self, envelope: dict[str, Any], *, method: str) -> None:
127
179
  assert self.session is not None, "use 'async with Client(...) as client:'"
128
180
  params = envelope.get("params")
129
- async with self.session.post(
130
- self.base_url, json=envelope, headers=self.headers(method, params=params)
181
+ async with self.http_request(
182
+ "POST", json=envelope, headers=self.headers(method, params=params)
131
183
  ) as resp:
132
184
  if not self.lost_session(resp):
133
185
  await resp.read()
134
186
  return
135
187
  await self.reopen()
136
- async with self.session.post(
137
- self.base_url, json=envelope, headers=self.headers(method, params=params)
188
+ async with self.http_request(
189
+ "POST", json=envelope, headers=self.headers(method, params=params)
138
190
  ) as resp:
139
191
  await resp.read()
140
192
 
@@ -147,7 +199,7 @@ class Client(BaseClient):
147
199
  headers["Accept"] = "text/event-stream"
148
200
  if last_event_id is not None:
149
201
  headers["Last-Event-ID"] = last_event_id
150
- async with self.session.get(self.base_url, headers=headers) as resp:
202
+ async with self.http_request("GET", headers=headers) as resp:
151
203
  resp.raise_for_status()
152
204
  async for event in read_sse(resp):
153
205
  if event.id is not None:
@@ -159,5 +211,5 @@ class Client(BaseClient):
159
211
  """Send a bare JSON-RPC response. The hub routes it to the node waiting for the answer."""
160
212
  assert self.session is not None, "use 'async with Client(...) as client:'"
161
213
  headers = self.headers(ANSWER_METHOD)
162
- async with self.session.post(self.base_url, json=envelope, headers=headers) as resp:
214
+ async with self.http_request("POST", json=envelope, headers=headers) as resp:
163
215
  await resp.read()
@@ -0,0 +1,107 @@
1
+ """Optional browser and loopback callback helper for native applications."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import webbrowser
7
+ from collections.abc import Awaitable, Callable, Sequence
8
+
9
+ from aiohttp import web
10
+ from yarl import URL
11
+
12
+ from .callback import SUCCESS_HTML, OAuthCallback
13
+ from .oauth import OAuth
14
+ from .oauth_helpers import OAuthError
15
+
16
+
17
+ class LoopbackCallback:
18
+ """Run the aiohttp callback on 127.0.0.1 and optionally open a browser.
19
+
20
+ Enter this context before constructing OAuth, then call ``login(auth)``.
21
+ Register ``redirect_uri`` with the authorization server, or use DCR. A fixed
22
+ port can be supplied for pre-registered clients. By default, the operating
23
+ system selects a free port. ``success_html`` is trusted
24
+ application HTML, served unchanged only after the token exchange and save.
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ *,
30
+ port: int = 0,
31
+ timeout: float = 300,
32
+ open_browser: Callable[[str], Awaitable[None]] | None = None,
33
+ success_html: str = SUCCESS_HTML,
34
+ ) -> None:
35
+ if timeout <= 0:
36
+ raise ValueError("The callback timeout must be positive.")
37
+ self.port = port
38
+ self.timeout = timeout
39
+ self.open_browser = open_browser
40
+ self.success_html = success_html
41
+ self.runner: web.AppRunner | None = None
42
+ self.callback_uri: str | None = None
43
+ self.callback: OAuthCallback | None = None
44
+
45
+ @property
46
+ def redirect_uri(self) -> str:
47
+ if self.callback_uri is None:
48
+ raise RuntimeError("Enter the LoopbackCallback context first.")
49
+ return self.callback_uri
50
+
51
+ async def __aenter__(self) -> LoopbackCallback:
52
+ if self.runner is not None:
53
+ raise RuntimeError("The callback listener is already open.")
54
+ app = web.Application()
55
+ app.router.add_get("/callback", self.handle)
56
+ runner = web.AppRunner(app, access_log=None)
57
+ await runner.setup()
58
+ try:
59
+ await web.TCPSite(runner, "127.0.0.1", self.port).start()
60
+ except BaseException:
61
+ await runner.cleanup()
62
+ raise
63
+ self.runner = runner
64
+ port = runner.addresses[0][1]
65
+ self.callback_uri = f"http://127.0.0.1:{port}/callback"
66
+ return self
67
+
68
+ async def __aexit__(self, *exc: object) -> None:
69
+ if self.callback is not None:
70
+ self.callback.cancel()
71
+ if self.runner is not None:
72
+ await self.runner.cleanup()
73
+ self.runner = None
74
+ self.callback_uri = None
75
+
76
+ async def login(self, auth: OAuth, *, scopes: Sequence[str] | None = None) -> None:
77
+ """Open the browser and wait until the token exchange and save finish."""
78
+ if auth.redirect_uri != self.redirect_uri:
79
+ raise ValueError("OAuth uses another callback URI.")
80
+ if self.callback is not None:
81
+ raise RuntimeError("A browser authorization is already in progress.")
82
+ callback = OAuthCallback(auth, success_html=self.success_html)
83
+ self.callback = callback
84
+ try:
85
+ attempt = await callback.begin(scopes=scopes)
86
+
87
+ async def interact() -> None:
88
+ if self.open_browser is not None:
89
+ await self.open_browser(attempt.url)
90
+ elif not await asyncio.to_thread(webbrowser.open, attempt.url):
91
+ raise OAuthError("The browser could not be opened.")
92
+ await callback.wait()
93
+
94
+ await asyncio.wait_for(interact(), timeout=self.timeout)
95
+ finally:
96
+ callback.cancel()
97
+ self.callback = None
98
+
99
+ async def handle(self, request: web.Request) -> web.Response:
100
+ if request.host != URL(self.redirect_uri).authority:
101
+ return OAuthCallback.response(False, "Invalid callback host.")
102
+ if self.callback is None:
103
+ return OAuthCallback.response(False, "No matching authorization attempt.")
104
+ return await self.callback.handle(request)
105
+
106
+
107
+ __all__ = ["LoopbackCallback"]