mcp-server-core 0.2.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.
mcp_framework/oauth.py ADDED
@@ -0,0 +1,658 @@
1
+ """OAuth 2.1 and RFC 9728 Protected Resource Implementation for ChatGPT and Remote Agents.
2
+
3
+ Implements MCP 2025-11-25 Authorization Specification:
4
+ - RFC 9728: OAuth 2.0 Protected Resource Metadata
5
+ - RFC 8414: OAuth 2.0 Authorization Server Metadata
6
+ - RFC 7591: Dynamic Client Registration (DCR)
7
+ - RFC 7636: Proof Key for Code Exchange (PKCE S256)
8
+ - Embedded Local Authorization Server & SQLite Persistent Storage
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import base64
13
+ from contextlib import contextmanager
14
+ import hashlib
15
+ import html
16
+ import json
17
+ import os
18
+ import secrets
19
+ import sqlite3
20
+ import time
21
+ from pathlib import Path
22
+ from typing import Any
23
+ from urllib.parse import urlencode
24
+
25
+ from starlette.requests import Request
26
+ from starlette.responses import HTMLResponse, JSONResponse, RedirectResponse, Response
27
+
28
+ from .env import get_runtime_dir
29
+
30
+
31
+ def base64url_encode(data: bytes) -> str:
32
+ """Encode bytes to base64url string without padding."""
33
+ return base64.urlsafe_b64encode(data).decode("utf-8").rstrip("=")
34
+
35
+
36
+ def verify_pkce(code_verifier: str, code_challenge: str, method: str = "S256") -> bool:
37
+ """Verify PKCE code_verifier against code_challenge."""
38
+ if method == "plain":
39
+ return code_verifier == code_challenge
40
+ elif method == "S256":
41
+ digest = hashlib.sha256(code_verifier.encode("ascii")).digest()
42
+ computed = base64url_encode(digest)
43
+ return computed == code_challenge
44
+ return False
45
+
46
+
47
+ def get_client_ip(request: Request) -> str:
48
+ """Extract real client IP considering reverse proxy and Cloudflare headers."""
49
+ cf_connecting_ip = request.headers.get("cf-connecting-ip")
50
+ if cf_connecting_ip:
51
+ return cf_connecting_ip.strip()
52
+ x_forwarded_for = request.headers.get("x-forwarded-for")
53
+ if x_forwarded_for:
54
+ return x_forwarded_for.split(",")[0].strip()
55
+ return request.client.host if request.client else "127.0.0.1"
56
+
57
+
58
+ class AuthRateLimiter:
59
+ """Sliding-window IP rate limiter with lockout penalty for failed authentications."""
60
+
61
+ def __init__(
62
+ self,
63
+ max_attempts: int = 5,
64
+ window_seconds: float = 600.0,
65
+ lockout_seconds: float = 900.0,
66
+ ) -> None:
67
+ self.max_attempts = max_attempts
68
+ self.window_seconds = window_seconds
69
+ self.lockout_seconds = lockout_seconds
70
+ self._lockouts: dict[str, float] = {}
71
+ self._failures: dict[str, list[float]] = {}
72
+ self._dcr_counts: dict[str, list[float]] = {}
73
+
74
+ def is_locked_out(self, ip: str) -> tuple[bool, int]:
75
+ now = time.time()
76
+ if ip in self._lockouts:
77
+ unlock_at = self._lockouts[ip]
78
+ if now < unlock_at:
79
+ return True, int(unlock_at - now)
80
+ else:
81
+ del self._lockouts[ip]
82
+ self._failures.pop(ip, None)
83
+ return False, 0
84
+
85
+ def record_failure(self, ip: str) -> tuple[bool, int, int]:
86
+ now = time.time()
87
+ attempts = self._failures.setdefault(ip, [])
88
+ attempts = [t for t in attempts if now - t < self.window_seconds]
89
+ attempts.append(now)
90
+ self._failures[ip] = attempts
91
+
92
+ if len(attempts) >= self.max_attempts:
93
+ self._lockouts[ip] = now + self.lockout_seconds
94
+ return True, int(self.lockout_seconds), 0
95
+ return False, 0, max(0, self.max_attempts - len(attempts))
96
+
97
+ def record_success(self, ip: str) -> None:
98
+ self._failures.pop(ip, None)
99
+ self._lockouts.pop(ip, None)
100
+
101
+ def check_dcr_rate_limit(self, ip: str, max_dcr_per_hour: int = 15) -> bool:
102
+ now = time.time()
103
+ records = self._dcr_counts.setdefault(ip, [])
104
+ records = [t for t in records if now - t < 3600.0]
105
+ if len(records) >= max_dcr_per_hour:
106
+ self._dcr_counts[ip] = records
107
+ return False
108
+ records.append(now)
109
+ self._dcr_counts[ip] = records
110
+ return True
111
+
112
+
113
+ class LocalOAuthServer:
114
+ """Embedded OAuth 2.1 server with native SQLite persistence, DCR, and PKCE verification."""
115
+
116
+ def __init__(self, admin_password: str, db_path: Path | str | None = None) -> None:
117
+ self.admin_password = admin_password
118
+ if db_path:
119
+ self.db_path = str(db_path)
120
+ Path(self.db_path).parent.mkdir(parents=True, exist_ok=True)
121
+ else:
122
+ runtime_dir = get_runtime_dir()
123
+ self.db_path = str(runtime_dir / "oauth_store.db")
124
+
125
+ self.rate_limiter = AuthRateLimiter()
126
+ self._init_db()
127
+
128
+ @contextmanager
129
+ def _db_conn(self):
130
+ """Context manager yielding SQLite connection with auto-commit and guaranteed close."""
131
+ conn = sqlite3.connect(self.db_path, timeout=10.0)
132
+ conn.row_factory = sqlite3.Row
133
+ try:
134
+ with conn:
135
+ yield conn
136
+ finally:
137
+ conn.close()
138
+
139
+ def _init_db(self) -> None:
140
+ with self._db_conn() as conn:
141
+ conn.executescript("""
142
+ CREATE TABLE IF NOT EXISTS oauth_clients (
143
+ client_id TEXT PRIMARY KEY,
144
+ client_secret TEXT,
145
+ client_name TEXT,
146
+ redirect_uris TEXT,
147
+ grant_types TEXT,
148
+ response_types TEXT,
149
+ created_at REAL
150
+ );
151
+ CREATE TABLE IF NOT EXISTS oauth_tokens (
152
+ access_token TEXT PRIMARY KEY,
153
+ token_type TEXT,
154
+ expires_in INTEGER,
155
+ expires_at REAL,
156
+ created_at REAL,
157
+ scope TEXT,
158
+ client_id TEXT
159
+ );
160
+ CREATE TABLE IF NOT EXISTS oauth_codes (
161
+ code TEXT PRIMARY KEY,
162
+ client_id TEXT,
163
+ redirect_uri TEXT,
164
+ code_challenge TEXT,
165
+ code_challenge_method TEXT,
166
+ scope TEXT,
167
+ expires_at REAL,
168
+ created_at REAL
169
+ );
170
+ CREATE INDEX IF NOT EXISTS idx_tokens_expires_at ON oauth_tokens(expires_at);
171
+ CREATE INDEX IF NOT EXISTS idx_codes_expires_at ON oauth_codes(expires_at);
172
+ """)
173
+
174
+ now = time.time()
175
+ conn.execute("DELETE FROM oauth_codes WHERE expires_at < ?", (now,))
176
+ conn.execute("DELETE FROM oauth_tokens WHERE expires_at < ?", (now,))
177
+
178
+ conn.execute("""
179
+ INSERT OR IGNORE INTO oauth_clients (client_id, client_secret, client_name, redirect_uris, grant_types, response_types, created_at)
180
+ VALUES (?, ?, ?, ?, ?, ?, ?)
181
+ """, (
182
+ "chatgpt",
183
+ self.admin_password,
184
+ "ChatGPT Pre-registered",
185
+ "[]",
186
+ '["authorization_code", "refresh_token"]',
187
+ '["code"]',
188
+ now,
189
+ ))
190
+
191
+ def register_client(self, metadata: dict[str, Any]) -> dict[str, Any]:
192
+ """RFC 7591 Dynamic Client Registration with automatic storage in SQLite."""
193
+ client_id = f"mcp_client_{secrets.token_urlsafe(12)}"
194
+ client_secret = f"mcp_sec_{secrets.token_urlsafe(24)}"
195
+ record = {
196
+ "client_id": client_id,
197
+ "client_secret": client_secret,
198
+ "client_name": metadata.get("client_name", "ChatGPT"),
199
+ "redirect_uris": metadata.get("redirect_uris", []),
200
+ "grant_types": metadata.get("grant_types", ["authorization_code", "refresh_token"]),
201
+ "response_types": metadata.get("response_types", ["code"]),
202
+ "created_at": time.time(),
203
+ }
204
+ with self._db_conn() as conn:
205
+ total = conn.execute("SELECT COUNT(*) FROM oauth_clients").fetchone()[0]
206
+ if total >= 200:
207
+ conn.execute("""
208
+ DELETE FROM oauth_clients WHERE client_id != 'chatgpt'
209
+ AND client_id IN (
210
+ SELECT client_id FROM oauth_clients WHERE client_id != 'chatgpt' ORDER BY created_at ASC LIMIT 20
211
+ )
212
+ """)
213
+
214
+ conn.execute("""
215
+ INSERT INTO oauth_clients (client_id, client_secret, client_name, redirect_uris, grant_types, response_types, created_at)
216
+ VALUES (?, ?, ?, ?, ?, ?, ?)
217
+ """, (
218
+ client_id,
219
+ client_secret,
220
+ record["client_name"],
221
+ json.dumps(record["redirect_uris"]),
222
+ json.dumps(record["grant_types"]),
223
+ json.dumps(record["response_types"]),
224
+ record["created_at"],
225
+ ))
226
+ return record
227
+
228
+ def create_auth_code(
229
+ self,
230
+ client_id: str,
231
+ redirect_uri: str,
232
+ code_challenge: str,
233
+ code_challenge_method: str = "S256",
234
+ scope: str = "",
235
+ ) -> str:
236
+ """Issue an authorization code stored safely in SQLite."""
237
+ code = f"auth_code_{secrets.token_urlsafe(24)}"
238
+ now = time.time()
239
+ expires_at = now + 600 # 10 minutes
240
+ with self._db_conn() as conn:
241
+ conn.execute("""
242
+ INSERT INTO oauth_codes (code, client_id, redirect_uri, code_challenge, code_challenge_method, scope, expires_at, created_at)
243
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
244
+ """, (code, client_id, redirect_uri, code_challenge, code_challenge_method, scope, expires_at, now))
245
+ return code
246
+
247
+ def exchange_code_for_token(
248
+ self,
249
+ code: str,
250
+ client_id: str,
251
+ redirect_uri: str,
252
+ code_verifier: str,
253
+ ) -> dict[str, Any]:
254
+ """Exchange authorization code and PKCE verifier for a persistent access token."""
255
+ now = time.time()
256
+ with self._db_conn() as conn:
257
+ row = conn.execute("SELECT * FROM oauth_codes WHERE code = ?", (code,)).fetchone()
258
+ if not row:
259
+ raise ValueError("Invalid or expired authorization code")
260
+ auth_data = dict(row)
261
+
262
+ if now > auth_data["expires_at"]:
263
+ conn.execute("DELETE FROM oauth_codes WHERE code = ?", (code,))
264
+ raise ValueError("Authorization code has expired")
265
+
266
+ if client_id and auth_data["client_id"] != client_id:
267
+ raise ValueError("client_id mismatch")
268
+
269
+ challenge = auth_data["code_challenge"]
270
+ method = auth_data.get("code_challenge_method", "S256")
271
+ if challenge and not verify_pkce(code_verifier, challenge, method):
272
+ raise ValueError("PKCE code verification failed")
273
+
274
+ # Invalidate used code
275
+ conn.execute("DELETE FROM oauth_codes WHERE code = ?", (code,))
276
+
277
+ access_token = f"mcp_tok_{secrets.token_urlsafe(32)}"
278
+ expires_in = 86400 * 30 # 30 days
279
+ expires_at = now + expires_in
280
+ scope = auth_data.get("scope") or "mcp:read mcp:write"
281
+
282
+ conn.execute("""
283
+ INSERT INTO oauth_tokens (access_token, token_type, expires_in, expires_at, created_at, scope, client_id)
284
+ VALUES (?, ?, ?, ?, ?, ?, ?)
285
+ """, (access_token, "Bearer", expires_in, expires_at, now, scope, auth_data["client_id"]))
286
+
287
+ return {
288
+ "access_token": access_token,
289
+ "token_type": "Bearer",
290
+ "expires_in": expires_in,
291
+ "created_at": now,
292
+ "scope": scope,
293
+ "client_id": auth_data["client_id"],
294
+ }
295
+
296
+ def is_token_valid(self, token: str) -> bool:
297
+ """Check whether an issued access token or static admin password is valid."""
298
+ if not token:
299
+ return False
300
+ if self.admin_password and token == self.admin_password:
301
+ return True
302
+ now = time.time()
303
+ with self._db_conn() as conn:
304
+ row = conn.execute("SELECT expires_at FROM oauth_tokens WHERE access_token = ?", (token,)).fetchone()
305
+ if row:
306
+ if now < row["expires_at"]:
307
+ return True
308
+ else:
309
+ conn.execute("DELETE FROM oauth_tokens WHERE access_token = ?", (token,))
310
+ return False
311
+
312
+
313
+ def get_server_public_url(request: Request) -> str:
314
+ """Determine public base URL honoring reverse proxy headers and env overrides."""
315
+ override = os.getenv("PUBLIC_BASE_URL")
316
+ if override:
317
+ return override.rstrip("/")
318
+
319
+ forwarded_proto = request.headers.get("x-forwarded-proto") or request.url.scheme
320
+ forwarded_host = request.headers.get("x-forwarded-host") or request.headers.get("host") or request.url.netloc
321
+ return f"{forwarded_proto}://{forwarded_host}".rstrip("/")
322
+
323
+
324
+ async def oauth_protected_resource_endpoint(request: Request) -> Response:
325
+ """RFC 9728 OAuth Protected Resource Metadata document for ChatGPT."""
326
+ public_url = get_server_public_url(request)
327
+ auth0_domain = os.getenv("AUTH0_DOMAIN", "").replace("https://", "").rstrip("/")
328
+ issuer = f"https://{auth0_domain}" if auth0_domain else public_url
329
+
330
+ req_resource = request.query_params.get("resource")
331
+ if req_resource:
332
+ resource_uri = req_resource
333
+ elif request.url.path.rstrip("/").endswith("/mcp"):
334
+ resource_uri = f"{public_url}/mcp"
335
+ else:
336
+ resource_uri = f"{public_url}/mcp"
337
+
338
+ metadata = {
339
+ "resource": resource_uri,
340
+ "authorization_servers": [issuer],
341
+ "scopes_supported": ["openid", "profile", "email", "mcp:read", "mcp:write"],
342
+ "resource_documentation": f"{public_url}/",
343
+ }
344
+ return JSONResponse(metadata, headers={"Access-Control-Allow-Origin": "*"})
345
+
346
+
347
+ async def oauth_authorization_server_metadata_endpoint(request: Request) -> Response:
348
+ """RFC 8414 OAuth 2.0 Authorization Server Metadata document for ChatGPT."""
349
+ public_url = get_server_public_url(request)
350
+
351
+ metadata = {
352
+ "issuer": public_url,
353
+ "authorization_endpoint": f"{public_url}/oauth/authorize",
354
+ "token_endpoint": f"{public_url}/oauth/token",
355
+ "registration_endpoint": f"{public_url}/oauth/register",
356
+ "jwks_uri": f"{public_url}/oauth/jwks.json",
357
+ "response_types_supported": ["code"],
358
+ "grant_types_supported": ["authorization_code", "refresh_token"],
359
+ "code_challenge_methods_supported": ["S256", "plain"],
360
+ "token_endpoint_auth_methods_supported": ["none", "client_secret_post", "client_secret_basic"],
361
+ "scopes_supported": ["openid", "profile", "email", "mcp:read", "mcp:write"],
362
+ "subject_types_supported": ["public"],
363
+ }
364
+ return JSONResponse(metadata, headers={"Access-Control-Allow-Origin": "*"})
365
+
366
+
367
+ async def oauth_jwks_endpoint(request: Request) -> Response:
368
+ """JWKS endpoint returning empty or public keys for OIDC validation."""
369
+ return JSONResponse({"keys": []}, headers={"Access-Control-Allow-Origin": "*"})
370
+
371
+
372
+ async def oauth_register_endpoint(request: Request, oauth_server: LocalOAuthServer) -> Response:
373
+ """RFC 7591 Dynamic Client Registration endpoint for ChatGPT with rate limiting."""
374
+ client_ip = get_client_ip(request)
375
+ if not oauth_server.rate_limiter.check_dcr_rate_limit(client_ip):
376
+ return JSONResponse(
377
+ {"error": "rate_limit_exceeded", "error_description": "Too many client registration requests. Please wait."},
378
+ status_code=429,
379
+ headers={"Access-Control-Allow-Origin": "*", "Retry-After": "3600"},
380
+ )
381
+ try:
382
+ body = await request.json()
383
+ except Exception:
384
+ body = {}
385
+
386
+ client_info = oauth_server.register_client(body)
387
+ return JSONResponse(client_info, status_code=201, headers={"Access-Control-Allow-Origin": "*"})
388
+
389
+
390
+ async def oauth_authorize_endpoint(request: Request, oauth_server: LocalOAuthServer) -> Response:
391
+ """Handle OAuth 2.1 authorization consent page and code generation with brute-force defense."""
392
+ client_ip = get_client_ip(request)
393
+ is_locked, remaining_seconds = oauth_server.rate_limiter.is_locked_out(client_ip)
394
+ if is_locked:
395
+ err_msg = f"❌ 连续输入错误密码过多,IP 已被安全锁定。请在 {remaining_seconds} 秒后再试!"
396
+ html_page = _render_consent_html(
397
+ error_msg=err_msg,
398
+ client_id=request.query_params.get("client_id", ""),
399
+ redirect_uri=request.query_params.get("redirect_uri", ""),
400
+ scope=request.query_params.get("scope", ""),
401
+ state=request.query_params.get("state", ""),
402
+ code_challenge=request.query_params.get("code_challenge", ""),
403
+ code_challenge_method=request.query_params.get("code_challenge_method", "S256"),
404
+ )
405
+ return HTMLResponse(html_page, status_code=429, headers={"Retry-After": str(remaining_seconds)})
406
+
407
+ params = request.query_params
408
+ response_type = params.get("response_type", "code")
409
+ client_id = params.get("client_id", "")
410
+ redirect_uri = params.get("redirect_uri", "")
411
+ scope = params.get("scope", "")
412
+ state = params.get("state", "")
413
+ code_challenge = params.get("code_challenge", "")
414
+ code_challenge_method = params.get("code_challenge_method", "S256")
415
+
416
+ if request.method == "POST":
417
+ form = await request.form()
418
+ password = str(form.get("password", "")).strip()
419
+ f_client_id = str(form.get("client_id", client_id))
420
+ f_redirect_uri = str(form.get("redirect_uri", redirect_uri))
421
+ f_scope = str(form.get("scope", scope))
422
+ f_state = str(form.get("state", state))
423
+ f_challenge = str(form.get("code_challenge", code_challenge))
424
+ f_method = str(form.get("code_challenge_method", code_challenge_method))
425
+
426
+ if oauth_server.admin_password and password != oauth_server.admin_password:
427
+ is_locked, lockout_secs, remaining_attempts = oauth_server.rate_limiter.record_failure(client_ip)
428
+ if is_locked:
429
+ err_text = f"❌ 密码错误次数超限!IP 已触发锁定保护,请在 {lockout_secs} 秒后重试。"
430
+ status_code = 429
431
+ headers = {"Retry-After": str(lockout_secs)}
432
+ else:
433
+ err_text = f"❌ 访问密码错误!还可尝试 {remaining_attempts} 次。"
434
+ status_code = 401
435
+ headers = {}
436
+
437
+ error_html = _render_consent_html(
438
+ error_msg=err_text,
439
+ client_id=f_client_id,
440
+ redirect_uri=f_redirect_uri,
441
+ scope=f_scope,
442
+ state=f_state,
443
+ code_challenge=f_challenge,
444
+ code_challenge_method=f_method,
445
+ )
446
+ return HTMLResponse(error_html, status_code=status_code, headers=headers)
447
+
448
+ oauth_server.rate_limiter.record_success(client_ip)
449
+
450
+ code = oauth_server.create_auth_code(
451
+ client_id=f_client_id,
452
+ redirect_uri=f_redirect_uri,
453
+ code_challenge=f_challenge,
454
+ code_challenge_method=f_method,
455
+ scope=f_scope,
456
+ )
457
+
458
+ query_parts = {"code": code}
459
+ if f_state:
460
+ query_parts["state"] = f_state
461
+
462
+ sep = "&" if "?" in f_redirect_uri else "?"
463
+ callback_url = f"{f_redirect_uri}{sep}{urlencode(query_parts)}"
464
+ return RedirectResponse(callback_url, status_code=302)
465
+
466
+ content = _render_consent_html(
467
+ error_msg="",
468
+ client_id=client_id,
469
+ redirect_uri=redirect_uri,
470
+ scope=scope,
471
+ state=state,
472
+ code_challenge=code_challenge,
473
+ code_challenge_method=code_challenge_method,
474
+ )
475
+ return HTMLResponse(content)
476
+
477
+
478
+ async def oauth_token_endpoint(request: Request, oauth_server: LocalOAuthServer) -> Response:
479
+ """RFC 6749 & RFC 7636 Token Endpoint with PKCE verification."""
480
+ content_type = request.headers.get("content-type", "")
481
+ if "application/json" in content_type:
482
+ try:
483
+ data = await request.json()
484
+ except Exception:
485
+ data = {}
486
+ else:
487
+ form = await request.form()
488
+ data = dict(form)
489
+
490
+ grant_type = data.get("grant_type")
491
+ code = data.get("code", "")
492
+ client_id = data.get("client_id", "")
493
+ redirect_uri = data.get("redirect_uri", "")
494
+ code_verifier = data.get("code_verifier", "")
495
+
496
+ auth_header = request.headers.get("authorization", "")
497
+ if auth_header.startswith("Basic "):
498
+ try:
499
+ decoded = base64.b64decode(auth_header[6:]).decode("utf-8")
500
+ if ":" in decoded:
501
+ client_id = decoded.split(":")[0]
502
+ except Exception:
503
+ pass
504
+
505
+ if grant_type != "authorization_code":
506
+ return JSONResponse(
507
+ {"error": "unsupported_grant_type", "error_description": "Only authorization_code is supported"},
508
+ status_code=400,
509
+ headers={"Access-Control-Allow-Origin": "*"},
510
+ )
511
+
512
+ try:
513
+ token_info = oauth_server.exchange_code_for_token(
514
+ code=code,
515
+ client_id=client_id,
516
+ redirect_uri=redirect_uri,
517
+ code_verifier=code_verifier,
518
+ )
519
+ return JSONResponse(token_info, headers={"Access-Control-Allow-Origin": "*"})
520
+ except ValueError as e:
521
+ return JSONResponse(
522
+ {"error": "invalid_grant", "error_description": str(e)},
523
+ status_code=400,
524
+ headers={"Access-Control-Allow-Origin": "*"},
525
+ )
526
+
527
+
528
+ def _render_consent_html(
529
+ error_msg: str,
530
+ client_id: str,
531
+ redirect_uri: str,
532
+ scope: str,
533
+ state: str,
534
+ code_challenge: str,
535
+ code_challenge_method: str,
536
+ ) -> str:
537
+ """Render clean, responsive HTML consent page for ChatGPT."""
538
+ err_block = f'<div style="color: #ef4444; background: #fee2e2; border: 1px solid #f87171; padding: 10px; border-radius: 6px; margin-bottom: 16px; font-size: 14px;">{html.escape(error_msg)}</div>' if error_msg else ""
539
+ return f"""<!DOCTYPE html>
540
+ <html lang="zh-CN">
541
+ <head>
542
+ <meta charset="UTF-8">
543
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
544
+ <title>ChatGPT / MCP 授权登录</title>
545
+ <style>
546
+ body {{
547
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
548
+ background: #f3f4f6;
549
+ display: flex;
550
+ align-items: center;
551
+ justify-content: center;
552
+ min-height: 100vh;
553
+ margin: 0;
554
+ padding: 16px;
555
+ }}
556
+ .card {{
557
+ background: #ffffff;
558
+ border-radius: 12px;
559
+ box-shadow: 0 10px 25px rgba(0, 0, 0, 0.08);
560
+ width: 100%;
561
+ max-width: 440px;
562
+ padding: 32px;
563
+ box-sizing: border-box;
564
+ }}
565
+ h2 {{
566
+ margin-top: 0;
567
+ color: #111827;
568
+ font-size: 22px;
569
+ display: flex;
570
+ align-items: center;
571
+ gap: 8px;
572
+ }}
573
+ p {{
574
+ color: #4b5563;
575
+ font-size: 14px;
576
+ line-height: 1.5;
577
+ }}
578
+ .badge {{
579
+ background: #e0f2fe;
580
+ color: #0369a1;
581
+ padding: 2px 8px;
582
+ border-radius: 4px;
583
+ font-size: 12px;
584
+ font-weight: 600;
585
+ }}
586
+ label {{
587
+ display: block;
588
+ margin-bottom: 6px;
589
+ font-size: 14px;
590
+ color: #374151;
591
+ font-weight: 500;
592
+ }}
593
+ input[type="password"] {{
594
+ width: 100%;
595
+ padding: 10px 12px;
596
+ border: 1px solid #d1d5db;
597
+ border-radius: 6px;
598
+ font-size: 15px;
599
+ box-sizing: border-box;
600
+ outline: none;
601
+ transition: border-color 0.2s;
602
+ }}
603
+ input[type="password"]:focus {{
604
+ border-color: #2563eb;
605
+ box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.15);
606
+ }}
607
+ button {{
608
+ width: 100%;
609
+ background: #10a37f;
610
+ color: #ffffff;
611
+ border: none;
612
+ padding: 12px;
613
+ border-radius: 6px;
614
+ font-size: 15px;
615
+ font-weight: 600;
616
+ cursor: pointer;
617
+ margin-top: 20px;
618
+ transition: background 0.2s;
619
+ }}
620
+ button:hover {{
621
+ background: #0e8c6d;
622
+ }}
623
+ .footer {{
624
+ margin-top: 20px;
625
+ font-size: 12px;
626
+ color: #9ca3af;
627
+ text-align: center;
628
+ }}
629
+ </style>
630
+ </head>
631
+ <body>
632
+ <div class="card">
633
+ <h2>🚀 ChatGPT / MCP 安全授权</h2>
634
+ <p>远程 <b>ChatGPT</b> / AI Agent 客户端正在请求连接本机 <b>MCP Server</b>,请验证管理员访问密码以完成授权绑定。</p>
635
+ <p><span class="badge">安全隔离</span> 权限仅对经过授权的会话生效。</p>
636
+
637
+ {err_block}
638
+
639
+ <form method="POST">
640
+ <input type="hidden" name="client_id" value="{html.escape(client_id)}">
641
+ <input type="hidden" name="redirect_uri" value="{html.escape(redirect_uri)}">
642
+ <input type="hidden" name="scope" value="{html.escape(scope)}">
643
+ <input type="hidden" name="state" value="{html.escape(state)}">
644
+ <input type="hidden" name="code_challenge" value="{html.escape(code_challenge)}">
645
+ <input type="hidden" name="code_challenge_method" value="{html.escape(code_challenge_method)}">
646
+
647
+ <label for="password">请输入本机安全访问密钥 (API Key):</label>
648
+ <input type="password" id="password" name="password" required autofocus placeholder="输入控制台或 .env 中的访问密钥">
649
+
650
+ <button type="submit">确认授权客户端访问</button>
651
+ </form>
652
+
653
+ <div class="footer">
654
+ Local MCP Server • RFC 9728 & OAuth 2.1
655
+ </div>
656
+ </div>
657
+ </body>
658
+ </html>"""