deapi-mcp 0.7.0__py3-none-any.whl
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.
- deapi_mcp/__init__.py +24 -0
- deapi_mcp/auth.py +33 -0
- deapi_mcp/auth_code_store.py +226 -0
- deapi_mcp/config.py +297 -0
- deapi_mcp/consent.py +549 -0
- deapi_mcp/deapi_client.py +466 -0
- deapi_mcp/fastmcp_auth.py +227 -0
- deapi_mcp/key_verifier.py +225 -0
- deapi_mcp/landing.py +431 -0
- deapi_mcp/middleware.py +756 -0
- deapi_mcp/oauth_clients.py +443 -0
- deapi_mcp/oauth_endpoints.py +973 -0
- deapi_mcp/observability.py +199 -0
- deapi_mcp/polling_manager.py +319 -0
- deapi_mcp/py.typed +0 -0
- deapi_mcp/schemas.py +397 -0
- deapi_mcp/server_remote.py +416 -0
- deapi_mcp/tools/__init__.py +0 -0
- deapi_mcp/tools/_price_helpers.py +167 -0
- deapi_mcp/tools/_responses.py +157 -0
- deapi_mcp/tools/audio.py +1195 -0
- deapi_mcp/tools/embedding.py +102 -0
- deapi_mcp/tools/image.py +884 -0
- deapi_mcp/tools/prompt.py +155 -0
- deapi_mcp/tools/utility.py +230 -0
- deapi_mcp/tools/video.py +1117 -0
- deapi_mcp/utils.py +666 -0
- deapi_mcp/webhooks.py +349 -0
- deapi_mcp-0.7.0.dist-info/METADATA +642 -0
- deapi_mcp-0.7.0.dist-info/RECORD +33 -0
- deapi_mcp-0.7.0.dist-info/WHEEL +4 -0
- deapi_mcp-0.7.0.dist-info/entry_points.txt +2 -0
- deapi_mcp-0.7.0.dist-info/licenses/LICENSE +21 -0
deapi_mcp/consent.py
ADDED
|
@@ -0,0 +1,549 @@
|
|
|
1
|
+
"""The sign-in screen at /authorize for public OAuth clients (CIMD or DCR).
|
|
2
|
+
|
|
3
|
+
A client that registered itself has no secret, so the deAPI key has to come from the
|
|
4
|
+
user: ``GET /authorize`` shows who is asking (the client's name, the host that vouches
|
|
5
|
+
for it, where the browser will return) and asks for the key; ``POST /authorize`` checks
|
|
6
|
+
the key with deAPI and, if it works, issues the authorization code. The pre-registered
|
|
7
|
+
``deapi-mcp`` client never sees this page.
|
|
8
|
+
|
|
9
|
+
Defences, in the order a request meets them:
|
|
10
|
+
|
|
11
|
+
- the client and its redirect URI are checked *before* anything is shown, and a bad one
|
|
12
|
+
gets an error page, never a redirect (no open redirector);
|
|
13
|
+
- the authorization request travels from GET to POST inside an HMAC-signed, 10-minute
|
|
14
|
+
token, so the form cannot be re-pointed at another client or redirect URI;
|
|
15
|
+
- a double-submit CSRF cookie (``SameSite=Strict``, ``__Host-`` on https);
|
|
16
|
+
- failed key attempts are counted per client IP (Redis when configured, shared by every
|
|
17
|
+
replica) and refused after ``MAX_KEY_FAILURES`` in ``KEY_FAILURE_WINDOW``;
|
|
18
|
+
- the page loads nothing, runs no script, cannot be framed, and is never cached; its CSP
|
|
19
|
+
allows the form to post only here and to redirect only to the client's own URI.
|
|
20
|
+
|
|
21
|
+
The key is never logged and never echoed back into the page.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
import base64
|
|
25
|
+
import hashlib
|
|
26
|
+
import hmac
|
|
27
|
+
import json
|
|
28
|
+
import logging
|
|
29
|
+
import os
|
|
30
|
+
import secrets
|
|
31
|
+
import time
|
|
32
|
+
from html import escape
|
|
33
|
+
from typing import Any, Optional
|
|
34
|
+
from urllib.parse import urlsplit
|
|
35
|
+
|
|
36
|
+
from starlette.requests import Request
|
|
37
|
+
from starlette.responses import HTMLResponse, Response
|
|
38
|
+
|
|
39
|
+
from . import auth_code_store
|
|
40
|
+
from .auth_code_store import AuthCodeStoreUnavailable, build_redis_client
|
|
41
|
+
from .config import settings
|
|
42
|
+
from .key_verifier import KeyStatus, get_key_verifier
|
|
43
|
+
from .landing import CSS, HOME_URL, KEYS_URL, LOGO_SVG, MCP_DOCS_URL
|
|
44
|
+
from .oauth_clients import OAuthClient, is_loopback_redirect, resolve_client
|
|
45
|
+
|
|
46
|
+
logger = logging.getLogger(__name__)
|
|
47
|
+
|
|
48
|
+
REQUEST_TTL_SECONDS = 600
|
|
49
|
+
MAX_KEY_FAILURES = 10
|
|
50
|
+
KEY_FAILURE_WINDOW = 900
|
|
51
|
+
MAX_KEY_LENGTH = 512
|
|
52
|
+
CSRF_COOKIE_HTTPS = "__Host-deapi_mcp_csrf"
|
|
53
|
+
CSRF_COOKIE_HTTP = "deapi_mcp_csrf"
|
|
54
|
+
|
|
55
|
+
CONSENT_CSS = """
|
|
56
|
+
main.signin{padding:1.25rem 1.25rem 2.5rem}
|
|
57
|
+
.auth{max-width:40rem;margin:0 auto;background:var(--card);border:1px solid var(--line);
|
|
58
|
+
border-radius:12px;padding:1.4rem 2rem 1.25rem;line-height:1.55;font-size:14px}
|
|
59
|
+
.auth h1{font-size:1.6rem;text-align:left;margin:0 0 .25rem}
|
|
60
|
+
.auth p{margin:.4rem 0}
|
|
61
|
+
.who{display:flex;gap:.9rem;align-items:center;margin:.9rem 0 .5rem;padding:.7rem 1rem;
|
|
62
|
+
background:var(--bg-deep);border:1px solid var(--line-soft);border-radius:8px}
|
|
63
|
+
.avatar{width:2.6rem;height:2.6rem;border-radius:8px;background:#2a2416;color:var(--amber);
|
|
64
|
+
display:flex;align-items:center;justify-content:center;font:700 1.1rem var(--sans);flex:none}
|
|
65
|
+
.who b{display:block;font-family:var(--sans);font-size:1.05rem;overflow-wrap:anywhere}
|
|
66
|
+
.who span{font-size:.8rem;color:var(--dim);overflow-wrap:anywhere}
|
|
67
|
+
.dest{font-size:.9rem;margin:.2rem 0 .6rem}
|
|
68
|
+
.dest b{color:var(--amber);overflow-wrap:anywhere}
|
|
69
|
+
.warn,.error{border-radius:8px;padding:.6rem 1rem;font-size:.85rem;margin:.6rem 0}
|
|
70
|
+
.warn{border:1px solid #6b4a12;background:#2a1e08;color:#ffd38a}
|
|
71
|
+
.warn b{color:#ffe2ad}
|
|
72
|
+
.error{border:1px solid #7a2433;background:#2a0d12;color:#ffb3c0}
|
|
73
|
+
label{display:block;color:var(--fg);font:600 .95rem var(--sans);margin:.9rem 0 .35rem}
|
|
74
|
+
input[type=password]{width:100%;font:1rem var(--mono);color:var(--fg);background:var(--bg-deep);
|
|
75
|
+
border:1px solid var(--line);border-radius:6px;padding:.75rem .9rem}
|
|
76
|
+
input[type=password]:focus{outline:2px solid var(--amber);outline-offset:1px}
|
|
77
|
+
.hint{font-size:.8rem;color:var(--dim);margin:.4rem 0 0}
|
|
78
|
+
ul.grants{margin:.3rem 0 .4rem;padding-left:1.2rem;font-size:.88rem}
|
|
79
|
+
ul.grants li{margin:.1rem 0}
|
|
80
|
+
.actions{display:flex;gap:.7rem;margin-top:1rem}
|
|
81
|
+
.actions button{flex:1;cursor:pointer;font:700 .85rem/1 var(--mono);padding:.95rem;
|
|
82
|
+
border-radius:4px;border:1px solid var(--amber);color:var(--amber);background:none}
|
|
83
|
+
.actions button.solid{background:var(--amber);color:#11100d}
|
|
84
|
+
.actions button:hover{background:var(--amber-hi);border-color:var(--amber-hi);color:#11100d}
|
|
85
|
+
.fine{font-size:.78rem;color:var(--dim);margin-top:.9rem}
|
|
86
|
+
"""
|
|
87
|
+
|
|
88
|
+
STYLE = CSS + CONSENT_CSS
|
|
89
|
+
_STYLE_HASH = base64.b64encode(hashlib.sha256(STYLE.encode()).digest()).decode()
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
# --- signed authorization request -----------------------------------------------------------
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _request_key() -> bytes:
|
|
96
|
+
from .oauth_endpoints import get_jwt_secret_key
|
|
97
|
+
|
|
98
|
+
return hashlib.sha256(b"deapi-mcp/consent-request\x00" + get_jwt_secret_key().encode()).digest()
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _b64(data: bytes) -> str:
|
|
102
|
+
return base64.urlsafe_b64encode(data).decode().rstrip("=")
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def sign_request(fields: dict[str, Any]) -> str:
|
|
106
|
+
body = _b64(json.dumps({**fields, "exp": int(time.time()) + REQUEST_TTL_SECONDS}).encode())
|
|
107
|
+
signature = _b64(hmac.new(_request_key(), body.encode(), hashlib.sha256).digest())
|
|
108
|
+
return f"{body}.{signature}"
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def verify_request(token: Optional[str]) -> Optional[dict[str, Any]]:
|
|
112
|
+
if not token:
|
|
113
|
+
return None
|
|
114
|
+
body, sep, signature = token.partition(".")
|
|
115
|
+
if not sep:
|
|
116
|
+
return None
|
|
117
|
+
expected = _b64(hmac.new(_request_key(), body.encode(), hashlib.sha256).digest())
|
|
118
|
+
if not hmac.compare_digest(expected.encode(), signature.encode()):
|
|
119
|
+
return None
|
|
120
|
+
try:
|
|
121
|
+
data = json.loads(base64.urlsafe_b64decode(body + "=" * (-len(body) % 4)))
|
|
122
|
+
except (ValueError, RecursionError):
|
|
123
|
+
return None
|
|
124
|
+
if not isinstance(data, dict) or int(data.get("exp", 0)) < time.time():
|
|
125
|
+
return None
|
|
126
|
+
return data
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
# --- failed key attempts -----------------------------------------------------------------------
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
class KeyFailureLimiter:
|
|
133
|
+
"""Counts failed key attempts per client IP; Redis when configured, else this process.
|
|
134
|
+
|
|
135
|
+
A Redis error falls back to the in-process count, so the sign-in screen keeps
|
|
136
|
+
working (with a per-replica limit) while Redis is away.
|
|
137
|
+
"""
|
|
138
|
+
|
|
139
|
+
def __init__(self) -> None:
|
|
140
|
+
self._local: dict[str, tuple[int, float]] = {}
|
|
141
|
+
self._redis: Any = None
|
|
142
|
+
if settings.redis_host:
|
|
143
|
+
self._redis = build_redis_client(settings)
|
|
144
|
+
|
|
145
|
+
@staticmethod
|
|
146
|
+
def _bucket(ip: str) -> str:
|
|
147
|
+
return hashlib.sha256(ip.encode()).hexdigest()[:32]
|
|
148
|
+
|
|
149
|
+
def _redis_key(self, ip: str) -> str:
|
|
150
|
+
return f"{settings.redis_prefix}oauth_key_fail:{self._bucket(ip)}"
|
|
151
|
+
|
|
152
|
+
def _local_count(self, ip: str) -> int:
|
|
153
|
+
count, until = self._local.get(ip, (0, 0.0))
|
|
154
|
+
if until <= time.time():
|
|
155
|
+
self._local.pop(ip, None)
|
|
156
|
+
return 0
|
|
157
|
+
return count
|
|
158
|
+
|
|
159
|
+
async def blocked(self, ip: str) -> bool:
|
|
160
|
+
if self._redis is not None:
|
|
161
|
+
try:
|
|
162
|
+
raw = await self._redis.get(self._redis_key(ip))
|
|
163
|
+
return int(raw or 0) >= MAX_KEY_FAILURES
|
|
164
|
+
except Exception:
|
|
165
|
+
logger.warning("Key attempt limiter: Redis unavailable, counting in memory")
|
|
166
|
+
return self._local_count(ip) >= MAX_KEY_FAILURES
|
|
167
|
+
|
|
168
|
+
async def record_failure(self, ip: str) -> None:
|
|
169
|
+
if self._redis is not None:
|
|
170
|
+
try:
|
|
171
|
+
key = self._redis_key(ip)
|
|
172
|
+
async with self._redis.pipeline(transaction=True) as pipe:
|
|
173
|
+
pipe.set(key, 0, ex=KEY_FAILURE_WINDOW, nx=True)
|
|
174
|
+
pipe.incr(key)
|
|
175
|
+
await pipe.execute()
|
|
176
|
+
return
|
|
177
|
+
except Exception:
|
|
178
|
+
logger.warning("Key attempt limiter: Redis unavailable, counting in memory")
|
|
179
|
+
count = self._local_count(ip)
|
|
180
|
+
until = self._local.get(ip, (0, time.time() + KEY_FAILURE_WINDOW))[1]
|
|
181
|
+
self._local[ip] = (count + 1, until)
|
|
182
|
+
if len(self._local) > 10_000:
|
|
183
|
+
self._local.pop(next(iter(self._local)))
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
_limiter: Optional[KeyFailureLimiter] = None
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def get_limiter() -> KeyFailureLimiter:
|
|
190
|
+
global _limiter
|
|
191
|
+
if _limiter is None:
|
|
192
|
+
_limiter = KeyFailureLimiter()
|
|
193
|
+
return _limiter
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def reset_limiter(limiter: Optional[KeyFailureLimiter] = None) -> None:
|
|
197
|
+
global _limiter
|
|
198
|
+
_limiter = limiter
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
# --- pages ------------------------------------------------------------------------------------
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _form_action_source(redirect_uri: str) -> str:
|
|
205
|
+
"""The CSP source that lets the form's POST redirect on to ``redirect_uri``.
|
|
206
|
+
|
|
207
|
+
Browsers check form-action against redirects that follow a form submission, so the
|
|
208
|
+
client's own origin (or, for a native app, its scheme) must be listed.
|
|
209
|
+
"""
|
|
210
|
+
parts = urlsplit(redirect_uri)
|
|
211
|
+
if parts.scheme in ("http", "https"):
|
|
212
|
+
host = parts.hostname or ""
|
|
213
|
+
if ":" in host:
|
|
214
|
+
host = f"[{host}]"
|
|
215
|
+
port = f":{parts.port}" if parts.port else ""
|
|
216
|
+
return f"{parts.scheme}://{host}{port}"
|
|
217
|
+
return f"{parts.scheme}:"
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _headers(redirect_uri: Optional[str] = None) -> dict[str, str]:
|
|
221
|
+
form_action = "'self'" + (f" {_form_action_source(redirect_uri)}" if redirect_uri else "")
|
|
222
|
+
return {
|
|
223
|
+
"Content-Security-Policy": (
|
|
224
|
+
f"default-src 'none'; style-src 'sha256-{_STYLE_HASH}'; base-uri 'none'; "
|
|
225
|
+
f"form-action {form_action}; frame-ancestors 'none'"
|
|
226
|
+
),
|
|
227
|
+
"X-Content-Type-Options": "nosniff",
|
|
228
|
+
"X-Frame-Options": "DENY",
|
|
229
|
+
"Referrer-Policy": "no-referrer",
|
|
230
|
+
"Cross-Origin-Opener-Policy": "same-origin",
|
|
231
|
+
"Cache-Control": "no-store",
|
|
232
|
+
"Pragma": "no-cache",
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _page(title: str, body: str) -> str:
|
|
237
|
+
return f"""<!doctype html>
|
|
238
|
+
<html lang=en>
|
|
239
|
+
<head>
|
|
240
|
+
<meta charset=utf-8>
|
|
241
|
+
<meta name=viewport content="width=device-width, initial-scale=1">
|
|
242
|
+
<meta name=referrer content=no-referrer>
|
|
243
|
+
<meta name=robots content=noindex>
|
|
244
|
+
<title>{escape(title)}</title>
|
|
245
|
+
<style>{STYLE}</style>
|
|
246
|
+
</head>
|
|
247
|
+
<body>
|
|
248
|
+
<div class=bar></div>
|
|
249
|
+
<header>
|
|
250
|
+
<a class=home href="{HOME_URL}">{LOGO_SVG}</a>
|
|
251
|
+
<span class=pill>MCP SERVER</span>
|
|
252
|
+
</header>
|
|
253
|
+
<main class=signin>
|
|
254
|
+
{body}
|
|
255
|
+
</main>
|
|
256
|
+
</body>
|
|
257
|
+
</html>
|
|
258
|
+
"""
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def error_page(message: str, status_code: int = 400) -> HTMLResponse:
|
|
262
|
+
body = f"""<div class=auth>
|
|
263
|
+
<h1>Cannot connect</h1>
|
|
264
|
+
<div class=error>{escape(message)}</div>
|
|
265
|
+
<p class=hint>Start the connection again from your application. If this keeps happening,
|
|
266
|
+
see the <a href="{MCP_DOCS_URL}">MCP server docs</a>.</p>
|
|
267
|
+
</div>"""
|
|
268
|
+
return HTMLResponse(
|
|
269
|
+
_page("Cannot connect to deAPI", body), status_code=status_code, headers=_headers()
|
|
270
|
+
)
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _host_label(redirect_uri: str) -> str:
|
|
274
|
+
parts = urlsplit(redirect_uri)
|
|
275
|
+
if is_loopback_redirect(redirect_uri):
|
|
276
|
+
return "localhost (an app on this computer)"
|
|
277
|
+
if parts.scheme in ("http", "https"):
|
|
278
|
+
return parts.hostname or redirect_uri
|
|
279
|
+
return f"the app that handles {parts.scheme}: links"
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def _same_site(host: str, publisher: str) -> bool:
|
|
283
|
+
"""``host`` is ``publisher`` or one of its subdomains."""
|
|
284
|
+
return host == publisher or host.endswith("." + publisher)
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _warnings(client: OAuthClient, redirect_uri: str) -> str:
|
|
288
|
+
"""Every warning that applies, most important first."""
|
|
289
|
+
host = escape(_host_label(redirect_uri))
|
|
290
|
+
parts = urlsplit(redirect_uri)
|
|
291
|
+
out = []
|
|
292
|
+
if is_loopback_redirect(redirect_uri):
|
|
293
|
+
out.append(
|
|
294
|
+
"<b>Returns to an app on this computer.</b> Continue only if you just started the "
|
|
295
|
+
"connection from a program you run, such as Claude Code or Cursor."
|
|
296
|
+
)
|
|
297
|
+
elif parts.scheme not in ("http", "https"):
|
|
298
|
+
out.append(
|
|
299
|
+
f"<b>Returns to an app on your device</b> ({escape(parts.scheme)}: links). Continue "
|
|
300
|
+
"only if you just started the connection from that app."
|
|
301
|
+
)
|
|
302
|
+
elif client.verified_host and not _same_site(parts.hostname or "", client.verified_host):
|
|
303
|
+
out.append(
|
|
304
|
+
f"<b>Access goes to a different site.</b> This application is published at "
|
|
305
|
+
f"<b>{escape(client.verified_host)}</b>, but your access goes to <b>{host}</b>. Only "
|
|
306
|
+
"continue if you trust both."
|
|
307
|
+
)
|
|
308
|
+
if client.kind != "cimd":
|
|
309
|
+
out.append(
|
|
310
|
+
"<b>Unverified application.</b> deAPI cannot confirm who runs it; its name was "
|
|
311
|
+
"chosen by the application itself. Only continue if you started this connection "
|
|
312
|
+
f"and you trust <b>{host}</b>."
|
|
313
|
+
)
|
|
314
|
+
return "".join(f"<div class=warn>{w}</div>" for w in out)
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def consent_page(
|
|
318
|
+
client: OAuthClient,
|
|
319
|
+
redirect_uri: str,
|
|
320
|
+
signed_request: str,
|
|
321
|
+
csrf: str,
|
|
322
|
+
error: Optional[str] = None,
|
|
323
|
+
status_code: int = 200,
|
|
324
|
+
) -> HTMLResponse:
|
|
325
|
+
returns = escape(_host_label(redirect_uri))
|
|
326
|
+
if client.verified_host:
|
|
327
|
+
# The publisher is the host serving the client's metadata. deAPI does not vouch for
|
|
328
|
+
# it: it is shown as a fact, not as a verification.
|
|
329
|
+
name = escape(client.name)
|
|
330
|
+
initial = escape(client.name[:1].upper() or "?")
|
|
331
|
+
badge = f"published at {escape(client.verified_host)}"
|
|
332
|
+
else:
|
|
333
|
+
name = f"“{escape(client.name)}” (unverified)"
|
|
334
|
+
initial = "?"
|
|
335
|
+
badge = "registered itself, name not verified"
|
|
336
|
+
error_html = f"<div class=error role=alert>{escape(error)}</div>" if error else ""
|
|
337
|
+
body = f"""<div class=auth>
|
|
338
|
+
<h1>Connect to deAPI</h1>
|
|
339
|
+
<p>An application wants to use deAPI models on your behalf.</p>
|
|
340
|
+
<div class=who><div class=avatar>{initial}</div><div><b>{name}</b><span>{badge}</span></div></div>
|
|
341
|
+
<p class=dest>Access goes to <b>{returns}</b></p>
|
|
342
|
+
{_warnings(client, redirect_uri)}
|
|
343
|
+
<p>If you continue, this application will be able to:</p>
|
|
344
|
+
<ul class=grants>
|
|
345
|
+
<li>run image, video, audio, transcription, OCR and embedding models</li>
|
|
346
|
+
<li>check your balance and job status</li>
|
|
347
|
+
<li>spend your deAPI balance on the jobs it runs</li>
|
|
348
|
+
</ul>
|
|
349
|
+
<form method=post action="/authorize">
|
|
350
|
+
<input type=hidden name=request value="{escape(signed_request)}">
|
|
351
|
+
<input type=hidden name=csrf value="{escape(csrf)}">
|
|
352
|
+
{error_html}
|
|
353
|
+
<label for=api_key>deAPI API key</label>
|
|
354
|
+
<input id=api_key name=api_key type=password autocomplete=off spellcheck=false
|
|
355
|
+
required maxlength={MAX_KEY_LENGTH} placeholder="sk-dp-...">
|
|
356
|
+
<p class=hint>Create or copy a key at <a href="{KEYS_URL}">app.deapi.ai/settings/api-keys</a>.
|
|
357
|
+
Consider a separate key for each app, so you can revoke one without the others.</p>
|
|
358
|
+
<div class=actions><button type=submit name=action value=deny formnovalidate>Cancel</button><button
|
|
359
|
+
type=submit name=action value=allow class=solid>Allow access</button></div>
|
|
360
|
+
</form>
|
|
361
|
+
<p class=fine>Your key is checked with deAPI and reaches the application only inside encrypted
|
|
362
|
+
tokens it cannot read. Deleting the key in deAPI ends this connection.</p>
|
|
363
|
+
</div>"""
|
|
364
|
+
response = HTMLResponse(
|
|
365
|
+
_page("Connect to deAPI", body), status_code=status_code, headers=_headers(redirect_uri)
|
|
366
|
+
)
|
|
367
|
+
return response
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
# --- request handling ---------------------------------------------------------------------------
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def _is_https(request: Request) -> bool:
|
|
374
|
+
"""Whether the browser reached us over https: PUBLIC_BASE_URL decides when it is set.
|
|
375
|
+
|
|
376
|
+
A proxy that does not forward the scheme would otherwise downgrade the CSRF cookie
|
|
377
|
+
(no ``Secure``, no ``__Host-`` prefix).
|
|
378
|
+
"""
|
|
379
|
+
public = os.getenv("PUBLIC_BASE_URL")
|
|
380
|
+
if public:
|
|
381
|
+
return public.lower().startswith("https://")
|
|
382
|
+
return request.url.scheme == "https"
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def _csrf_cookie_name(request: Request) -> str:
|
|
386
|
+
return CSRF_COOKIE_HTTPS if _is_https(request) else CSRF_COOKIE_HTTP
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def _client_ip(request: Request) -> str:
|
|
390
|
+
"""The address the wrong-key limit counts against.
|
|
391
|
+
|
|
392
|
+
``DEAPI_CLIENT_IP_HEADER`` names a header the edge sets and clients cannot (for example
|
|
393
|
+
``CF-Connecting-IP`` when every request comes through Cloudflare). Without it the
|
|
394
|
+
connection's address is used, which behind a proxy that trusts ``X-Forwarded-For``
|
|
395
|
+
blindly can be chosen by the client.
|
|
396
|
+
"""
|
|
397
|
+
header = settings.client_ip_header
|
|
398
|
+
if header:
|
|
399
|
+
value = request.headers.get(header, "").split(",")[0].strip()
|
|
400
|
+
if value:
|
|
401
|
+
return value
|
|
402
|
+
return request.client.host if request.client else "unknown"
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def _with_csrf_cookie(response: Response, request: Request, value: str) -> Response:
|
|
406
|
+
response.set_cookie(
|
|
407
|
+
_csrf_cookie_name(request),
|
|
408
|
+
value,
|
|
409
|
+
max_age=REQUEST_TTL_SECONDS,
|
|
410
|
+
path="/",
|
|
411
|
+
secure=_is_https(request),
|
|
412
|
+
httponly=True,
|
|
413
|
+
samesite="strict",
|
|
414
|
+
)
|
|
415
|
+
return response
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
async def show_consent(
|
|
419
|
+
request: Request, client: OAuthClient, redirect_uri: str, fields: dict[str, Any]
|
|
420
|
+
) -> Response:
|
|
421
|
+
"""Render the sign-in screen for an already validated authorization request."""
|
|
422
|
+
csrf = request.cookies.get(_csrf_cookie_name(request)) or secrets.token_urlsafe(32)
|
|
423
|
+
page = consent_page(client, redirect_uri, sign_request(fields), csrf)
|
|
424
|
+
return _with_csrf_cookie(page, request, csrf)
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
async def submit_consent(request: Request) -> Response:
|
|
428
|
+
"""Handle the sign-in form: deny, or check the key and issue the authorization code."""
|
|
429
|
+
from .oauth_endpoints import (
|
|
430
|
+
AUTHORIZATION_CODE_EXPIRATION_SECONDS,
|
|
431
|
+
authorization_redirect,
|
|
432
|
+
encrypt_token,
|
|
433
|
+
)
|
|
434
|
+
|
|
435
|
+
form = await request.form()
|
|
436
|
+
raw_request = form.get("request")
|
|
437
|
+
fields = verify_request(raw_request if isinstance(raw_request, str) else None)
|
|
438
|
+
if fields is None:
|
|
439
|
+
return error_page("This sign-in page has expired. Start the connection again.")
|
|
440
|
+
|
|
441
|
+
csrf_form = form.get("csrf")
|
|
442
|
+
csrf_cookie = request.cookies.get(_csrf_cookie_name(request))
|
|
443
|
+
if (
|
|
444
|
+
not isinstance(csrf_form, str)
|
|
445
|
+
or not csrf_cookie
|
|
446
|
+
or not hmac.compare_digest(csrf_form.encode(), csrf_cookie.encode())
|
|
447
|
+
):
|
|
448
|
+
return error_page(
|
|
449
|
+
"The sign-in form could not be verified. Make sure cookies are enabled and start "
|
|
450
|
+
"the connection again."
|
|
451
|
+
)
|
|
452
|
+
|
|
453
|
+
client = await resolve_client(str(fields.get("client_id", "")))
|
|
454
|
+
redirect_uri = str(fields.get("redirect_uri", ""))
|
|
455
|
+
if client is None or not client.allows_redirect(redirect_uri):
|
|
456
|
+
return error_page("This application is no longer registered. Start the connection again.")
|
|
457
|
+
state = fields.get("state")
|
|
458
|
+
|
|
459
|
+
if form.get("action") != "allow":
|
|
460
|
+
return authorization_redirect(
|
|
461
|
+
request,
|
|
462
|
+
redirect_uri,
|
|
463
|
+
{"error": "access_denied", "error_description": "The user declined"},
|
|
464
|
+
state,
|
|
465
|
+
status_code=303,
|
|
466
|
+
)
|
|
467
|
+
|
|
468
|
+
signed = raw_request if isinstance(raw_request, str) else ""
|
|
469
|
+
ip = _client_ip(request)
|
|
470
|
+
limiter = get_limiter()
|
|
471
|
+
if await limiter.blocked(ip):
|
|
472
|
+
page = consent_page(
|
|
473
|
+
client,
|
|
474
|
+
redirect_uri,
|
|
475
|
+
signed,
|
|
476
|
+
csrf_cookie,
|
|
477
|
+
"Too many attempts with a wrong key. Wait a few minutes and try again.",
|
|
478
|
+
status_code=429,
|
|
479
|
+
)
|
|
480
|
+
return page
|
|
481
|
+
|
|
482
|
+
key_value = form.get("api_key")
|
|
483
|
+
api_key = key_value.strip() if isinstance(key_value, str) else ""
|
|
484
|
+
if len(api_key) < 10 or len(api_key) > MAX_KEY_LENGTH:
|
|
485
|
+
return consent_page(
|
|
486
|
+
client, redirect_uri, signed, csrf_cookie, "Enter your deAPI API key.", 400
|
|
487
|
+
)
|
|
488
|
+
|
|
489
|
+
status = (
|
|
490
|
+
await get_key_verifier().verify(api_key) if settings.verify_api_keys else KeyStatus.VALID
|
|
491
|
+
)
|
|
492
|
+
if status is KeyStatus.INVALID:
|
|
493
|
+
await limiter.record_failure(ip)
|
|
494
|
+
return consent_page(
|
|
495
|
+
client,
|
|
496
|
+
redirect_uri,
|
|
497
|
+
signed,
|
|
498
|
+
csrf_cookie,
|
|
499
|
+
"deAPI did not accept this key. Check it and try again.",
|
|
500
|
+
400,
|
|
501
|
+
)
|
|
502
|
+
if status is not KeyStatus.VALID:
|
|
503
|
+
return consent_page(
|
|
504
|
+
client,
|
|
505
|
+
redirect_uri,
|
|
506
|
+
signed,
|
|
507
|
+
csrf_cookie,
|
|
508
|
+
"The key could not be checked with deAPI right now. Try again in a moment.",
|
|
509
|
+
503,
|
|
510
|
+
)
|
|
511
|
+
|
|
512
|
+
code = secrets.token_urlsafe(32)
|
|
513
|
+
try:
|
|
514
|
+
stored = await auth_code_store.get_auth_code_store().put(
|
|
515
|
+
code,
|
|
516
|
+
{
|
|
517
|
+
"client_id": client.client_id,
|
|
518
|
+
"redirect_uri": redirect_uri,
|
|
519
|
+
"redirect_uri_supplied": bool(fields.get("redirect_uri_supplied", True)),
|
|
520
|
+
"code_challenge": fields.get("code_challenge"),
|
|
521
|
+
"expires_at": time.time() + AUTHORIZATION_CODE_EXPIRATION_SECONDS,
|
|
522
|
+
"state": state,
|
|
523
|
+
"resource": fields.get("resource"),
|
|
524
|
+
"key_enc": encrypt_token(api_key),
|
|
525
|
+
},
|
|
526
|
+
AUTHORIZATION_CODE_EXPIRATION_SECONDS,
|
|
527
|
+
)
|
|
528
|
+
except AuthCodeStoreUnavailable:
|
|
529
|
+
logger.error("Authorization code store unavailable during sign-in")
|
|
530
|
+
stored = None
|
|
531
|
+
if not stored:
|
|
532
|
+
return consent_page(
|
|
533
|
+
client,
|
|
534
|
+
redirect_uri,
|
|
535
|
+
signed,
|
|
536
|
+
csrf_cookie,
|
|
537
|
+
"deAPI MCP is busy right now. Try again in a moment.",
|
|
538
|
+
503,
|
|
539
|
+
)
|
|
540
|
+
logger.info("Public client signed in (%s)", client.kind)
|
|
541
|
+
response = authorization_redirect(request, redirect_uri, {"code": code}, state, 303)
|
|
542
|
+
response.delete_cookie(
|
|
543
|
+
_csrf_cookie_name(request),
|
|
544
|
+
path="/",
|
|
545
|
+
secure=_is_https(request),
|
|
546
|
+
httponly=True,
|
|
547
|
+
samesite="strict",
|
|
548
|
+
)
|
|
549
|
+
return response
|