diff --git a/CLAUDE.md b/CLAUDE.md index 2029d3a..da0de15 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -203,6 +203,19 @@ se desactiva porque el modelo diga `none`. back into this same app in-process (`httpx.ASGITransport`) forwarding the caller's auth headers, so it can never drift from the REST behavior. Cloud mode 401s without a resolvable user; self-host stays BYOK-open. +- **OAuth for MCP clients** (`cloud/mcp_oauth.py`, cloud mode only): claude.ai + and ChatGPT connect by URL, so the server publishes RFC 9728/8414 metadata + under `/.well-known/`, accepts dynamic client registration (`POST + /oauth/register`, public clients, PKCE S256 mandatory) and bounces + `GET /oauth/authorize` to the dashboard consent screen (`#/oauth/authorize`), + because the session JWT lives in localStorage on the frontend host and a + bare API GET cannot see it. `POST /api/oauth/authorize` (session auth) mints + the code; `POST /oauth/token` redeems it by **minting an ordinary `osk_` + key** named after the client and returning it as the access token. No new + auth path, no refresh tokens: the key shows up in Account → API keys and + revoking it disconnects the app. The `/mcp` 401 carries + `WWW-Authenticate: Bearer resource_metadata=...` so clients find the flow. + `oauth_codes` is in `USER_OWNED_TABLES`; `oauth_clients` deliberately not. - **Webhooks**: `POST /api/process` takes `webhook_url` + optional `webhook_secret` (HMAC-SHA256, `X-OpenShorts-Signature`). Validated with `security_utils.assert_public_url` at submit AND at delivery (DNS rebinding). diff --git a/README.md b/README.md index 8a9f58b..db2d09f 100644 --- a/README.md +++ b/README.md @@ -303,8 +303,10 @@ You don't need the dashboard. The whole pipeline is callable by AI agents and sc OpenShorts ships a built-in [MCP](https://modelcontextprotocol.io) server, so Claude, ChatGPT, Cursor or any MCP client can clip and publish videos for you: +**claude.ai and ChatGPT**: paste `https://mcp.openshorts.app/mcp` as a custom connector (Settings → Connectors) and approve the access on openshorts.app. The server does OAuth 2.1 with dynamic client registration, so there is no key to copy; the connection shows up under Account → API keys, where revoking it disconnects the app. + ```bash -# Hosted (create an API key in your account page at openshorts.app): +# Claude Code / Cursor / n8n (hosted): create an API key in your account page claude mcp add --transport http openshorts https://mcp.openshorts.app/mcp \ --header "Authorization: Bearer osk_..." diff --git a/cloud/__init__.py b/cloud/__init__.py index 8be2a51..0abb659 100644 --- a/cloud/__init__.py +++ b/cloud/__init__.py @@ -26,7 +26,7 @@ def setup_sync(app): from starlette.middleware.sessions import SessionMiddleware app.add_middleware(SessionMiddleware, secret_key=settings.jwt_secret) - from . import auth, oauth, billing, social_profiles, videos, api_keys, account + from . import auth, oauth, billing, social_profiles, videos, api_keys, account, mcp_oauth oauth.register() billing._init_stripe() app.include_router(auth.router) @@ -35,6 +35,7 @@ def setup_sync(app): app.include_router(social_profiles.router) app.include_router(videos.router) app.include_router(api_keys.router) + app.include_router(mcp_oauth.router) app.include_router(account.router) diff --git a/cloud/account.py b/cloud/account.py index 9781305..60a003a 100644 --- a/cloud/account.py +++ b/cloud/account.py @@ -41,7 +41,7 @@ from . import database, email_policy, storage from .models import ( User, Subscription, CreditTopup, UsageLedger, MagicLinkToken, SignupAttribution, ApiKey, UploadPostProfile, UserVideo, ClipExpiryWarning, - Project, AccountDeletion, + Project, AccountDeletion, OAuthCode, ) # Every table that holds rows belonging to a user, child-first (clip_expiry_ @@ -55,7 +55,7 @@ from .models import ( # foreign-key violation the first time a real user tries to leave. USER_OWNED_TABLES = ( ClipExpiryWarning, UserVideo, Project, UsageLedger, CreditTopup, - Subscription, ApiKey, SignupAttribution, UploadPostProfile, + Subscription, ApiKey, SignupAttribution, UploadPostProfile, OAuthCode, ) # The optional "why are you leaving" answer, as a closed list. It was a free diff --git a/cloud/mcp_oauth.py b/cloud/mcp_oauth.py new file mode 100644 index 0000000..921d376 --- /dev/null +++ b/cloud/mcp_oauth.py @@ -0,0 +1,357 @@ +"""OAuth 2.1 authorization server for the MCP endpoint (cloud mode). + +claude.ai and ChatGPT connect to a remote MCP server by URL alone: the user +pastes ``https://mcp.openshorts.app/mcp`` and the client discovers how to log +in from the server's metadata. That takes the pieces those clients actually +use, and nothing else: + +* RFC 9728 protected-resource metadata (``/.well-known/oauth-protected-resource``), + which the ``/mcp`` 401 points at via ``WWW-Authenticate``; +* RFC 8414 authorization-server metadata (``/.well-known/oauth-authorization-server``); +* RFC 7591 dynamic client registration (``POST /oauth/register``), because + neither client ships a pre-shared client id; +* the authorization-code grant with PKCE S256 and **no client secret**: these + are public clients, PKCE is what binds the code to whoever started the flow. + +The consent screen lives in the dashboard (``#/oauth/authorize``), not here: +the session is a bearer JWT in localStorage on www.openshorts.app, which a +plain browser GET to the API cannot see. So ``GET /oauth/authorize`` validates +the request and bounces to the dashboard, the dashboard signs the user in if +needed and asks "connect Claude to your account?", and ``POST /api/oauth/authorize`` +(session-authenticated) mints the code and hands back the redirect. + +Redeeming the code mints an ordinary ``osk_`` API key named after the client +and returns it as the access token. That is deliberate: every existing auth, +quota and ownership rule already understands those keys, the connection shows +up in the account page next to hand-made keys, and revoking it there is how +the user disconnects the client. No refresh tokens: the key does not expire. +""" +import base64 +import hashlib +import json +import secrets +from datetime import datetime, timedelta, timezone +from typing import Optional +from urllib.parse import urlencode, urlsplit, urlunsplit, parse_qsl + +from fastapi import APIRouter, HTTPException, Request +from fastapi.responses import JSONResponse, RedirectResponse +from pydantic import BaseModel +from sqlalchemy import select + +from . import database, api_keys +from .config import settings +from .models import OAuthClient, OAuthCode, ApiKey + +router = APIRouter() + +SCOPE = "openshorts" +CODE_TTL = timedelta(minutes=10) +MAX_REDIRECT_URIS = 10 + + +def _now(): + return datetime.now(timezone.utc) + + +# --------------------------------------------------------------------------- # +# Pure helpers (unit-tested without a database) +# --------------------------------------------------------------------------- # +def base_url(request: Request) -> str: + """The origin the client is talking to, so the metadata names the host the + client actually used (mcp.openshorts.app or api.openshorts.app both route + here). uvicorn runs with --proxy-headers, so the scheme is the public one.""" + u = request.base_url + return f"{u.scheme}://{u.netloc}" + + +def resource_metadata(base: str) -> dict: + return { + "resource": f"{base}/mcp", + "authorization_servers": [base], + "bearer_methods_supported": ["header"], + "scopes_supported": [SCOPE], + "resource_name": "OpenShorts", + "resource_documentation": "https://www.openshorts.app/mcp", + } + + +def server_metadata(base: str) -> dict: + return { + "issuer": base, + "authorization_endpoint": f"{base}/oauth/authorize", + "token_endpoint": f"{base}/oauth/token", + "registration_endpoint": f"{base}/oauth/register", + "response_types_supported": ["code"], + "response_modes_supported": ["query"], + "grant_types_supported": ["authorization_code"], + "code_challenge_methods_supported": ["S256"], + "token_endpoint_auth_methods_supported": ["none"], + "scopes_supported": [SCOPE], + "service_documentation": "https://www.openshorts.app/mcp", + } + + +def valid_redirect_uri(uri: str) -> bool: + """https anywhere, or plain http only on the loopback (CLI clients open a + local listener to catch the redirect). No fragments, no wildcards.""" + try: + p = urlsplit(uri) + except ValueError: + return False + if p.fragment or not p.netloc: + return False + host = (p.hostname or "").lower() + if p.scheme == "https": + return True + if p.scheme == "http": + return host in ("localhost", "127.0.0.1", "::1") + return False + + +def pkce_matches(code_verifier: str, code_challenge: str) -> bool: + if not code_verifier or not code_challenge: + return False + if not (43 <= len(code_verifier) <= 128): + return False + digest = hashlib.sha256(code_verifier.encode("ascii")).digest() + expected = base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii") + return secrets.compare_digest(expected, code_challenge) + + +def add_query(uri: str, **params) -> str: + """Append params to a redirect URI, keeping any query it already has.""" + p = urlsplit(uri) + q = parse_qsl(p.query, keep_blank_values=True) + q.extend((k, v) for k, v in params.items() if v is not None) + return urlunsplit((p.scheme, p.netloc, p.path, urlencode(q), "")) + + +def hash_code(code: str) -> str: + return hashlib.sha256(code.encode()).hexdigest() + + +def consent_url(base_frontend: str, params: dict) -> str: + """Where the dashboard renders the consent screen. The params ride in the + hash's query so the SPA (hash router) can read them.""" + return f"{base_frontend.rstrip('/')}/#/oauth/authorize?{urlencode(params)}" + + +def _oauth_error(status: int, error: str, description: str): + return JSONResponse({"error": error, "error_description": description}, status_code=status) + + +# --------------------------------------------------------------------------- # +# Discovery +# --------------------------------------------------------------------------- # +@router.get("/.well-known/oauth-protected-resource") +@router.get("/.well-known/oauth-protected-resource/mcp") +async def protected_resource(request: Request): + return JSONResponse(resource_metadata(base_url(request)), + headers={"Access-Control-Allow-Origin": "*"}) + + +@router.get("/.well-known/oauth-authorization-server") +@router.get("/.well-known/oauth-authorization-server/mcp") +async def authorization_server(request: Request): + return JSONResponse(server_metadata(base_url(request)), + headers={"Access-Control-Allow-Origin": "*"}) + + +# --------------------------------------------------------------------------- # +# Dynamic client registration (RFC 7591) +# --------------------------------------------------------------------------- # +@router.post("/oauth/register", status_code=201) +async def register_client(request: Request): + try: + body = json.loads(await request.body() or b"{}") + except ValueError: + return _oauth_error(400, "invalid_client_metadata", "Body must be JSON.") + if not isinstance(body, dict): + return _oauth_error(400, "invalid_client_metadata", "Body must be a JSON object.") + + uris = body.get("redirect_uris") + if not isinstance(uris, list) or not uris or len(uris) > MAX_REDIRECT_URIS: + return _oauth_error(400, "invalid_redirect_uri", + f"redirect_uris must list 1 to {MAX_REDIRECT_URIS} URIs.") + uris = [str(u) for u in uris] + bad = [u for u in uris if not valid_redirect_uri(u)] + if bad: + return _oauth_error(400, "invalid_redirect_uri", + f"redirect_uris must be https (or http on localhost): {bad[0]}") + + auth_method = body.get("token_endpoint_auth_method") or "none" + if auth_method != "none": + return _oauth_error(400, "invalid_client_metadata", + "Only public clients (token_endpoint_auth_method=none) are supported.") + grants = body.get("grant_types") or ["authorization_code"] + if any(g not in ("authorization_code", "refresh_token") for g in grants): + return _oauth_error(400, "invalid_client_metadata", + "Only the authorization_code grant is supported.") + + name = str(body.get("client_name") or "MCP client").strip()[:80] or "MCP client" + client_id = secrets.token_urlsafe(24) + async with database.session() as session: + session.add(OAuthClient(id=client_id, client_name=name, redirect_uris=json.dumps(uris))) + await session.commit() + + return JSONResponse({ + "client_id": client_id, + "client_id_issued_at": int(_now().timestamp()), + "client_name": name, + "redirect_uris": uris, + "token_endpoint_auth_method": "none", + "grant_types": ["authorization_code"], + "response_types": ["code"], + "scope": SCOPE, + }, status_code=201, headers={"Access-Control-Allow-Origin": "*"}) + + +async def _load_client(client_id: str) -> Optional[OAuthClient]: + if not client_id: + return None + async with database.session() as session: + return (await session.execute( + select(OAuthClient).where(OAuthClient.id == client_id))).scalar_one_or_none() + + +def _client_allows(client: OAuthClient, redirect_uri: str) -> bool: + try: + return redirect_uri in json.loads(client.redirect_uris) + except ValueError: + return False + + +# --------------------------------------------------------------------------- # +# Authorization: browser GET bounces to the dashboard consent screen +# --------------------------------------------------------------------------- # +AUTHORIZE_PARAMS = ("client_id", "redirect_uri", "response_type", "state", + "code_challenge", "code_challenge_method", "scope", "resource") + + +async def _validate_authorize(params: dict): + """Returns (client, error) where error is (code, description). A bad + client_id / redirect_uri is reported to the user, never redirected: the + spec forbids sending the browser to an unverified URI.""" + client = await _load_client(params.get("client_id", "")) + if client is None: + raise HTTPException(status_code=400, detail="Unknown client_id.") + redirect_uri = params.get("redirect_uri", "") + if not redirect_uri or not _client_allows(client, redirect_uri): + raise HTTPException(status_code=400, detail="redirect_uri is not registered for this client.") + if params.get("response_type") != "code": + return client, ("unsupported_response_type", "Only response_type=code is supported.") + if not params.get("code_challenge"): + return client, ("invalid_request", "PKCE code_challenge is required.") + if (params.get("code_challenge_method") or "S256") != "S256": + return client, ("invalid_request", "Only code_challenge_method=S256 is supported.") + return client, None + + +@router.get("/oauth/authorize") +async def authorize(request: Request): + params = {k: request.query_params.get(k) for k in AUTHORIZE_PARAMS if request.query_params.get(k)} + client, err = await _validate_authorize(params) + if err: + return RedirectResponse(add_query(params["redirect_uri"], error=err[0], + error_description=err[1], state=params.get("state")), + status_code=302) + return RedirectResponse(consent_url(settings.frontend_url, params), status_code=302) + + +@router.get("/api/oauth/client/{client_id}") +async def client_info(client_id: str): + """What the consent screen shows: the name the client registered with.""" + client = await _load_client(client_id) + if client is None: + raise HTTPException(status_code=404, detail="Unknown client_id.") + return {"client_id": client.id, "client_name": client.client_name} + + +class ConsentRequest(BaseModel): + client_id: str + redirect_uri: str + state: Optional[str] = None + code_challenge: str + code_challenge_method: Optional[str] = "S256" + scope: Optional[str] = None + response_type: Optional[str] = "code" + + +@router.post("/api/oauth/authorize") +async def consent(payload: ConsentRequest, request: Request): + """The user said yes on the dashboard: mint the code, return where to go.""" + from .auth import get_current_user_required + user = await get_current_user_required(request) + params = payload.model_dump(exclude_none=True) + client, err = await _validate_authorize(params) + if err: + return {"redirect": add_query(payload.redirect_uri, error=err[0], + error_description=err[1], state=payload.state)} + code = secrets.token_urlsafe(32) + async with database.session() as session: + session.add(OAuthCode( + code_hash=hash_code(code), client_id=client.id, user_id=user.id, + redirect_uri=payload.redirect_uri, code_challenge=payload.code_challenge, + scope=payload.scope or SCOPE, expires_at=_now() + CODE_TTL)) + await session.commit() + return {"redirect": add_query(payload.redirect_uri, code=code, state=payload.state)} + + +# --------------------------------------------------------------------------- # +# Token +# --------------------------------------------------------------------------- # +@router.post("/oauth/token") +async def token(request: Request): + ctype = request.headers.get("content-type", "") + if "application/json" in ctype: + try: + form = json.loads(await request.body() or b"{}") + except ValueError: + return _oauth_error(400, "invalid_request", "Malformed JSON body.") + else: + form = dict(await request.form()) + grant = form.get("grant_type") + if grant != "authorization_code": + return _oauth_error(400, "unsupported_grant_type", + "Only authorization_code is supported (tokens do not expire).") + code = str(form.get("code") or "") + verifier = str(form.get("code_verifier") or "") + client_id = str(form.get("client_id") or "") + redirect_uri = str(form.get("redirect_uri") or "") + + async with database.session() as session: + row = (await session.execute( + select(OAuthCode).where(OAuthCode.code_hash == hash_code(code)))).scalar_one_or_none() + if row is None or row.used_at is not None or row.expires_at < _now(): + return _oauth_error(400, "invalid_grant", "Unknown, used or expired code.") + if row.client_id != client_id or (redirect_uri and row.redirect_uri != redirect_uri): + return _oauth_error(400, "invalid_grant", "Code was issued to another client or redirect_uri.") + if not pkce_matches(verifier, row.code_challenge): + return _oauth_error(400, "invalid_grant", "PKCE verification failed.") + client = (await session.execute( + select(OAuthClient).where(OAuthClient.id == client_id))).scalar_one_or_none() + row.used_at = _now() + + raw, key_hash, prefix = api_keys.generate_key() + session.add(ApiKey(user_id=row.user_id, key_hash=key_hash, prefix=prefix, + name=f"{(client.client_name if client else 'MCP client')[:50]} · connected via OAuth")) + await session.commit() + + return JSONResponse({"access_token": raw, "token_type": "bearer", "scope": row.scope or SCOPE}, + headers={"Cache-Control": "no-store", "Access-Control-Allow-Origin": "*"}) + + +@router.options("/oauth/register") +@router.options("/oauth/token") +async def preflight(): + return JSONResponse({}, headers={ + "Access-Control-Allow-Origin": "*", + "Access-Control-Allow-Methods": "POST, OPTIONS", + "Access-Control-Allow-Headers": "Content-Type, Authorization", + }) + + +def www_authenticate(base: str) -> str: + """Value for the 401 on /mcp: tells an OAuth-capable client where to look.""" + return f'Bearer resource_metadata="{base}/.well-known/oauth-protected-resource"' diff --git a/cloud/models.py b/cloud/models.py index 0b915e2..6cd8c1d 100644 --- a/cloud/models.py +++ b/cloud/models.py @@ -255,3 +255,34 @@ class AccountDeletion(Base): r2_objects_deleted = Column(Integer, nullable=True) reason = Column(String(32), nullable=True) # one of account.DELETION_REASONS deleted_at = Column(DateTime(timezone=True), server_default=func.now()) + + +class OAuthClient(Base): + """An MCP client registered through OAuth dynamic client registration + (RFC 7591): claude.ai, ChatGPT, Cursor... They are public clients (no + secret): PKCE is what ties the authorization code to the party that + started the flow. Rows are not user-owned — one registration serves every + user of that client — so they survive account erasure.""" + __tablename__ = "oauth_clients" + id = Column(Text, primary_key=True) # client_id + client_name = Column(Text, nullable=False) + redirect_uris = Column(Text, nullable=False) # JSON list + created_at = Column(DateTime(timezone=True), server_default=func.now()) + + +class OAuthCode(Base): + """A short-lived authorization code (10 min, single use). Only its sha256 + is stored; the code itself travels once, in the redirect back to the + client. Redeeming it mints an ``osk_`` API key for the user, which is what + the client keeps as its access token: the key shows up in the account + page like any other, and revoking it there disconnects the client.""" + __tablename__ = "oauth_codes" + code_hash = Column(Text, primary_key=True) + client_id = Column(Text, ForeignKey("oauth_clients.id", ondelete="CASCADE"), nullable=False) + user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), + nullable=False, index=True) + redirect_uri = Column(Text, nullable=False) + code_challenge = Column(Text, nullable=False) + scope = Column(Text, nullable=True) + expires_at = Column(DateTime(timezone=True), nullable=False) + used_at = Column(DateTime(timezone=True), nullable=True) diff --git a/dashboard/seo/pages.js b/dashboard/seo/pages.js index 6a13ed6..06233c0 100644 --- a/dashboard/seo/pages.js +++ b/dashboard/seo/pages.js @@ -1045,17 +1045,25 @@ YouTube URL, turn it into 3 to 15 vertical clips with word-level captions, restyle those captions, and publish or schedule the result to TikTok, Instagram Reels and YouTube Shorts.

-

How do I connect Claude or another MCP client?

+

How do I connect Claude or ChatGPT?

+

With the URL alone. The server implements OAuth 2.1 with dynamic client +registration, which is what claude.ai and ChatGPT expect from a remote MCP +server, so there is no key to copy:

    -
  1. Sign in at openshorts.app and create an API key in your account page. The key is shown once and starts with osk_.
  2. -
  3. Add the server to your client. With Claude Code:
  4. +
  5. claude.ai: Settings, Connectors, Add custom connector, paste https://mcp.openshorts.app/mcp, Connect.
  6. +
  7. ChatGPT: Settings, Connectors, Create, paste the same URL, choose OAuth.
  8. +
  9. Approve the access on openshorts.app (sign in if you are not). The 7 tools appear in every chat, and the connection is listed under Account, API keys, where revoking it disconnects the app.
+

How do I connect Claude Code, Cursor or n8n?

+

CLI and workflow clients take an API key instead: create one in your account +page (shown once, starts with osk_) and pass it as a Bearer +token. With Claude Code:

claude mcp add --transport http openshorts https://mcp.openshorts.app/mcp \\
   --header "Authorization: Bearer osk_..."

Any client that speaks Streamable HTTP works the same way: the endpoint is -https://mcp.openshorts.app/mcp and the key travels as a Bearer -token. The server describes itself over the protocol, tool schemas included, so -there is nothing else to configure.

+https://mcp.openshorts.app/mcp, the server describes itself over +the protocol, tool schemas included, and the account page has copy-ready +snippets for Claude Desktop, Cursor, n8n and curl.

What tools does the MCP server expose?

diff --git a/dashboard/src/App.jsx b/dashboard/src/App.jsx index 40cace6..b8b3d3f 100644 --- a/dashboard/src/App.jsx +++ b/dashboard/src/App.jsx @@ -2,6 +2,7 @@ import React, { useState, useEffect, useRef } from 'react'; import { Upload, Sparkles, Youtube, Instagram, Share2, ChevronDown, Check, Activity, LayoutDashboard, Settings, Plus, History, X, Terminal, Shield, LayoutGrid, Image, Globe, RotateCcw, Calendar, AlertTriangle, KeyRound, Bot, Users, Smartphone, ExternalLink, Copy, CheckCircle2, Mail, Loader2, Download, Menu } from 'lucide-react'; import KeyInput from './components/KeyInput'; import MediaInput from './components/MediaInput'; +import McpConnectCard from './components/McpConnectCard'; import ResultCard from './components/ResultCard'; import ProcessingAnimation from './components/ProcessingAnimation'; // import Gallery from './components/Gallery'; @@ -1221,6 +1222,9 @@ function App() { Privacy: keys only live in your browser (sent to backend just to process) + {/* Self-hosted installs have no account page, so the agent + how-to lives here; cloud users get it (with OAuth) in Account. */} + {!billingEnabled &&
} {isManaged ? (
@@ -1615,6 +1619,18 @@ function App() {

Drop your long-form video below to instantly generate viral clips with AI.

+ {/* The same pipeline is an MCP server: point people at the + one place that explains how to drive it from an agent. */} +

+ Or let an agent do it:{' '} + { if (!billingEnabled) { e.preventDefault(); setActiveTab('settings'); } }} + className="text-ink2 underline underline-offset-2 hover:text-brass transition-colors" + > + connect Claude, ChatGPT or n8n → + +

diff --git a/dashboard/src/components/AccountPage.jsx b/dashboard/src/components/AccountPage.jsx index af44189..ad5c4e9 100644 --- a/dashboard/src/components/AccountPage.jsx +++ b/dashboard/src/components/AccountPage.jsx @@ -4,6 +4,7 @@ import { useAuth } from '../contexts/AuthContext'; import { apiJson } from '../lib/api'; import { track } from '../lib/analytics'; import ApiKeysCard from './ApiKeysCard'; +import McpConnectCard from './McpConnectCard'; import DeleteAccountCard from './DeleteAccountCard'; import SocialAnalyticsCard from './SocialAnalyticsCard'; @@ -203,6 +204,8 @@ export default function AccountPage() {
)} + + diff --git a/dashboard/src/components/ApiKeysCard.jsx b/dashboard/src/components/ApiKeysCard.jsx index c3749a0..84a866e 100644 --- a/dashboard/src/components/ApiKeysCard.jsx +++ b/dashboard/src/components/ApiKeysCard.jsx @@ -52,10 +52,9 @@ export default function ApiKeysCard() { API keys

- Automate OpenShorts from agents and scripts. Connect any MCP client to{' '} - https://mcp.openshorts.app/mcp with{' '} - Authorization: Bearer <key>, or call the REST API - directly. Keys use your plan's minutes. + Keys for CLI clients, scripts and the REST API (see “Connect an agent” above). + Apps connected through claude.ai or ChatGPT show up here too: revoking a key disconnects + that app. Keys use your plan's minutes.

{freshKey && ( diff --git a/dashboard/src/components/McpConnectCard.jsx b/dashboard/src/components/McpConnectCard.jsx new file mode 100644 index 0000000..24da2eb --- /dev/null +++ b/dashboard/src/components/McpConnectCard.jsx @@ -0,0 +1,140 @@ +import React, { useState, useCallback } from 'react'; +import { Plug, Copy, Check } from 'lucide-react'; +import { getApiUrl } from '../config'; + +// "Connect an agent": the one place that tells a person how to drive +// OpenShorts from Claude, ChatGPT, Cursor or n8n. Cloud accounts connect by +// URL (claude.ai and ChatGPT run the OAuth flow themselves; CLI clients take +// an API key); a self-hosted install has no auth, so every snippet is the +// local URL and nothing else. + +const CLOUD_MCP_URL = 'https://mcp.openshorts.app/mcp'; + +// The self-hosted dashboard proxies /api and /videos to the backend but not +// /mcp (neither the Vite dev proxy nor nginx.conf), so an MCP client must +// talk to the API container itself: VITE_API_URL when it is set, otherwise +// the backend's default port on the same host. +function localMcpUrl() { + const u = getApiUrl('/mcp'); + if (u.startsWith('http')) return u; + try { return `${window.location.protocol}//${window.location.hostname}:8000/mcp`; } catch { return 'http://localhost:8000/mcp'; } +} + +function buildClients({ cloud, url }) { + const key = cloud ? 'osk_YOUR_KEY' : null; + const header = key ? ` \\\n --header "Authorization: Bearer ${key}"` : ''; + const desktopArgs = key + ? `["-y", "mcp-remote", "${url}", "--header", "Authorization: Bearer ${key}"]` + : `["-y", "mcp-remote", "${url}"]`; + const cursorHeaders = key ? `,\n "headers": { "Authorization": "Bearer ${key}" }` : ''; + return [ + cloud && { + id: 'claude-ai', label: 'Claude (claude.ai)', kind: 'steps', + steps: [ + 'Open claude.ai → Settings → Connectors → Add custom connector.', + `Paste this URL and save: ${url}`, + 'Click Connect: you will land on OpenShorts to approve the access, then the 7 tools appear in every chat.', + ], + snippet: url, + }, + cloud && { + id: 'chatgpt', label: 'ChatGPT', kind: 'steps', + steps: [ + 'Open ChatGPT → Settings → Connectors → Create (developer mode).', + `Name it OpenShorts, paste this MCP server URL, choose OAuth: ${url}`, + 'Approve the access on OpenShorts when asked. Done: ask ChatGPT to clip a video.', + ], + snippet: url, + }, + { + id: 'claude-code', label: 'Claude Code', kind: 'code', lang: 'bash', + snippet: `claude mcp add --transport http openshorts ${url}${header}`, + note: cloud ? 'Create a key below and paste it in place of osk_YOUR_KEY.' : 'No key needed on a self-hosted install.', + }, + { + id: 'claude-desktop', label: 'Claude Desktop', kind: 'code', lang: 'json', + snippet: `{\n "mcpServers": {\n "openshorts": {\n "command": "npx",\n "args": ${desktopArgs}\n }\n }\n}`, + note: 'Settings → Developer → Edit config (claude_desktop_config.json), then restart Claude.', + }, + { + id: 'cursor', label: 'Cursor', kind: 'code', lang: 'json', + snippet: `{\n "mcpServers": {\n "openshorts": {\n "url": "${url}"${cursorHeaders}\n }\n }\n}`, + note: 'Settings → MCP → Add new global MCP server (.cursor/mcp.json).', + }, + { + id: 'n8n', label: 'n8n', kind: 'steps', + steps: [ + 'Add an "MCP Client Tool" node to your AI Agent.', + `Endpoint: ${url} · Transport: HTTP Streamable.`, + cloud ? 'Authentication: Bearer, with a key from below.' : 'Authentication: none.', + ], + snippet: url, + }, + { + id: 'curl', label: 'curl', kind: 'code', lang: 'bash', + snippet: `curl -X POST ${url} \\\n -H "Content-Type: application/json"${key ? ` \\\n -H "Authorization: Bearer ${key}"` : ''} \\\n -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'`, + note: 'Plain JSON-RPC over HTTP: the same endpoint every client above talks to.', + }, + ].filter(Boolean); +} + +export default function McpConnectCard({ cloud = true, compact = false }) { + const url = cloud ? CLOUD_MCP_URL : localMcpUrl(); + const clients = buildClients({ cloud, url }); + const [active, setActive] = useState(clients[0].id); + const [copied, setCopied] = useState(false); + const current = clients.find((c) => c.id === active) || clients[0]; + + const copy = useCallback(() => { + navigator.clipboard?.writeText(current.snippet).then(() => { + setCopied(true); + setTimeout(() => setCopied(false), 1600); + }).catch(() => {}); + }, [current]); + + return ( +
+

+ Connect an agent +

+

+ Let Claude, ChatGPT, Cursor or n8n clip and publish for you through the built-in MCP server: + 7 tools (process a video, check a job, list clips, add subtitles, recut, publish, quota). + {cloud + ? ' claude.ai and ChatGPT connect with one URL and a sign-in; CLI clients use an API key.' + : ' This install runs without accounts, so no key is needed.'} +

+ +
+ {clients.map((c) => ( + + ))} +
+ + {current.kind === 'steps' && ( +
    + {current.steps.map((s) =>
  1. {s}
  2. )} +
+ )} + +
+
+          {current.snippet}
+        
+ +
+ {current.note &&

{current.note}

} +
+ ); +} diff --git a/dashboard/src/components/OAuthConsent.jsx b/dashboard/src/components/OAuthConsent.jsx new file mode 100644 index 0000000..9e73c0b --- /dev/null +++ b/dashboard/src/components/OAuthConsent.jsx @@ -0,0 +1,111 @@ +import React, { useEffect, useMemo, useState } from 'react'; +import { Plug, Loader2, ShieldCheck } from 'lucide-react'; +import { useAuth } from '../contexts/AuthContext'; +import { apiJson } from '../lib/api'; +import { getApiUrl } from '../config'; +import LoginModal from './LoginModal'; + +// The OAuth consent screen for MCP clients (claude.ai, ChatGPT, ...). The API +// bounced the client's /oauth/authorize request here because only the +// dashboard holds the session. Approving mints a code server-side and sends +// the browser back to the client; the access token it then receives is an +// ordinary API key, listed (and revocable) in the account page. + +function readParams() { + const hash = window.location.hash || ''; + const q = hash.includes('?') ? hash.slice(hash.indexOf('?') + 1) : ''; + return Object.fromEntries(new URLSearchParams(q).entries()); +} + +export default function OAuthConsent() { + const { isSignedIn, loading, me } = useAuth(); + const params = useMemo(readParams, []); + const [client, setClient] = useState(null); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + const [showLogin, setShowLogin] = useState(false); + + useEffect(() => { + if (!params.client_id) { setError('This link is missing the client id.'); return; } + fetch(getApiUrl(`/api/oauth/client/${encodeURIComponent(params.client_id)}`)) + .then((r) => (r.ok ? r.json() : Promise.reject(new Error('Unknown client')))) + .then(setClient) + .catch(() => setError('This connection request comes from an unknown app. Start again from the app you are connecting.')); + }, [params.client_id]); + + useEffect(() => { + if (!loading && !isSignedIn) setShowLogin(true); + }, [loading, isSignedIn]); + + const decide = async (allow) => { + setBusy(true); + try { + if (!allow) { + const u = new URL(params.redirect_uri); + u.searchParams.set('error', 'access_denied'); + if (params.state) u.searchParams.set('state', params.state); + window.location.replace(u.toString()); + return; + } + const d = await apiJson('/api/oauth/authorize', { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + client_id: params.client_id, + redirect_uri: params.redirect_uri, + state: params.state || null, + code_challenge: params.code_challenge, + code_challenge_method: params.code_challenge_method || 'S256', + scope: params.scope || null, + response_type: params.response_type || 'code', + }), + }); + window.location.replace(d.redirect); + } catch (e) { + setError(e?.detail || 'Could not complete the connection. Try again from the app.'); + setBusy(false); + } + }; + + const name = client?.client_name || 'an app'; + + return ( +
+
+
+ +
+

Connect {name} to OpenShorts

+ {error ? ( +

{error}

+ ) : ( + <> +

+ {name} wants to clip and publish videos with your account + {me?.email ? <> ({me.email}) : null}. + It will use your plan's minutes and you can disconnect it any time from + Account → API keys. +

+
    +
  • Process videos and read the resulting clips
  • +
  • Add subtitles, recut and publish clips you own
  • +
  • Nothing else: no billing, no account settings, no key management
  • +
+ {loading || !client ? ( +
+ ) : isSignedIn ? ( +
+ + +
+ ) : ( + + )} + + )} +
+ {showLogin && !isSignedIn && setShowLogin(false)} />} +
+ ); +} diff --git a/dashboard/src/main.jsx b/dashboard/src/main.jsx index 825a23c..ffcb3b9 100644 --- a/dashboard/src/main.jsx +++ b/dashboard/src/main.jsx @@ -9,6 +9,7 @@ import { capture as captureAttribution } from './lib/attribution' import PricingPage from './components/PricingPage' import AccountPage from './components/AccountPage' import LoginModal from './components/LoginModal' +import OAuthConsent from './components/OAuthConsent' function PageShell({ title, children }) { return ( @@ -70,6 +71,7 @@ function Root() { const resolveView = () => { const hash = window.location.hash || ''; if (hash.startsWith('#/auth/')) return 'auth'; // AuthContext consumes then redirects + if (hash.startsWith('#/oauth/authorize')) return 'oauth'; if (hash.startsWith('#/account')) return 'account'; if (hash.startsWith('#/deleted')) return 'deleted'; if (hash.startsWith('#/pricing')) return 'pricing'; @@ -97,6 +99,7 @@ function Root() { if (view === 'legal') return ; if (view === 'pricing') return ; if (view === 'account') return ; + if (view === 'oauth') return ; if (view === 'deleted') return ; if (view === 'auth') { return
Signing you in…
; diff --git a/mcp_server.py b/mcp_server.py index e2dfce3..4b3e017 100644 --- a/mcp_server.py +++ b/mcp_server.py @@ -527,11 +527,17 @@ async def _authorized(request: Request) -> bool: @router.post("/mcp") async def mcp_endpoint(request: Request): if not await _authorized(request): + # OAuth-capable clients (claude.ai, ChatGPT) read resource_metadata off + # this header and run the login flow themselves; everyone else gets the + # API-key hint in the body. + from cloud import mcp_oauth + u = request.base_url return JSONResponse( - {"error": "Authentication required. Pass an OpenShorts API key: " - "Authorization: Bearer osk_... (create one in the dashboard)."}, + {"error": "Authentication required. Connect with OAuth (claude.ai, ChatGPT) " + "or pass an OpenShorts API key: Authorization: Bearer osk_... " + "(create one in the dashboard)."}, status_code=401, - headers={"WWW-Authenticate": "Bearer"}, + headers={"WWW-Authenticate": mcp_oauth.www_authenticate(f"{u.scheme}://{u.netloc}")}, ) try: msg = json.loads(await request.body()) diff --git a/tests/test_mcp_endpoint.py b/tests/test_mcp_endpoint.py index 46b718a..82dc5a9 100644 --- a/tests/test_mcp_endpoint.py +++ b/tests/test_mcp_endpoint.py @@ -106,7 +106,9 @@ class TestCloudModeAuth: monkeypatch.setenv("BILLING_ENABLED", "1") resp = _post({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}}) assert resp.status_code == 401 - assert resp.headers.get("www-authenticate") == "Bearer" + # OAuth-capable clients discover the login flow from this header. + assert resp.headers.get("www-authenticate").startswith("Bearer resource_metadata=") + assert "/.well-known/oauth-protected-resource" in resp.headers.get("www-authenticate") assert "osk_" in resp.json()["error"] # the fix is named in the message def test_resolvable_user_passes(self, monkeypatch): diff --git a/tests/test_mcp_oauth.py b/tests/test_mcp_oauth.py new file mode 100644 index 0000000..560869e --- /dev/null +++ b/tests/test_mcp_oauth.py @@ -0,0 +1,84 @@ +"""OAuth 2.1 for the MCP endpoint: discovery documents, dynamic registration +input rules, PKCE and redirect building. The database-backed pieces +(register/authorize/token) are exercised against prod after deploy; what is +pinned here is every rule a client can trip over without a database.""" +import base64 +import hashlib +import secrets + +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from cloud import mcp_oauth + + +class TestHelpers: + def test_redirect_uri_rules(self): + ok = ["https://claude.ai/api/mcp/auth_callback", "https://chatgpt.com/connector_platform_oauth_redirect", + "http://localhost:3334/callback", "http://127.0.0.1:8080/cb"] + bad = ["http://evil.com/cb", "https://x.com/cb#frag", "ftp://x/cb", "not a url", ""] + assert all(mcp_oauth.valid_redirect_uri(u) for u in ok) + assert not any(mcp_oauth.valid_redirect_uri(u) for u in bad) + + def test_pkce_s256(self): + verifier = secrets.token_urlsafe(48) + challenge = base64.urlsafe_b64encode( + hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode() + assert mcp_oauth.pkce_matches(verifier, challenge) + assert not mcp_oauth.pkce_matches(verifier + "x", challenge) + assert not mcp_oauth.pkce_matches("short", challenge) # < 43 chars + assert not mcp_oauth.pkce_matches("", challenge) + + def test_add_query_keeps_existing_params_and_drops_none(self): + out = mcp_oauth.add_query("https://c.ai/cb?a=1", code="xyz", state=None) + assert out == "https://c.ai/cb?a=1&code=xyz" + + def test_consent_url_targets_the_hash_router(self): + url = mcp_oauth.consent_url("https://www.openshorts.app/", {"client_id": "abc", "state": "s"}) + assert url.startswith("https://www.openshorts.app/#/oauth/authorize?") + assert "client_id=abc" in url and "state=s" in url + + def test_metadata_points_at_the_same_host(self): + m = mcp_oauth.server_metadata("https://mcp.openshorts.app") + assert m["issuer"] == "https://mcp.openshorts.app" + assert m["token_endpoint"] == "https://mcp.openshorts.app/oauth/token" + assert m["code_challenge_methods_supported"] == ["S256"] + assert m["token_endpoint_auth_methods_supported"] == ["none"] + r = mcp_oauth.resource_metadata("https://mcp.openshorts.app") + assert r["resource"] == "https://mcp.openshorts.app/mcp" + assert r["authorization_servers"] == ["https://mcp.openshorts.app"] + + +class TestDiscoveryEndpoints: + def _client(self): + # The router is mounted by cloud.setup_sync in cloud mode only; test it + # on a bare app so the checks don't depend on BILLING_ENABLED. + app = FastAPI() + app.include_router(mcp_oauth.router) + return TestClient(app) + + def test_well_known_documents_are_served(self): + c = self._client() + for path in ("/.well-known/oauth-protected-resource", + "/.well-known/oauth-protected-resource/mcp", + "/.well-known/oauth-authorization-server", + "/.well-known/oauth-authorization-server/mcp"): + r = c.get(path) + assert r.status_code == 200, path + assert r.headers.get("access-control-allow-origin") == "*" + body = r.json() + assert ("resource" in body) or ("issuer" in body) + + def test_register_rejects_bad_redirects_and_secrets(self): + c = self._client() + r = c.post("/oauth/register", json={"client_name": "x", "redirect_uris": ["http://evil.com/cb"]}) + assert r.status_code == 400 and r.json()["error"] == "invalid_redirect_uri" + r = c.post("/oauth/register", json={"redirect_uris": ["https://ok.com/cb"], + "token_endpoint_auth_method": "client_secret_basic"}) + assert r.status_code == 400 and r.json()["error"] == "invalid_client_metadata" + r = c.post("/oauth/register", json={"redirect_uris": []}) + assert r.status_code == 400 + + def test_token_rejects_other_grants(self): + r = self._client().post("/oauth/token", data={"grant_type": "client_credentials"}) + assert r.status_code == 400 and r.json()["error"] == "unsupported_grant_type"