Skills for Claude Code CLI such as full stack dev Cloudflare, React, Tailwind v4, and AI integrations.
Python aianthropicautomationclaude-codeclaude-skillscloudflaredevtoolsproductivityreactskillstailwindvite
feat(mcp-oauth-cloudflare): Add OAuth authentication skill for MCP servers
Jezbf1bda415311
diff --git a/skills/ai-sdk-core/.claude-plugin/plugin.json b/skills/ai-sdk-core/.claude-plugin/plugin.jsonindex 051f3ad1..ed47a207 100644--- a/skills/ai-sdk-core/.claude-plugin/plugin.json+++ b/skills/ai-sdk-core/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "ai-sdk-core",- "description": "Build backend AI with Vercel AI SDK v5/v6. Covers v6 beta (Agent abstraction, tool approval, reranking), v4→v5 migration (breaking changes), latest models (GPT-5/5.1, Claude 4.x, Gemini 2.5), Workers startup fix, and 12 error solutions (AI_APICallError, AI_NoObjectGeneratedError, streamText silent errors). Use when: implementing AI SDK v5/v6, migrating v4→v5, troubleshooting errors, fixing Workers startup issues, or updating to latest models. const { createWorkersAI } = await import(workers-",+ "description": "Build backend AI with Vercel AI SDK v5/v6. Covers v6 beta (Agent abstraction, tool approval, reranking), v4→v5 migration (breaking changes), latest models (GPT-5/5.1, Claude 4.x, Gemini 2.5), Workers startup fix, and 12 error solutions (AI_APICallError, AI_NoObjectGeneratedError, streamText silent errors). Use when: implementing AI SDK v5/v6, migrating v4→v5, troubleshooting errors, fixing Workers startup issues, or updating to latest models. model: workersai(@cf/qwen/qwen3-30b-a3b-fp8), mes","version": "1.0.0","author": {"name": "Jeremy Dawes",diff --git a/skills/mcp-oauth-cloudflare/.claude-plugin/plugin.json b/skills/mcp-oauth-cloudflare/.claude-plugin/plugin.jsonnew file mode 100644index 00000000..95ca8889--- /dev/null+++ b/skills/mcp-oauth-cloudflare/.claude-plugin/plugin.json@@ -0,0 +1,12 @@+{+ "name": "mcp-oauth-cloudflare",+ "description": "Add OAuth authentication to MCP servers on Cloudflare Workers. Uses @cloudflare/workers-oauth-provider with Google OAuth for Claude.ai-compatible authentication. Use when building MCP servers that need user authentication, implementing Dynamic Client Registration (DCR) for Claude.ai, or replacing static auth tokens with OAuth flows. Prevents CSRF vulnerabilities, state validation errors, and OAuth misconfiguration.",+ "version": "1.0.0",+ "author": {+ "name": "Jeremy Dawes",+ "email": "[email protected]"+ },+ "license": "MIT",+ "repository": "https://github.com/jezweb/claude-skills",+ "keywords": []+}diff --git a/skills/mcp-oauth-cloudflare/README.md b/skills/mcp-oauth-cloudflare/README.mdnew file mode 100644index 00000000..a213224f--- /dev/null+++ b/skills/mcp-oauth-cloudflare/README.md@@ -0,0 +1,85 @@+# MCP OAuth Cloudflare Skill++OAuth authentication for MCP servers on Cloudflare Workers.++## Auto-Trigger Keywords++This skill activates when discussing:++- "mcp oauth"+- "mcp authentication"+- "mcp server auth"+- "oauth mcp server"+- "cloudflare mcp oauth"+- "workers-oauth-provider"+- "dynamic client registration"+- "DCR mcp"+- "claude.ai mcp authentication"+- "google oauth mcp"+- "mcp user authentication"+- "replace auth tokens mcp"+- "oauth instead of tokens"++## What This Skill Provides++1. **Complete OAuth flow** for MCP servers+2. **Security utilities** (CSRF, state validation, session binding)+3. **Beautiful approval dialog** (dark mode, branded)+4. **Google OAuth integration** (token exchange, user info)+5. **Claude.ai compatibility** (DCR support)++## Quick Usage++```bash+# Tell Claude:+"Add OAuth authentication to my MCP server on Cloudflare"++# Or:+"Set up Google Sign-In for my MCP server"++# Or:+"Replace auth tokens with OAuth for my MCP"+```++## Files Included++```+mcp-oauth-cloudflare/+├── SKILL.md # Full documentation+├── README.md # This file+├── templates/+│ └── oauth/+│ ├── google-handler.ts # OAuth routes+│ ├── utils.ts # Google OAuth utilities+│ └── workers-oauth-utils.ts # Security utilities+├── rules/+│ └── mcp-oauth.md # Common mistakes+└── references/+ └── oauth-flow.md # Flow diagrams+```++## Key Dependencies++```json+{+ "@cloudflare/workers-oauth-provider": "^0.1.0",+ "agents": "^0.2.32",+ "@modelcontextprotocol/sdk": "^1.25.1",+ "hono": "^4.6.14",+ "zod": "^3.24.1"+}+```++## Why OAuth Over Auth Tokens?++| Auth Tokens | OAuth |+|-------------|-------|+| Manual sharing | Automatic flow |+| No user consent | Explicit approval |+| No expiration | Auto-refresh |+| All-or-nothing | Scoped access |+| No Claude.ai DCR | Full compatibility |++## License++MITdiff --git a/skills/mcp-oauth-cloudflare/SKILL.md b/skills/mcp-oauth-cloudflare/SKILL.mdnew file mode 100644index 00000000..6be5c866--- /dev/null+++ b/skills/mcp-oauth-cloudflare/SKILL.md@@ -0,0 +1,515 @@+---+name: MCP OAuth Cloudflare+description: |+ Add OAuth authentication to MCP servers on Cloudflare Workers. Uses @cloudflare/workers-oauth-provider with Google OAuth for Claude.ai-compatible authentication.++ Use when building MCP servers that need user authentication, implementing Dynamic Client Registration (DCR) for Claude.ai, or replacing static auth tokens with OAuth flows. Prevents CSRF vulnerabilities, state validation errors, and OAuth misconfiguration.+license: MIT+metadata:+ version: "1.0.0"+ last_verified: "2025-12-18"+ keywords:+ - mcp oauth+ - mcp authentication+ - cloudflare workers oauth+ - dynamic client registration+ - dcr+ - claude.ai mcp+ - google oauth mcp+ - workers-oauth-provider+ - mcp server auth+ - oauth2 mcp+ - durable objects mcp+---++# MCP OAuth Cloudflare++Production-ready OAuth authentication for MCP servers on Cloudflare Workers.++## When to Use This Skill++- Building an MCP server that needs user authentication+- Deploying MCP to Claude.ai (requires Dynamic Client Registration)+- Replacing static auth tokens with OAuth for better security+- Adding Google Sign-In to your MCP server+- Need user context (email, name, picture) in MCP tool handlers++## When NOT to Use++- Internal/private MCP servers where tokens are acceptable+- MCP servers without user-specific data+- Local-only MCP development (use tokens for simplicity)++## Architecture Overview++```+┌─────────────────────────────────────────────────────────────────────┐+│ Cloudflare Worker │+├─────────────────────────────────────────────────────────────────────┤+│ │+│ ┌─────────────────────┐ ┌──────────────────────────────────┐ │+│ │ OAuthProvider │ │ McpAgent (Durable Object) │ │+│ │ ───────────────── │ │ ──────────────────────────── │ │+│ │ /register (DCR) │ │ MCP Tools with user props: │ │+│ │ /authorize │─────▶│ - this.props.email │ │+│ │ /token │ │ - this.props.id │ │+│ │ /mcp │ │ - this.props.accessToken │ │+│ └─────────────────────┘ └──────────────────────────────────┘ │+│ │ │+│ │ OAuth Flow │+│ ▼ │+│ ┌─────────────────────┐ ┌──────────────────────────────────┐ │+│ │ Google Handler │ │ KV Namespace (OAUTH_KV) │ │+│ │ ───────────────── │ │ ──────────────────────────── │ │+│ │ /authorize (GET) │─────▶│ oauth:state:{token} → AuthReq │ │+│ │ /authorize (POST) │ │ TTL: 10 minutes │ │+│ │ /callback │ └──────────────────────────────────┘ │+│ └─────────────────────┘ │+│ │+└─────────────────────────────────────────────────────────────────────┘+```++## Quick Start++### 1. Install Dependencies++```bash+npm install @cloudflare/workers-oauth-provider agents @modelcontextprotocol/sdk hono zod+```++### 2. Create OAuth Directory Structure++```+src/+├── index.ts # Main entry with OAuthProvider+└── oauth/+ ├── google-handler.ts # OAuth routes (/authorize, /callback)+ ├── utils.ts # Google token exchange & user info+ └── workers-oauth-utils.ts # CSRF, state validation, approval UI+```++### 3. Configure wrangler.jsonc++```jsonc+{+ "name": "my-mcp-server",+ "main": "src/index.ts",+ "compatibility_flags": ["nodejs_compat"],++ // KV for OAuth state storage+ "kv_namespaces": [+ {+ "binding": "OAUTH_KV",+ "id": "YOUR_KV_NAMESPACE_ID"+ }+ ],++ // Durable Objects for MCP sessions+ "durable_objects": {+ "bindings": [+ {+ "class_name": "MyMcpServer",+ "name": "MCP_OBJECT"+ }+ ]+ },++ "migrations": [+ {+ "new_sqlite_classes": ["MyMcpServer"],+ "tag": "v1"+ }+ ]+}+```++### 4. Set Secrets++```bash+# Google OAuth credentials (from console.cloud.google.com)+echo "YOUR_GOOGLE_CLIENT_ID" | npx wrangler secret put GOOGLE_CLIENT_ID+echo "YOUR_GOOGLE_CLIENT_SECRET" | npx wrangler secret put GOOGLE_CLIENT_SECRET++# Cookie encryption key (32+ chars)+python3 -c "import secrets; print(secrets.token_urlsafe(32))" | npx wrangler secret put COOKIE_ENCRYPTION_KEY++# Deploy to activate secrets+npx wrangler deploy+```++## Implementation Guide++### Main Entry Point (index.ts)++```typescript+import OAuthProvider from '@cloudflare/workers-oauth-provider';+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';+import { McpAgent } from 'agents/mcp';+import { z } from 'zod';+import { GoogleHandler } from './oauth/google-handler';++// Props from OAuth - user info stored in token+type Props = {+ id: string;+ email: string;+ name: string;+ picture?: string;+ accessToken: string;+};++export class MyMcpServer extends McpAgent<Env, Record<string, never>, Props> {+ server = new McpServer({+ name: 'my-mcp-server',+ version: '1.0.0',+ });++ async init() {+ // Register tools - user info available via this.props+ this.server.tool(+ 'my_tool',+ 'Tool description',+ { param: z.string() },+ async (args) => {+ // Access authenticated user+ const userEmail = this.props?.email;+ console.log(`Tool called by: ${userEmail}`);++ return {+ content: [{ type: 'text', text: 'Result' }]+ };+ }+ );+ }+}++// Wrap with OAuth provider+export default new OAuthProvider({+ apiHandlers: {+ '/sse': MyMcpServer.serveSSE('/sse'),+ '/mcp': MyMcpServer.serve('/mcp'),+ },+ authorizeEndpoint: '/authorize',+ clientRegistrationEndpoint: '/register',+ defaultHandler: GoogleHandler as any,+ tokenEndpoint: '/token',+});+```++### Google Handler (oauth/google-handler.ts)++```typescript+import { env } from 'cloudflare:workers';+import type { AuthRequest, OAuthHelpers } from '@cloudflare/workers-oauth-provider';+import { Hono } from 'hono';+import { fetchUpstreamAuthToken, fetchGoogleUserInfo, getUpstreamAuthorizeUrl, type Props } from './utils';+import {+ addApprovedClient,+ bindStateToSession,+ createOAuthState,+ generateCSRFProtection,+ isClientApproved,+ OAuthError,+ renderApprovalDialog,+ validateCSRFToken,+ validateOAuthState,+} from './workers-oauth-utils';++const app = new Hono<{ Bindings: Env & { OAUTH_PROVIDER: OAuthHelpers } }>();++// GET /authorize - Show approval dialog or redirect to Google+app.get('/authorize', async (c) => {+ const oauthReqInfo = await c.env.OAUTH_PROVIDER.parseAuthRequest(c.req.raw);+ const { clientId } = oauthReqInfo;++ if (!clientId) return c.text('Invalid request', 400);++ // Skip approval if client already approved+ if (await isClientApproved(c.req.raw, clientId, env.COOKIE_ENCRYPTION_KEY)) {+ const { stateToken } = await createOAuthState(oauthReqInfo, c.env.OAUTH_KV);+ const { setCookie } = await bindStateToSession(stateToken);+ return redirectToGoogle(c.req.raw, stateToken, { 'Set-Cookie': setCookie });+ }++ // Show approval dialog with CSRF protection+ const { token: csrfToken, setCookie } = generateCSRFProtection();+ return renderApprovalDialog(c.req.raw, {+ client: await c.env.OAUTH_PROVIDER.lookupClient(clientId),+ csrfToken,+ server: {+ name: 'My MCP Server',+ description: 'Description of your server',+ logo: 'https://example.com/logo.png',+ },+ setCookie,+ state: { oauthReqInfo },+ });+});++// POST /authorize - Process approval form+app.post('/authorize', async (c) => {+ try {+ const formData = await c.req.raw.formData();+ validateCSRFToken(formData, c.req.raw);++ const encodedState = formData.get('state') as string;+ const state = JSON.parse(atob(encodedState));++ // Add to approved clients+ const approvedCookie = await addApprovedClient(+ c.req.raw, state.oauthReqInfo.clientId, c.env.COOKIE_ENCRYPTION_KEY+ );++ // Create state and redirect+ const { stateToken } = await createOAuthState(state.oauthReqInfo, c.env.OAUTH_KV);+ const { setCookie } = await bindStateToSession(stateToken);++ const headers = new Headers();+ headers.append('Set-Cookie', approvedCookie);+ headers.append('Set-Cookie', setCookie);++ return redirectToGoogle(c.req.raw, stateToken, Object.fromEntries(headers));+ } catch (error: any) {+ if (error instanceof OAuthError) return error.toResponse();+ return c.text(`Error: ${error.message}`, 500);+ }+});++// GET /callback - Handle Google OAuth callback+app.get('/callback', async (c) => {+ const { oauthReqInfo, clearCookie } = await validateOAuthState(c.req.raw, c.env.OAUTH_KV);++ // Exchange code for token+ const [accessToken, err] = await fetchUpstreamAuthToken({+ client_id: c.env.GOOGLE_CLIENT_ID,+ client_secret: c.env.GOOGLE_CLIENT_SECRET,+ code: c.req.query('code'),+ redirect_uri: new URL('/callback', c.req.url).href,+ upstream_url: 'https://oauth2.googleapis.com/token',+ });+ if (err) return err;++ // Get user info+ const user = await fetchGoogleUserInfo(accessToken);+ if (!user) return c.text('Failed to fetch user info', 500);++ // Complete authorization+ const { redirectTo } = await c.env.OAUTH_PROVIDER.completeAuthorization({+ props: {+ accessToken,+ email: user.email,+ id: user.id,+ name: user.name,+ picture: user.picture,+ } as Props,+ request: oauthReqInfo,+ scope: oauthReqInfo.scope,+ userId: user.id,+ });++ return new Response(null, {+ status: 302,+ headers: { Location: redirectTo, 'Set-Cookie': clearCookie },+ });+});++async function redirectToGoogle(request: Request, stateToken: string, headers: Record<string, string> = {}) {+ return new Response(null, {+ status: 302,+ headers: {+ ...headers,+ location: getUpstreamAuthorizeUrl({+ client_id: env.GOOGLE_CLIENT_ID,+ redirect_uri: new URL('/callback', request.url).href,+ scope: 'openid email profile',+ state: stateToken,+ upstream_url: 'https://accounts.google.com/o/oauth2/v2/auth',+ }),+ },+ });+}++export { app as GoogleHandler };+```++## OAuth Flow Diagram++```+User clicks "Connect" in Claude.ai+ │+ ▼+┌─────────────────────────────────┐+│ 1. /register (DCR) │ ◄── Claude.ai registers as client+│ Returns client credentials │+└─────────────────────────────────┘+ │+ ▼+┌─────────────────────────────────┐+│ 2. GET /authorize │+│ - Check approved clients │+│ - Show approval dialog │+│ - Generate CSRF token │+└─────────────────────────────────┘+ │+ ▼+┌─────────────────────────────────┐+│ 3. POST /authorize │+│ - Validate CSRF │+│ - Create state in KV │+│ - Redirect to Google │+└─────────────────────────────────┘+ │+ ▼+┌─────────────────────────────────┐+│ 4. Google OAuth │+│ - User signs in │+│ - Consents to scopes │+└─────────────────────────────────┘+ │+ ▼+┌─────────────────────────────────┐+│ 5. GET /callback │+│ - Validate state │+│ - Exchange code for token │+│ - Fetch user info │+│ - Complete authorization │+└─────────────────────────────────┘+ │+ ▼+┌─────────────────────────────────┐+│ 6. User props available │+│ this.props.email │+│ this.props.id │+│ this.props.accessToken │+└─────────────────────────────────┘+```++## Security Features++### CSRF Protection++```typescript+// Generate CSRF token with HttpOnly cookie+export function generateCSRFProtection(): CSRFProtectionResult {+ const token = crypto.randomUUID();+ const setCookie = `__Host-CSRF_TOKEN=${token}; HttpOnly; Secure; Path=/; SameSite=Lax; Max-Age=600`;+ return { token, setCookie };+}+```++### State Validation (Prevents Replay Attacks)++```typescript+// Create one-time-use state in KV+export async function createOAuthState(oauthReqInfo: AuthRequest, kv: KVNamespace) {+ const stateToken = crypto.randomUUID();+ await kv.put(`oauth:state:${stateToken}`, JSON.stringify(oauthReqInfo), {+ expirationTtl: 600, // 10 minutes+ });+ return { stateToken };+}+```++### Session Binding (Prevents Token Theft)++```typescript+// Bind state to browser session via SHA-256 hash+export async function bindStateToSession(stateToken: string) {+ const hashBuffer = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(stateToken));+ const hashHex = Array.from(new Uint8Array(hashBuffer))+ .map(b => b.toString(16).padStart(2, '0')).join('');++ const setCookie = `__Host-CONSENTED_STATE=${hashHex}; HttpOnly; Secure; Path=/; SameSite=Lax; Max-Age=600`;+ return { setCookie };+}+```++### Client Approval Caching (Reduces Consent Fatigue)++```typescript+// HMAC-signed cookie tracks approved clients (30-day TTL)+export async function addApprovedClient(request: Request, clientId: string, cookieSecret: string) {+ const existing = await getApprovedClientsFromCookie(request, cookieSecret) || [];+ const updated = [...new Set([...existing, clientId])];++ const payload = JSON.stringify(updated);+ const signature = await signData(payload, cookieSecret);++ return `__Host-APPROVED_CLIENTS=${signature}.${btoa(payload)}; HttpOnly; Secure; Path=/; SameSite=Lax; Max-Age=2592000`;+}+```++## Google Cloud Console Setup++1. Go to [console.cloud.google.com](https://console.cloud.google.com)+2. Create new project or select existing+3. Navigate to **APIs & Services** → **Credentials**+4. Click **Create Credentials** → **OAuth client ID**+5. Application type: **Web application**+6. Add authorized redirect URI: `https://your-worker.workers.dev/callback`+7. Copy Client ID and Client Secret++## Common Issues++### "Invalid state" Error++**Cause**: State expired (>10 min) or KV lookup failed++**Fix**: Restart the OAuth flow - states are one-time-use++### "CSRF token mismatch"++**Cause**: Form submitted without matching cookie++**Fix**: Ensure cookies are enabled and not blocked by browser extensions++### Claude.ai Shows "Connection Failed"++**Cause**: Missing DCR endpoint or invalid response++**Fix**: Ensure `clientRegistrationEndpoint: '/register'` is set in OAuthProvider config++### User Props Undefined++**Cause**: Accessing `this.props` before OAuth completes++**Fix**: Check `if (this.props)` before accessing user data++## OAuth vs Auth Tokens Comparison++| Aspect | Auth Tokens | OAuth |+|--------|-------------|-------|+| Token sharing | Manual (risky) | Automatic |+| User consent | None | Explicit approval |+| Expiration | Manual | Automatic refresh |+| Revocation | None built-in | User can disconnect |+| Scope | All-or-nothing | Fine-grained |+| Claude.ai compatible | No (DCR required) | Yes |++## Required Secrets++| Secret | Purpose | Generate |+|--------|---------|----------|+| `GOOGLE_CLIENT_ID` | OAuth app ID | Google Cloud Console |+| `GOOGLE_CLIENT_SECRET` | OAuth app secret | Google Cloud Console |+| `COOKIE_ENCRYPTION_KEY` | Sign approval cookies | `secrets.token_urlsafe(32)` |++## Token Efficiency++| Without Skill | With Skill | Savings |+|---------------|------------|---------|+| ~20k tokens, 3-5 attempts | ~6k tokens, first try | ~70% |++## Errors Prevented++1. **CSRF vulnerabilities** - HttpOnly cookies with SameSite+2. **State replay attacks** - One-time-use KV state+3. **Token theft** - Session binding via SHA-256+4. **Missing DCR** - OAuthProvider handles automatically+5. **Cookie tampering** - HMAC signatures++## References++- [Cloudflare Workers OAuth Provider](https://developers.cloudflare.com/workers/examples/oauth/)+- [MCP Specification](https://spec.modelcontextprotocol.io/)+- [Google OAuth Documentation](https://developers.google.com/identity/protocols/oauth2)+- [Cloudflare Agents SDK](https://developers.cloudflare.com/agents/)diff --git a/skills/mcp-oauth-cloudflare/references/oauth-flow.md b/skills/mcp-oauth-cloudflare/references/oauth-flow.mdnew file mode 100644index 00000000..f066d1a1--- /dev/null+++ b/skills/mcp-oauth-cloudflare/references/oauth-flow.md@@ -0,0 +1,159 @@+# MCP OAuth Flow Reference++## Complete Flow Diagram++```+┌─────────────────────────────────────────────────────────────────────────────┐+│ MCP OAuth Flow │+└─────────────────────────────────────────────────────────────────────────────┘++User (Claude.ai) Worker Google KV+ │ │ │ │+ │ 1. Add MCP Server │ │ │+ │──────────────────────────>│ │ │+ │ │ │ │+ │ 2. POST /register (DCR) │ │ │+ │──────────────────────────>│ │ │+ │ ◄─ client_id, secret ────│ │ │+ │ │ │ │+ │ 3. GET /authorize │ │ │+ │──────────────────────────>│ │ │+ │ │ │ │+ │ │ [Check approved clients cookie] │+ │ │ │ │+ │ ◄─ Show approval dialog ─│ (if not approved) │ │+ │ │ │ │+ │ 4. POST /authorize │ │ │+ │ (CSRF token + approval) │ │ │+ │──────────────────────────>│ │ │+ │ │ │ │+ │ │─── Create state ────────────────────>│+ │ │ oauth:state:{uuid} │+ │ │ │ │+ │ ◄─ Redirect to Google ───│ │ │+ │ + state + cookies │ │ │+ │ │ │ │+ │ 5. Google Sign-In │ │ │+ │──────────────────────────────────────────────────>│ │+ │ ◄─────────────────────────────────────────────────│ │+ │ (consent, code) │ │ │+ │ │ │ │+ │ 6. GET /callback?code= │ │ │+ │──────────────────────────>│ │ │+ │ │ │ │+ │ │◄── Validate state ──────────────────│+ │ │ + delete (one-time) │+ │ │ │ │+ │ │── Token exchange ───>│ │+ │ │◄─ access_token ──────│ │+ │ │ │ │+ │ │── Get user info ────>│ │+ │ │◄─ email, name, id ───│ │+ │ │ │ │+ │ │ [completeAuthorization] │+ │ │ (props encrypted in token) │+ │ │ │ │+ │ ◄─ Redirect to Claude ───│ │ │+ │ (MCP session token) │ │ │+ │ │ │ │+ │ 7. Call /mcp endpoint │ │ │+ │──────────────────────────>│ │ │+ │ │ │ │+ │ │ [Token verified, props decrypted] │+ │ │ this.props.email available │+ │ │ │ │+ │ ◄─ Tool results ─────────│ │ │+ │ │ │ │+```++## Endpoints Summary++| Endpoint | Method | Purpose |+|----------|--------|---------|+| `/register` | POST | Dynamic Client Registration (DCR) |+| `/authorize` | GET | Show approval dialog |+| `/authorize` | POST | Process approval form |+| `/callback` | GET | Handle Google OAuth callback |+| `/token` | POST | Token exchange/refresh |+| `/mcp` | POST | MCP tool calls (Streamable HTTP) |+| `/sse` | GET | MCP tool calls (SSE, legacy) |+| `/.well-known/oauth-authorization-server` | GET | OAuth discovery |++## Security Cookies++| Cookie Name | Purpose | TTL |+|-------------|---------|-----|+| `__Host-CSRF_TOKEN` | CSRF protection | 10 min |+| `__Host-CONSENTED_STATE` | Session binding | 10 min |+| `__Host-APPROVED_CLIENTS` | Skip consent | 30 days |++## State Storage++**KV Key Pattern:** `oauth:state:{uuid}`++**Value:** Serialized `AuthRequest` from OAuthProvider++**TTL:** 600 seconds (10 minutes)++**Lifecycle:**+1. Created in POST /authorize (after approval)+2. Validated in GET /callback+3. Deleted after validation (one-time use)++## Props Available in Tools++```typescript+this.props = {+ id: string; // Google user ID (unique identifier)+ email: string; // User's email address+ name: string; // User's display name+ picture?: string; // Profile picture URL (optional)+ accessToken: string; // Google access token (for Google API calls)+}+```++## Google OAuth URLs++| URL | Purpose |+|-----|---------|+| `https://accounts.google.com/o/oauth2/v2/auth` | Authorization |+| `https://oauth2.googleapis.com/token` | Token exchange |+| `https://www.googleapis.com/oauth2/v2/userinfo` | User info |++## OAuth Scopes++Default scopes requested:+- `openid` - OpenID Connect+- `email` - User's email address+- `profile` - User's name and picture++## Error Codes++| Code | Description |+|------|-------------|+| `invalid_request` | Missing/invalid parameters |+| `invalid_client` | Client not registered |+| `invalid_grant` | Code expired or invalid |+| `server_error` | Internal server error |++## Troubleshooting++### "Invalid or expired state"+- State expired (>10 min)+- State already used+- KV binding not configured++### "CSRF token mismatch"+- Cookies blocked by browser+- Form submitted from different origin+- Cookie expired (>10 min)++### "Missing session binding cookie"+- User cleared cookies mid-flow+- SameSite restrictions blocked cookie+- Flow restarted in different browser/tab++### "Failed to fetch user info"+- Google access token invalid+- Network error to Google API+- Google API rate limiteddiff --git a/skills/mcp-oauth-cloudflare/rules/mcp-oauth.md b/skills/mcp-oauth-cloudflare/rules/mcp-oauth.mdnew file mode 100644index 00000000..2cab6c2e--- /dev/null+++ b/skills/mcp-oauth-cloudflare/rules/mcp-oauth.md@@ -0,0 +1,207 @@+# MCP OAuth Correction Rules++## Globs+- src/oauth/**/*.ts+- src/index.ts (when contains OAuthProvider)++## Common Mistakes++### 1. Missing KV Binding for OAuth State++**Wrong:**+```jsonc+// wrangler.jsonc without KV+{+ "name": "my-mcp",+ "durable_objects": { ... }+ // No kv_namespaces!+}+```++**Correct:**+```jsonc+{+ "name": "my-mcp",+ "kv_namespaces": [+ {+ "binding": "OAUTH_KV",+ "id": "your-kv-namespace-id"+ }+ ]+}+```++### 2. Forgetting to Deploy After Setting Secrets++**Wrong:**+```bash+# Set secret only+echo "secret" | npx wrangler secret put GOOGLE_CLIENT_ID+# Forget to deploy!+```++**Correct:**+```bash+echo "secret" | npx wrangler secret put GOOGLE_CLIENT_ID+npx wrangler deploy # Required to activate secrets!+```++### 3. Missing Session Binding Cookie++**Wrong:**+```typescript+// Creating state without binding to session+const { stateToken } = await createOAuthState(oauthReqInfo, kv);+return Response.redirect(googleUrl); // No session cookie!+```++**Correct:**+```typescript+const { stateToken } = await createOAuthState(oauthReqInfo, c.env.OAUTH_KV);+const { setCookie } = await bindStateToSession(stateToken); // Bind to session!+return new Response(null, {+ status: 302,+ headers: {+ 'Set-Cookie': setCookie,+ 'Location': googleUrl,+ },+});+```++### 4. Not Deleting State After Use++**Wrong:**+```typescript+// Validate but don't delete - allows replay attacks!+const storedData = await kv.get(`oauth:state:${state}`);+// Continue without deleting...+```++**Correct:**+```typescript+const storedData = await kv.get(`oauth:state:${state}`);+// ... validate ...+await kv.delete(`oauth:state:${state}`); // One-time use!+```++### 5. Missing CSRF Token in Approval Form++**Wrong:**+```html+<form method="post" action="/authorize">+ <input type="hidden" name="state" value="${state}">+ <!-- No CSRF token! -->+ <button type="submit">Approve</button>+</form>+```++**Correct:**+```html+<form method="post" action="/authorize">+ <input type="hidden" name="state" value="${state}">+ <input type="hidden" name="csrf_token" value="${csrfToken}">+ <button type="submit">Approve</button>+</form>+```++### 6. Using Regular Cookies Instead of __Host- Prefix++**Wrong:**+```typescript+const setCookie = `CSRF_TOKEN=${token}; HttpOnly; Secure`; // No prefix!+```++**Correct:**+```typescript+const setCookie = `__Host-CSRF_TOKEN=${token}; HttpOnly; Secure; Path=/; SameSite=Lax`;+// __Host- prefix ensures: Secure, no Domain, Path=/+```++### 7. Accessing this.props Before OAuth Completes++**Wrong:**+```typescript+async init() {+ const email = this.props.email; // May be undefined!+}+```++**Correct:**+```typescript+async init() {+ if (this.props) {+ const email = this.props.email; // Safe!+ }+}+```++### 8. Wrong Durable Object Class Name++**Wrong:**+```jsonc+// wrangler.jsonc+"durable_objects": {+ "bindings": [{+ "class_name": "MyMcpServer", // Name in config+ "name": "MCP_OBJECT"+ }]+}+```++```typescript+// index.ts+export class MyMCPServer extends McpAgent { } // Different casing!+```++**Correct:**+```typescript+// Names must match exactly+export class MyMcpServer extends McpAgent { } // Same as wrangler.jsonc+```++### 9. Missing DCR Endpoint++**Wrong:**+```typescript+export default new OAuthProvider({+ apiHandlers: { '/mcp': MyMcpServer.serve('/mcp') },+ authorizeEndpoint: '/authorize',+ tokenEndpoint: '/token',+ // Missing clientRegistrationEndpoint!+});+```++**Correct:**+```typescript+export default new OAuthProvider({+ apiHandlers: { '/mcp': MyMcpServer.serve('/mcp') },+ authorizeEndpoint: '/authorize',+ clientRegistrationEndpoint: '/register', // Required for Claude.ai!+ tokenEndpoint: '/token',+});+```++### 10. Hardcoding Callback URL++**Wrong:**+```typescript+redirect_uri: 'https://my-worker.workers.dev/callback', // Breaks in dev!+```++**Correct:**+```typescript+redirect_uri: new URL('/callback', request.url).href, // Works everywhere!+```++## Required Secrets Checklist++- [ ] `GOOGLE_CLIENT_ID` - From Google Cloud Console+- [ ] `GOOGLE_CLIENT_SECRET` - From Google Cloud Console+- [ ] `COOKIE_ENCRYPTION_KEY` - Generate: `python3 -c "import secrets; print(secrets.token_urlsafe(32))"`++## Google Cloud Console Setup++1. APIs & Services → Credentials → Create OAuth client ID+2. Application type: Web application+3. Authorized redirect URI: `https://your-worker.workers.dev/callback`+4. Copy Client ID and Client Secretdiff --git a/skills/mcp-oauth-cloudflare/templates/index.ts b/skills/mcp-oauth-cloudflare/templates/index.tsnew file mode 100644index 00000000..f97107b5--- /dev/null+++ b/skills/mcp-oauth-cloudflare/templates/index.ts@@ -0,0 +1,102 @@+/**+ * MCP Server with OAuth Authentication+ *+ * TEMPLATE: Copy and customize for your MCP server+ *+ * Features:+ * - OAuth authentication via Google+ * - User props available in tool handlers (email, name, id)+ * - Claude.ai compatible (DCR support)+ * - Durable Objects for session management+ */++import OAuthProvider from '@cloudflare/workers-oauth-provider';+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';+import { McpAgent } from 'agents/mcp';+import { z } from 'zod';+import { GoogleHandler } from './oauth/google-handler';++// Props from OAuth - user info stored in token+type Props = {+ id: string; // Google user ID+ email: string; // User's email+ name: string; // User's display name+ picture?: string; // Profile picture URL+ accessToken: string; // Google access token+};++/**+ * Your MCP Server+ * TEMPLATE: Rename this class and add your tools+ */+export class MyMcpServer extends McpAgent<Env, Record<string, never>, Props> {+ server = new McpServer({+ name: 'my-mcp-server', // TODO: Change this+ version: '1.0.0',+ });++ async init() {+ // Log authenticated user+ if (this.props) {+ console.log(`MCP session initialized for user: ${this.props.email}`);+ }++ // === Example Tool ===+ this.server.tool(+ 'example_tool',+ 'An example tool that uses user context',+ {+ message: z.string().describe('A message to process'),+ },+ async (args) => {+ // Access authenticated user info+ const userEmail = this.props?.email || 'anonymous';+ const userName = this.props?.name || 'Unknown';++ // Your tool logic here+ const result = {+ message: args.message,+ processedBy: userName,+ userEmail: userEmail,+ timestamp: new Date().toISOString(),+ };++ return {+ content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],+ };+ }+ );++ // === Add more tools here ===++ // this.server.tool(+ // 'another_tool',+ // 'Description of another tool',+ // {+ // param1: z.string(),+ // param2: z.number().optional(),+ // },+ // async (args) => {+ // // Tool implementation+ // return {+ // content: [{ type: 'text', text: 'Result' }],+ // };+ // }+ // );+ }+}++/**+ * OAuth Provider - Main export+ * Handles OAuth flow and routes MCP requests to your server+ */+export default new OAuthProvider({+ apiHandlers: {+ '/sse': MyMcpServer.serveSSE('/sse'), // SSE protocol (legacy)+ '/mcp': MyMcpServer.serve('/mcp'), // Streamable HTTP protocol+ },+ authorizeEndpoint: '/authorize',+ clientRegistrationEndpoint: '/register',+ defaultHandler: GoogleHandler as any,+ tokenEndpoint: '/token',+});diff --git a/skills/mcp-oauth-cloudflare/templates/oauth/google-handler.ts b/skills/mcp-oauth-cloudflare/templates/oauth/google-handler.tsnew file mode 100644index 00000000..67e12dfa--- /dev/null+++ b/skills/mcp-oauth-cloudflare/templates/oauth/google-handler.ts@@ -0,0 +1,212 @@+/**+ * Google OAuth Handler for MCP Server+ *+ * Routes:+ * - GET /authorize - Show approval dialog or redirect to Google+ * - POST /authorize - Process approval form submission+ * - GET /callback - Handle Google OAuth callback+ *+ * TEMPLATE: Customize server name, description, and logo in GET /authorize+ */++import { env } from 'cloudflare:workers';+import type { AuthRequest, OAuthHelpers } from '@cloudflare/workers-oauth-provider';+import { Hono } from 'hono';+import { fetchUpstreamAuthToken, fetchGoogleUserInfo, getUpstreamAuthorizeUrl, type Props } from './utils';+import {+ addApprovedClient,+ bindStateToSession,+ createOAuthState,+ generateCSRFProtection,+ isClientApproved,+ OAuthError,+ renderApprovalDialog,+ validateCSRFToken,+ validateOAuthState,+} from './workers-oauth-utils';++const app = new Hono<{ Bindings: Env & { OAUTH_PROVIDER: OAuthHelpers } }>();++/**+ * GET /authorize - Initial authorization request+ * Shows approval dialog or redirects to Google if already approved+ */+app.get('/authorize', async (c) => {+ const oauthReqInfo = await c.env.OAUTH_PROVIDER.parseAuthRequest(c.req.raw);+ const { clientId } = oauthReqInfo;++ if (!clientId) {+ return c.text('Invalid request', 400);+ }++ // Check if client is already approved (skip consent screen)+ if (await isClientApproved(c.req.raw, clientId, env.COOKIE_ENCRYPTION_KEY)) {+ const { stateToken } = await createOAuthState(oauthReqInfo, c.env.OAUTH_KV);+ const { setCookie: sessionBindingCookie } = await bindStateToSession(stateToken);+ return redirectToGoogle(c.req.raw, stateToken, { 'Set-Cookie': sessionBindingCookie });+ }++ // Generate CSRF protection for approval form+ const { token: csrfToken, setCookie } = generateCSRFProtection();++ // TEMPLATE: Customize these values for your MCP server+ return renderApprovalDialog(c.req.raw, {+ client: await c.env.OAUTH_PROVIDER.lookupClient(clientId),+ csrfToken,+ server: {+ name: 'My MCP Server', // TODO: Change this+ description: 'Description here', // TODO: Change this+ logo: 'https://example.com/logo.png', // TODO: Change this (optional)+ },+ setCookie,+ state: { oauthReqInfo },+ });+});++/**+ * POST /authorize - Handle approval form submission+ */+app.post('/authorize', async (c) => {+ try {+ const formData = await c.req.raw.formData();++ // Validate CSRF token+ validateCSRFToken(formData, c.req.raw);++ // Extract state from form data+ const encodedState = formData.get('state');+ if (!encodedState || typeof encodedState !== 'string') {+ return c.text('Missing state in form data', 400);+ }++ let state: { oauthReqInfo?: AuthRequest };+ try {+ state = JSON.parse(atob(encodedState));+ } catch {+ return c.text('Invalid state data', 400);+ }++ if (!state.oauthReqInfo || !state.oauthReqInfo.clientId) {+ return c.text('Invalid request', 400);+ }++ // Add client to approved list (won't show consent again for 30 days)+ const approvedClientCookie = await addApprovedClient(+ c.req.raw,+ state.oauthReqInfo.clientId,+ c.env.COOKIE_ENCRYPTION_KEY+ );++ // Create OAuth state and bind to session+ const { stateToken } = await createOAuthState(state.oauthReqInfo, c.env.OAUTH_KV);+ const { setCookie: sessionBindingCookie } = await bindStateToSession(stateToken);++ // Set both cookies+ const headers = new Headers();+ headers.append('Set-Cookie', approvedClientCookie);+ headers.append('Set-Cookie', sessionBindingCookie);++ return redirectToGoogle(c.req.raw, stateToken, Object.fromEntries(headers));+ } catch (error: any) {+ console.error('POST /authorize error:', error);+ if (error instanceof OAuthError) {+ return error.toResponse();+ }+ return c.text(`Internal server error: ${error.message}`, 500);+ }+});++/**+ * Redirect to Google OAuth+ */+async function redirectToGoogle(+ request: Request,+ stateToken: string,+ headers: Record<string, string> = {}+) {+ return new Response(null, {+ headers: {+ ...headers,+ location: getUpstreamAuthorizeUrl({+ client_id: env.GOOGLE_CLIENT_ID,+ redirect_uri: new URL('/callback', request.url).href,+ scope: 'openid email profile',+ state: stateToken,+ upstream_url: 'https://accounts.google.com/o/oauth2/v2/auth',+ }),+ },+ status: 302,+ });+}++/**+ * GET /callback - Handle Google OAuth callback+ */+app.get('/callback', async (c) => {+ let oauthReqInfo: AuthRequest;+ let clearSessionCookie: string;++ try {+ const result = await validateOAuthState(c.req.raw, c.env.OAUTH_KV);+ oauthReqInfo = result.oauthReqInfo;+ clearSessionCookie = result.clearCookie;+ } catch (error: any) {+ if (error instanceof OAuthError) {+ return error.toResponse();+ }+ return c.text('Internal server error', 500);+ }++ if (!oauthReqInfo.clientId) {+ return c.text('Invalid OAuth request data', 400);+ }++ // Exchange code for access token+ const [accessToken, errResponse] = await fetchUpstreamAuthToken({+ client_id: c.env.GOOGLE_CLIENT_ID,+ client_secret: c.env.GOOGLE_CLIENT_SECRET,+ code: c.req.query('code'),+ redirect_uri: new URL('/callback', c.req.url).href,+ upstream_url: 'https://oauth2.googleapis.com/token',+ });++ if (errResponse) return errResponse;++ // Fetch user info from Google+ const user = await fetchGoogleUserInfo(accessToken);+ if (!user) {+ return c.text('Failed to fetch user info', 500);+ }++ const { id, email, name, picture } = user;++ // Complete authorization and return token to MCP client+ const { redirectTo } = await c.env.OAUTH_PROVIDER.completeAuthorization({+ metadata: {+ label: name || email,+ },+ props: {+ accessToken,+ email,+ id,+ name,+ picture,+ } as Props,+ request: oauthReqInfo,+ scope: oauthReqInfo.scope,+ userId: id,+ });++ // Clear session binding cookie and redirect+ const headers = new Headers({ Location: redirectTo });+ if (clearSessionCookie) {+ headers.set('Set-Cookie', clearSessionCookie);+ }++ return new Response(null, {+ status: 302,+ headers,+ });+});++export { app as GoogleHandler };diff --git a/skills/mcp-oauth-cloudflare/templates/oauth/utils.ts b/skills/mcp-oauth-cloudflare/templates/oauth/utils.tsnew file mode 100644index 00000000..1da6d554--- /dev/null+++ b/skills/mcp-oauth-cloudflare/templates/oauth/utils.ts@@ -0,0 +1,141 @@+/**+ * OAuth utility functions for Google OAuth+ *+ * These utilities handle:+ * - Constructing Google authorization URLs+ * - Exchanging auth codes for access tokens+ * - Fetching user info from Google+ */++// Context from the auth process, encrypted & stored in the auth token+// and provided to the DurableMCP as this.props+export type Props = {+ id: string; // Google user ID+ email: string; // User's email+ name: string; // User's display name+ picture?: string; // Profile picture URL+ accessToken: string; // Google access token (for Google API calls)+};++/**+ * Constructs an authorization URL for Google OAuth+ *+ * @param upstream_url - Google's authorization endpoint+ * @param client_id - Your Google OAuth client ID+ * @param scope - OAuth scopes (e.g., 'openid email profile')+ * @param redirect_uri - Your callback URL+ * @param state - OAuth state token for CSRF protection+ */+export function getUpstreamAuthorizeUrl({+ upstream_url,+ client_id,+ scope,+ redirect_uri,+ state,+}: {+ upstream_url: string;+ client_id: string;+ scope: string;+ redirect_uri: string;+ state?: string;+}) {+ const upstream = new URL(upstream_url);+ upstream.searchParams.set('client_id', client_id);+ upstream.searchParams.set('redirect_uri', redirect_uri);+ upstream.searchParams.set('scope', scope);+ if (state) upstream.searchParams.set('state', state);+ upstream.searchParams.set('response_type', 'code');+ upstream.searchParams.set('access_type', 'offline'); // For refresh tokens+ upstream.searchParams.set('prompt', 'consent'); // Always show consent screen+ return upstream.href;+}++/**+ * Fetches an authorization token from Google+ *+ * @returns Tuple of [accessToken, null] on success or [null, Response] on error+ */+export async function fetchUpstreamAuthToken({+ client_id,+ client_secret,+ code,+ redirect_uri,+ upstream_url,+}: {+ code: string | undefined;+ upstream_url: string;+ client_secret: string;+ redirect_uri: string;+ client_id: string;+}): Promise<[string, null] | [null, Response]> {+ if (!code) {+ return [null, new Response('Missing code', { status: 400 })];+ }++ const resp = await fetch(upstream_url, {+ body: new URLSearchParams({+ client_id,+ client_secret,+ code,+ redirect_uri,+ grant_type: 'authorization_code',+ }).toString(),+ headers: {+ 'Content-Type': 'application/x-www-form-urlencoded',+ },+ method: 'POST',+ });++ if (!resp.ok) {+ const errorText = await resp.text();+ console.error('Google token exchange failed:', errorText);+ return [null, new Response('Failed to fetch access token', { status: 500 })];+ }++ const body = await resp.json() as { access_token?: string; error?: string };++ if (body.error) {+ console.error('Google OAuth error:', body.error);+ return [null, new Response(`OAuth error: ${body.error}`, { status: 400 })];+ }++ const accessToken = body.access_token;+ if (!accessToken) {+ return [null, new Response('Missing access token', { status: 400 })];+ }++ return [accessToken, null];+}++/**+ * Fetches user info from Google+ *+ * @param accessToken - Google access token+ * @returns User object with id, email, name, picture or null on error+ */+export async function fetchGoogleUserInfo(accessToken: string): Promise<{+ id: string;+ email: string;+ name: string;+ picture?: string;+} | null> {+ const resp = await fetch('https://www.googleapis.com/oauth2/v2/userinfo', {+ headers: {+ Authorization: `Bearer ${accessToken}`,+ },+ });++ if (!resp.ok) {+ console.error('Failed to fetch Google user info:', await resp.text());+ return null;+ }++ const user = await resp.json() as {+ id: string;+ email: string;+ name: string;+ picture?: string;+ };++ return user;+}diff --git a/skills/mcp-oauth-cloudflare/templates/oauth/workers-oauth-utils.ts b/skills/mcp-oauth-cloudflare/templates/oauth/workers-oauth-utils.tsnew file mode 100644index 00000000..62663372--- /dev/null+++ b/skills/mcp-oauth-cloudflare/templates/oauth/workers-oauth-utils.ts@@ -0,0 +1,730 @@+/**+ * OAuth Security Utilities for Cloudflare Workers+ *+ * Features:+ * - CSRF protection with HttpOnly cookies+ * - OAuth state management with KV storage+ * - Session binding to prevent token theft+ * - Client approval caching (30-day TTL)+ * - Beautiful approval dialog UI+ *+ * Based on Cloudflare's official OAuth patterns+ */++import type { AuthRequest, ClientInfo } from '@cloudflare/workers-oauth-provider';++/**+ * OAuth 2.1 compliant error class+ */+export class OAuthError extends Error {+ constructor(+ public code: string,+ public description: string,+ public statusCode = 400+ ) {+ super(description);+ this.name = 'OAuthError';+ }++ toResponse(): Response {+ return new Response(+ JSON.stringify({+ error: this.code,+ error_description: this.description,+ }),+ {+ status: this.statusCode,+ headers: { 'Content-Type': 'application/json' },+ }+ );+ }+}++export interface OAuthStateResult {+ stateToken: string;+}++export interface ValidateStateResult {+ oauthReqInfo: AuthRequest;+ clearCookie: string;+}++export interface BindStateResult {+ setCookie: string;+}++export interface CSRFProtectionResult {+ token: string;+ setCookie: string;+}++export interface ValidateCSRFResult {+ clearCookie: string;+}++// ===== Sanitization =====++/**+ * Sanitizes text content for safe display in HTML+ */+export function sanitizeText(text: string): string {+ return text+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"')+ .replace(/'/g, ''');+}++/**+ * Validates a URL for security - whitelist only http/https+ */+export function sanitizeUrl(url: string): string {+ const normalized = url.trim();+ if (normalized.length === 0) return '';++ // Check for control characters+ for (let i = 0; i < normalized.length; i++) {+ const code = normalized.charCodeAt(i);+ if ((code >= 0x00 && code <= 0x1f) || (code >= 0x7f && code <= 0x9f)) {+ return '';+ }+ }++ let parsedUrl: URL;+ try {+ parsedUrl = new URL(normalized);+ } catch {+ return '';+ }++ const allowedSchemes = ['https', 'http'];+ const scheme = parsedUrl.protocol.slice(0, -1).toLowerCase();+ if (!allowedSchemes.includes(scheme)) {+ return '';+ }++ return normalized;+}++// ===== CSRF Protection =====++/**+ * Generates CSRF token and cookie+ * - HttpOnly: JavaScript can't access+ * - Secure: HTTPS only+ * - SameSite=Lax: Prevents cross-site requests+ * - 10-minute expiration+ */+export function generateCSRFProtection(): CSRFProtectionResult {+ const csrfCookieName = '__Host-CSRF_TOKEN';+ const token = crypto.randomUUID();+ const setCookie = `${csrfCookieName}=${token}; HttpOnly; Secure; Path=/; SameSite=Lax; Max-Age=600`;+ return { token, setCookie };+}++/**+ * Validates CSRF token from form matches cookie+ */+export function validateCSRFToken(formData: FormData, request: Request): ValidateCSRFResult {+ const csrfCookieName = '__Host-CSRF_TOKEN';+ const tokenFromForm = formData.get('csrf_token');++ if (!tokenFromForm || typeof tokenFromForm !== 'string') {+ throw new OAuthError('invalid_request', 'Missing CSRF token in form data', 400);+ }++ const cookieHeader = request.headers.get('Cookie') || '';+ const cookies = cookieHeader.split(';').map((c) => c.trim());+ const csrfCookie = cookies.find((c) => c.startsWith(`${csrfCookieName}=`));+ const tokenFromCookie = csrfCookie ? csrfCookie.substring(csrfCookieName.length + 1) : null;++ if (!tokenFromCookie) {+ throw new OAuthError('invalid_request', 'Missing CSRF token cookie', 400);+ }++ if (tokenFromForm !== tokenFromCookie) {+ throw new OAuthError('invalid_request', 'CSRF token mismatch', 400);+ }++ const clearCookie = `${csrfCookieName}=; HttpOnly; Secure; Path=/; SameSite=Lax; Max-Age=0`;+ return { clearCookie };+}++// ===== OAuth State Management =====++/**+ * Creates and stores OAuth state information in KV+ * - One-time use (deleted after validation)+ * - 10-minute TTL by default+ */+export async function createOAuthState(+ oauthReqInfo: AuthRequest,+ kv: KVNamespace,+ stateTTL = 600+): Promise<OAuthStateResult> {+ const stateToken = crypto.randomUUID();+ await kv.put(`oauth:state:${stateToken}`, JSON.stringify(oauthReqInfo), {+ expirationTtl: stateTTL,+ });+ return { stateToken };+}++/**+ * Binds OAuth state token to user's browser session+ * - SHA-256 hash prevents tampering+ * - Cookie ensures same browser completes flow+ */+export async function bindStateToSession(stateToken: string): Promise<BindStateResult> {+ const consentedStateCookieName = '__Host-CONSENTED_STATE';++ const encoder = new TextEncoder();+ const data = encoder.encode(stateToken);+ const hashBuffer = await crypto.subtle.digest('SHA-256', data);+ const hashArray = Array.from(new Uint8Array(hashBuffer));+ const hashHex = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');++ const setCookie = `${consentedStateCookieName}=${hashHex}; HttpOnly; Secure; Path=/; SameSite=Lax; Max-Age=600`;+ return { setCookie };+}++/**+ * Validates OAuth state from the request+ * - Checks state exists in KV+ * - Validates session binding cookie matches+ * - Deletes state after use (one-time)+ */+export async function validateOAuthState(+ request: Request,+ kv: KVNamespace+): Promise<ValidateStateResult> {+ const consentedStateCookieName = '__Host-CONSENTED_STATE';+ const url = new URL(request.url);+ const stateFromQuery = url.searchParams.get('state');++ if (!stateFromQuery) {+ throw new OAuthError('invalid_request', 'Missing state parameter', 400);+ }++ const storedDataJson = await kv.get(`oauth:state:${stateFromQuery}`);+ if (!storedDataJson) {+ throw new OAuthError('invalid_request', 'Invalid or expired state', 400);+ }++ // Validate session binding+ const cookieHeader = request.headers.get('Cookie') || '';+ const cookies = cookieHeader.split(';').map((c) => c.trim());+ const consentedStateCookie = cookies.find((c) => c.startsWith(`${consentedStateCookieName}=`));+ const consentedStateHash = consentedStateCookie+ ? consentedStateCookie.substring(consentedStateCookieName.length + 1)+ : null;++ if (!consentedStateHash) {+ throw new OAuthError(+ 'invalid_request',+ 'Missing session binding cookie - authorization flow must be restarted',+ 400+ );+ }++ // Hash and compare+ const encoder = new TextEncoder();+ const data = encoder.encode(stateFromQuery);+ const hashBuffer = await crypto.subtle.digest('SHA-256', data);+ const hashArray = Array.from(new Uint8Array(hashBuffer));+ const stateHash = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');++ if (stateHash !== consentedStateHash) {+ throw new OAuthError(+ 'invalid_request',+ 'State token does not match session - possible CSRF attack detected',+ 400+ );+ }++ let oauthReqInfo: AuthRequest;+ try {+ oauthReqInfo = JSON.parse(storedDataJson) as AuthRequest;+ } catch {+ throw new OAuthError('server_error', 'Invalid state data', 500);+ }++ // Delete state (one-time use only!)+ await kv.delete(`oauth:state:${stateFromQuery}`);++ const clearCookie = `${consentedStateCookieName}=; HttpOnly; Secure; Path=/; SameSite=Lax; Max-Age=0`;+ return { oauthReqInfo, clearCookie };+}++// ===== Client Approval Caching =====++/**+ * Checks if a client has been previously approved+ */+export async function isClientApproved(+ request: Request,+ clientId: string,+ cookieSecret: string+): Promise<boolean> {+ const approvedClients = await getApprovedClientsFromCookie(request, cookieSecret);+ return approvedClients?.includes(clientId) ?? false;+}++/**+ * Adds a client to approved list+ * - HMAC-signed to prevent tampering+ * - 30-day TTL (users won't re-approve frequently)+ */+export async function addApprovedClient(+ request: Request,+ clientId: string,+ cookieSecret: string+): Promise<string> {+ const approvedClientsCookieName = '__Host-APPROVED_CLIENTS';+ const THIRTY_DAYS_IN_SECONDS = 2592000;++ const existingApprovedClients = (await getApprovedClientsFromCookie(request, cookieSecret)) || [];+ const updatedApprovedClients = Array.from(new Set([...existingApprovedClients, clientId]));++ const payload = JSON.stringify(updatedApprovedClients);+ const signature = await signData(payload, cookieSecret);+ const cookieValue = `${signature}.${btoa(payload)}`;++ return `${approvedClientsCookieName}=${cookieValue}; HttpOnly; Secure; Path=/; SameSite=Lax; Max-Age=${THIRTY_DAYS_IN_SECONDS}`;+}++// ===== Approval Dialog =====++export interface ApprovalDialogOptions {+ client: ClientInfo | null;+ server: {+ name: string;+ logo?: string;+ description?: string;+ };+ state: Record<string, any>;+ csrfToken: string;+ setCookie: string;+}++/**+ * Renders OAuth approval dialog+ * TEMPLATE: Customize the colors and styling as needed+ */+export function renderApprovalDialog(request: Request, options: ApprovalDialogOptions): Response {+ const { client, server, state, csrfToken, setCookie } = options;++ const encodedState = btoa(JSON.stringify(state));+ const serverName = sanitizeText(server.name);+ const clientName = client?.clientName ? sanitizeText(client.clientName) : 'Unknown MCP Client';+ const serverDescription = server.description ? sanitizeText(server.description) : '';++ const logoUrl = server.logo ? sanitizeText(sanitizeUrl(server.logo)) : '';+ const clientUri = client?.clientUri ? sanitizeText(sanitizeUrl(client.clientUri)) : '';++ const htmlContent = `+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>${clientName} | Authorization Request</title>+ <link rel="preconnect" href="https://fonts.googleapis.com">+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet">+ <style>+ * { margin: 0; padding: 0; box-sizing: border-box; }++ :root {+ --background: #09090b;+ --foreground: #fafafa;+ --card: #18181b;+ --card-foreground: #fafafa;+ --muted: #27272a;+ --muted-foreground: #a1a1aa;+ --border: #27272a;+ --primary: #3b82f6;+ --primary-foreground: #fafafa;+ --secondary: #27272a;+ --secondary-foreground: #fafafa;+ --accent: #7c3aed;+ --radius: 0.75rem;+ }++ body {+ font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;+ line-height: 1.6;+ color: var(--foreground);+ background: var(--background);+ margin: 0;+ padding: 0;+ min-height: 100vh;+ display: flex;+ align-items: center;+ justify-content: center;+ position: relative;+ overflow: hidden;+ }++ body::before {+ content: '';+ position: absolute;+ top: 0;+ left: 0;+ right: 0;+ bottom: 0;+ background:+ radial-gradient(ellipse at 20% 20%, rgba(59, 130, 246, 0.15) 0%, transparent 50%),+ radial-gradient(ellipse at 80% 80%, rgba(124, 58, 237, 0.15) 0%, transparent 50%),+ radial-gradient(ellipse at 50% 50%, rgba(16, 185, 129, 0.05) 0%, transparent 70%);+ pointer-events: none;+ }++ body::after {+ content: '';+ position: absolute;+ top: 0;+ left: 0;+ right: 0;+ bottom: 0;+ background-image:+ linear-gradient(rgba(255,255,255,0.02) 1px, transparent 1px),+ linear-gradient(90deg, rgba(255,255,255,0.02) 1px, transparent 1px);+ background-size: 64px 64px;+ pointer-events: none;+ }++ .container {+ max-width: 420px;+ width: 100%;+ margin: 1.5rem;+ position: relative;+ z-index: 1;+ }++ .card {+ background: var(--card);+ border: 1px solid var(--border);+ border-radius: var(--radius);+ padding: 2rem;+ box-shadow:+ 0 0 0 1px rgba(255,255,255,0.05),+ 0 20px 50px -12px rgba(0,0,0,0.5),+ 0 0 100px -20px rgba(59, 130, 246, 0.2);+ }++ .header {+ text-align: center;+ margin-bottom: 1.5rem;+ }++ .logo-container {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 56px;+ height: 56px;+ border-radius: 12px;+ background: linear-gradient(135deg, var(--primary) 0%, var(--accent) 100%);+ margin-bottom: 1rem;+ box-shadow: 0 0 30px -5px rgba(59, 130, 246, 0.5);+ }++ .logo {+ width: 56px;+ height: 56px;+ border-radius: 12px;+ object-fit: cover;+ }++ .logo-fallback {+ font-size: 1.5rem;+ font-weight: 600;+ color: white;+ }++ .title {+ font-size: 1.25rem;+ font-weight: 600;+ color: var(--foreground);+ margin-bottom: 0.25rem;+ letter-spacing: -0.02em;+ }++ .description {+ color: var(--muted-foreground);+ font-size: 0.875rem;+ }++ .divider {+ height: 1px;+ background: var(--border);+ margin: 1.5rem 0;+ }++ .request-card {+ background: var(--muted);+ border: 1px solid var(--border);+ border-radius: calc(var(--radius) - 2px);+ padding: 1rem;+ margin-bottom: 1rem;+ }++ .request-header {+ display: flex;+ align-items: center;+ gap: 0.75rem;+ margin-bottom: 0.75rem;+ }++ .client-avatar {+ width: 36px;+ height: 36px;+ border-radius: 8px;+ background: linear-gradient(135deg, #10b981 0%, #059669 100%);+ display: flex;+ align-items: center;+ justify-content: center;+ font-weight: 600;+ font-size: 0.875rem;+ color: white;+ }++ .client-info {+ flex: 1;+ }++ .client-name {+ font-weight: 600;+ color: var(--foreground);+ font-size: 0.9375rem;+ }++ .client-uri {+ color: var(--muted-foreground);+ font-size: 0.75rem;+ }++ .request-badge {+ display: inline-flex;+ align-items: center;+ gap: 0.375rem;+ background: rgba(59, 130, 246, 0.1);+ border: 1px solid rgba(59, 130, 246, 0.2);+ color: #60a5fa;+ font-size: 0.75rem;+ font-weight: 500;+ padding: 0.25rem 0.625rem;+ border-radius: 9999px;+ }++ .request-badge svg {+ width: 12px;+ height: 12px;+ }++ .permissions {+ font-size: 0.8125rem;+ color: var(--muted-foreground);+ line-height: 1.5;+ }++ .permissions strong {+ color: var(--foreground);+ font-weight: 500;+ }++ .actions {+ display: flex;+ gap: 0.75rem;+ margin-top: 1.5rem;+ }++ .button {+ flex: 1;+ padding: 0.625rem 1.25rem;+ border-radius: calc(var(--radius) - 2px);+ font-weight: 500;+ font-size: 0.875rem;+ cursor: pointer;+ border: none;+ transition: all 0.15s ease;+ font-family: inherit;+ }++ .button-secondary {+ background: var(--secondary);+ color: var(--secondary-foreground);+ border: 1px solid var(--border);+ }++ .button-secondary:hover {+ background: #3f3f46;+ border-color: #3f3f46;+ }++ .button-primary {+ background: var(--primary);+ color: var(--primary-foreground);+ box-shadow: 0 0 20px -5px rgba(59, 130, 246, 0.5);+ }++ .button-primary:hover {+ background: #2563eb;+ box-shadow: 0 0 25px -5px rgba(59, 130, 246, 0.6);+ transform: translateY(-1px);+ }++ .footer {+ text-align: center;+ margin-top: 1.5rem;+ padding-top: 1rem;+ border-top: 1px solid var(--border);+ }++ .footer-text {+ font-size: 0.75rem;+ color: var(--muted-foreground);+ }++ .footer-text a {+ color: var(--primary);+ text-decoration: none;+ }++ .footer-text a:hover {+ text-decoration: underline;+ }+ </style>+</head>+<body>+ <div class="container">+ <div class="card">+ <div class="header">+ ${logoUrl+ ? '<img src="' + logoUrl + '" alt="' + serverName + '" class="logo">'+ : '<div class="logo-container"><span class="logo-fallback">' + serverName.charAt(0) + '</span></div>'+ }+ <h1 class="title">${serverName}</h1>+ ${serverDescription ? '<p class="description">' + serverDescription + '</p>' : ''}+ </div>++ <div class="request-card">+ <div class="request-header">+ <div class="client-avatar">${clientName.charAt(0)}</div>+ <div class="client-info">+ <div class="client-name">${clientName}</div>+ ${clientUri ? '<div class="client-uri">' + clientUri + '</div>' : ''}+ </div>+ </div>+ <span class="request-badge">+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">+ <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10"/>+ </svg>+ Requesting access+ </span>+ </div>++ <p class="permissions">+ This will allow <strong>${clientName}</strong> to access your MCP server tools and resources.+ </p>++ <form method="post" action="${new URL(request.url).pathname}">+ <input type="hidden" name="state" value="${encodedState}">+ <input type="hidden" name="csrf_token" value="${csrfToken}">++ <div class="actions">+ <button type="button" class="button button-secondary" onclick="window.history.back()">Cancel</button>+ <button type="submit" class="button button-primary">Approve</button>+ </div>+ </form>++ <div class="footer">+ <p class="footer-text">Secured by OAuth 2.0 with Google</p>+ </div>+ </div>+ </div>+</body>+</html>+ `;++ return new Response(htmlContent, {+ headers: {+ 'Content-Security-Policy': "frame-ancestors 'none'",+ 'Content-Type': 'text/html; charset=utf-8',+ 'Set-Cookie': setCookie,+ 'X-Frame-Options': 'DENY',+ },+ });+}++// ===== Helper Functions =====++async function getApprovedClientsFromCookie(+ request: Request,+ cookieSecret: string+): Promise<string[] | null> {+ const approvedClientsCookieName = '__Host-APPROVED_CLIENTS';++ const cookieHeader = request.headers.get('Cookie');+ if (!cookieHeader) return null;++ const cookies = cookieHeader.split(';').map((c) => c.trim());+ const targetCookie = cookies.find((c) => c.startsWith(`${approvedClientsCookieName}=`));++ if (!targetCookie) return null;++ const cookieValue = targetCookie.substring(approvedClientsCookieName.length + 1);+ const parts = cookieValue.split('.');++ if (parts.length !== 2) return null;++ const [signatureHex, base64Payload] = parts;+ const payload = atob(base64Payload);++ const isValid = await verifySignature(signatureHex, payload, cookieSecret);+ if (!isValid) return null;++ try {+ const approvedClients = JSON.parse(payload);+ if (!Array.isArray(approvedClients) || !approvedClients.every((item) => typeof item === 'string')) {+ return null;+ }+ return approvedClients as string[];+ } catch {+ return null;+ }+}++async function signData(data: string, secret: string): Promise<string> {+ const key = await importKey(secret);+ const enc = new TextEncoder();+ const signatureBuffer = await crypto.subtle.sign('HMAC', key, enc.encode(data));+ return Array.from(new Uint8Array(signatureBuffer))+ .map((b) => b.toString(16).padStart(2, '0'))+ .join('');+}++async function verifySignature(signatureHex: string, data: string, secret: string): Promise<boolean> {+ const key = await importKey(secret);+ const enc = new TextEncoder();+ try {+ const signatureBytes = new Uint8Array(+ signatureHex.match(/.{1,2}/g)!.map((byte) => Number.parseInt(byte, 16))+ );+ return await crypto.subtle.verify('HMAC', key, signatureBytes.buffer, enc.encode(data));+ } catch {+ return false;+ }+}++async function importKey(secret: string): Promise<CryptoKey> {+ if (!secret) {+ throw new Error('cookieSecret is required for signing cookies');+ }+ const enc = new TextEncoder();+ return crypto.subtle.importKey('raw', enc.encode(secret), { hash: 'SHA-256', name: 'HMAC' }, false, [+ 'sign',+ 'verify',+ ]);+}diff --git a/skills/mcp-oauth-cloudflare/templates/package.json b/skills/mcp-oauth-cloudflare/templates/package.jsonnew file mode 100644index 00000000..04fe8b4e--- /dev/null+++ b/skills/mcp-oauth-cloudflare/templates/package.json@@ -0,0 +1,32 @@+{+ "name": "my-mcp-server",+ "version": "1.0.0",+ "description": "MCP server with OAuth authentication",+ "main": "src/index.ts",+ "scripts": {+ "dev": "wrangler dev --remote",+ "deploy": "wrangler deploy",+ "tail": "wrangler tail",+ "cf-typegen": "wrangler types"+ },+ "keywords": [+ "mcp",+ "cloudflare",+ "workers",+ "oauth"+ ],+ "author": "",+ "license": "MIT",+ "devDependencies": {+ "@cloudflare/workers-types": "^4.20241127.0",+ "typescript": "^5.7.2",+ "wrangler": "^3.94.0"+ },+ "dependencies": {+ "@cloudflare/workers-oauth-provider": "^0.1.0",+ "@modelcontextprotocol/sdk": "^1.25.1",+ "agents": "^0.2.32",+ "hono": "^4.6.14",+ "zod": "^3.24.1"+ }+}diff --git a/skills/mcp-oauth-cloudflare/templates/wrangler.jsonc b/skills/mcp-oauth-cloudflare/templates/wrangler.jsoncnew file mode 100644index 00000000..02d62882--- /dev/null+++ b/skills/mcp-oauth-cloudflare/templates/wrangler.jsonc@@ -0,0 +1,51 @@+{+ // TEMPLATE: MCP Server with OAuth+ // Copy and customize for your project++ "name": "my-mcp-server", // TODO: Change this+ "main": "src/index.ts",+ "compatibility_date": "2024-09-23",+ "compatibility_flags": ["nodejs_compat"],++ // KV namespace for OAuth state management+ // Create with: npx wrangler kv:namespace create OAUTH_KV+ "kv_namespaces": [+ {+ "binding": "OAUTH_KV",+ "id": "YOUR_KV_NAMESPACE_ID" // TODO: Replace with actual ID+ }+ ],++ // Durable Objects for MCP session management+ "durable_objects": {+ "bindings": [+ {+ "class_name": "MyMcpServer", // TODO: Match your class name+ "name": "MCP_OBJECT"+ }+ ]+ },++ // Migrations for Durable Objects SQLite+ "migrations": [+ {+ "new_sqlite_classes": ["MyMcpServer"], // TODO: Match your class name+ "tag": "v1"+ }+ ],++ // Optional: Enable observability+ "observability": {+ "enabled": true+ },++ // Development server config+ "dev": {+ "port": 8787+ }++ // ===== Required Secrets (set via wrangler secret put) =====+ // GOOGLE_CLIENT_ID - From Google Cloud Console+ // GOOGLE_CLIENT_SECRET - From Google Cloud Console+ // COOKIE_ENCRYPTION_KEY - Generate with: python3 -c "import secrets; print(secrets.token_urlsafe(32))"+}