Skills for Claude Code CLI such as full stack dev Cloudflare, React, Tailwind v4, and AI integrations.
Python aianthropicautomationclaude-codeclaude-skillscloudflaredevtoolsproductivityreactskillstailwindvite
feat(google-workspace): Add unified skill for all Google Workspace APIs
Jez622825e5df99
diff --git a/skills/google-workspace/README.md b/skills/google-workspace/README.mdnew file mode 100644index 00000000..0fd718d1--- /dev/null+++ b/skills/google-workspace/README.md@@ -0,0 +1,95 @@+# Google Workspace APIs++**Status**: Production Ready+**Last Updated**: 2026-01-03++## Auto-Trigger Keywords++### General+- google workspace, google workspace api, google apis+- google oauth, google service account, domain-wide delegation+- google api rate limit, google quota exceeded, 429 error++### Gmail+- gmail api, gmail integration, email automation+- gmail labels, gmail threads, gmail attachments+- gmail mcp, gmail push notifications++### Calendar+- google calendar, calendar api, calendar events+- recurring events, free busy, calendar sharing+- calendar mcp, event scheduling++### Drive+- google drive, drive api, file upload+- drive permissions, drive sharing, file search+- drive mcp, file storage++### Sheets+- google sheets, sheets api, spreadsheet+- a1 notation, sheets batch update, cell formatting+- sheets mcp, spreadsheet automation++### Docs+- google docs, docs api, document generation+- docs mcp, document automation++### Chat+- google chat, google chat api, google spaces+- chat bot, chat webhooks, cards v2+- chat mcp, interactive cards, chat forms++### Meet+- google meet, meet api, video conferencing+- meet mcp, meeting scheduling++### Forms+- google forms, forms api, form responses+- forms mcp, survey automation++### Tasks+- google tasks, tasks api, task management+- tasks mcp, todo automation++### Admin+- google admin, admin sdk, user management+- group management, domain admin+- admin mcp, workspace admin++## What This Skill Does++Comprehensive guide for building integrations with all Google Workspace APIs. Covers OAuth 2.0, service accounts, rate limits, batch operations, and Cloudflare Workers patterns.++## Core Capabilities++**Shared Patterns:**+- OAuth 2.0 with refresh tokens+- Service account authentication+- Domain-wide delegation+- Rate limit handling with exponential backoff+- Batch request patterns++**APIs Covered:**+- Gmail, Calendar, Drive, Sheets, Docs+- Chat, Meet, Forms, Tasks+- Admin SDK, People API++## Quick Start++```bash+# No npm packages required - use fetch API directly+# Just need jose for service account JWT signing+npm install jose+```++See [SKILL.md](SKILL.md) for complete documentation.++## Token Savings++- **Manual research**: ~15k tokens per API+- **With Skill**: ~3k tokens (shared patterns) + ~2k per API+- **Savings**: ~60-70%++## Production Tested++Built from real MCP server implementations for Google Workspace APIs.diff --git a/skills/google-workspace/SKILL.md b/skills/google-workspace/SKILL.mdnew file mode 100644index 00000000..b6d0ad5a--- /dev/null+++ b/skills/google-workspace/SKILL.md@@ -0,0 +1,384 @@+---+name: google-workspace+description: |+ Build integrations with Google Workspace APIs (Gmail, Calendar, Drive, Sheets, Docs, Chat, Meet, Forms, Tasks, Admin SDK). Covers OAuth 2.0, service accounts, rate limits, batch operations, and Cloudflare Workers patterns.++ Use when building MCP servers, automation tools, or integrations with any Google Workspace API, or troubleshooting OAuth errors, rate limit 429 errors, scope issues, or API-specific gotchas.+---++# Google Workspace APIs++**Status**: Production Ready+**Last Updated**: 2026-01-03+**Dependencies**: Cloudflare Workers (recommended), Google Cloud Project+**Skill Version**: 1.0.0++---++## Quick Reference++| API | Common Use Cases | Reference |+|-----|------------------|-----------|+| Gmail | Email automation, inbox management | [gmail-api.md](references/gmail-api.md) |+| Calendar | Event management, scheduling | [calendar-api.md](references/calendar-api.md) |+| Drive | File storage, sharing | [drive-api.md](references/drive-api.md) |+| Sheets | Spreadsheet data, reporting | [sheets-api.md](references/sheets-api.md) |+| Docs | Document generation | [docs-api.md](references/docs-api.md) |+| Chat | Bots, webhooks, spaces | [chat-api.md](references/chat-api.md) |+| Meet | Video conferencing | [meet-api.md](references/meet-api.md) |+| Forms | Form responses, creation | [forms-api.md](references/forms-api.md) |+| Tasks | Task management | [tasks-api.md](references/tasks-api.md) |+| Admin SDK | User/group management | [admin-sdk.md](references/admin-sdk.md) |+| People | Contacts management | [people-api.md](references/people-api.md) |++---++## Shared Authentication Patterns++All Google Workspace APIs use the same authentication mechanisms. Choose based on your use case.++### Option 1: OAuth 2.0 (User Context)++Best for: Acting on behalf of a user, accessing user-specific data.++```typescript+// Authorization URL+const authUrl = new URL('https://accounts.google.com/o/oauth2/v2/auth')+authUrl.searchParams.set('client_id', env.GOOGLE_CLIENT_ID)+authUrl.searchParams.set('redirect_uri', `${env.BASE_URL}/callback`)+authUrl.searchParams.set('response_type', 'code')+authUrl.searchParams.set('scope', SCOPES.join(' '))+authUrl.searchParams.set('access_type', 'offline') // For refresh tokens+authUrl.searchParams.set('prompt', 'consent') // Force consent for refresh token++// Token exchange+async function exchangeCode(code: string): Promise<TokenResponse> {+ const response = await fetch('https://oauth2.googleapis.com/token', {+ method: 'POST',+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },+ body: new URLSearchParams({+ code,+ client_id: env.GOOGLE_CLIENT_ID,+ client_secret: env.GOOGLE_CLIENT_SECRET,+ redirect_uri: `${env.BASE_URL}/callback`,+ grant_type: 'authorization_code',+ }),+ })+ return response.json()+}++// Refresh token+async function refreshToken(refresh_token: string): Promise<TokenResponse> {+ const response = await fetch('https://oauth2.googleapis.com/token', {+ method: 'POST',+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },+ body: new URLSearchParams({+ refresh_token,+ client_id: env.GOOGLE_CLIENT_ID,+ client_secret: env.GOOGLE_CLIENT_SECRET,+ grant_type: 'refresh_token',+ }),+ })+ return response.json()+}+```++**Critical:**+- Always request `access_type=offline` for refresh tokens+- Use `prompt=consent` to ensure refresh token is returned+- Store refresh tokens securely (Cloudflare KV or D1)+- Access tokens expire in ~1 hour++### Option 2: Service Account (Server-to-Server)++Best for: Backend automation, no user interaction, domain-wide delegation.++```typescript+import { SignJWT } from 'jose'++async function getServiceAccountToken(+ serviceAccount: ServiceAccountKey,+ scopes: string[]+): Promise<string> {+ const now = Math.floor(Date.now() / 1000)++ // Create JWT+ const jwt = await new SignJWT({+ iss: serviceAccount.client_email,+ scope: scopes.join(' '),+ aud: 'https://oauth2.googleapis.com/token',+ iat: now,+ exp: now + 3600,+ })+ .setProtectedHeader({ alg: 'RS256', typ: 'JWT' })+ .sign(await importPKCS8(serviceAccount.private_key, 'RS256'))++ // Exchange JWT for access token+ const response = await fetch('https://oauth2.googleapis.com/token', {+ method: 'POST',+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },+ body: new URLSearchParams({+ grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',+ assertion: jwt,+ }),+ })++ const data = await response.json()+ return data.access_token+}+```++**Domain-Wide Delegation** (impersonate users):+```typescript+const jwt = await new SignJWT({+ iss: serviceAccount.client_email,+ sub: '[email protected]', // User to impersonate+ scope: scopes.join(' '),+ aud: 'https://oauth2.googleapis.com/token',+ iat: now,+ exp: now + 3600,+})+```++**Setup Required:**+1. Create service account in Google Cloud Console+2. Download JSON key file+3. Enable domain-wide delegation in Admin Console (if impersonating)+4. Store key as Cloudflare secret (JSON stringified)++---++## Common Rate Limits++All Google Workspace APIs enforce quotas. These are approximate - check each API's specific limits.++### Per-User Limits (OAuth)++| API | Reads | Writes | Notes |+|-----|-------|--------|-------|+| Gmail | 250/user/sec | 250/user/sec | Aggregate across all methods |+| Calendar | 500/user/100sec | 500/user/100sec | Per calendar |+| Drive | 1000/user/100sec | 1000/user/100sec | |+| Sheets | 100/user/100sec | 100/user/100sec | Lower than others |++### Per-Project Limits++| API | Daily Quota | Per-Minute | Notes |+|-----|-------------|------------|-------|+| Gmail | 1B units | Varies | Unit-based (send = 100 units) |+| Calendar | 1M queries | 500/sec | |+| Drive | 1B queries | 1000/sec | |+| Sheets | Unlimited | 500/user/100sec | |++### Handling Rate Limits++```typescript+async function withRetry<T>(+ fn: () => Promise<T>,+ maxRetries = 5+): Promise<T> {+ for (let i = 0; i < maxRetries; i++) {+ try {+ return await fn()+ } catch (error: any) {+ const status = error.status || error.code++ if (status === 429 || status === 503) {+ // Rate limited or service unavailable+ const retryAfter = error.headers?.get('Retry-After') || Math.pow(2, i)+ await new Promise(r => setTimeout(r, retryAfter * 1000))+ continue+ }++ if (status === 403 && error.message?.includes('rateLimitExceeded')) {+ // Quota exceeded - exponential backoff+ await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000))+ continue+ }++ throw error+ }+ }+ throw new Error('Max retries exceeded')+}+```++---++## Batch Requests++Most Google APIs support batching multiple requests into one HTTP call.++```typescript+async function batchRequest(+ accessToken: string,+ requests: BatchRequestItem[]+): Promise<BatchResponse[]> {+ const boundary = 'batch_boundary'++ let body = ''+ requests.forEach((req, i) => {+ body += `--${boundary}\r\n`+ body += 'Content-Type: application/http\r\n'+ body += `Content-ID: <item${i}>\r\n\r\n`+ body += `${req.method} ${req.path} HTTP/1.1\r\n`+ body += 'Content-Type: application/json\r\n\r\n'+ if (req.body) body += JSON.stringify(req.body)+ body += '\r\n'+ })+ body += `--${boundary}--`++ const response = await fetch('https://www.googleapis.com/batch/v1', {+ method: 'POST',+ headers: {+ 'Authorization': `Bearer ${accessToken}`,+ 'Content-Type': `multipart/mixed; boundary=${boundary}`,+ },+ body,+ })++ // Parse multipart response...+ return parseBatchResponse(await response.text())+}+```++**Limits:**+- Max 100 requests per batch (most APIs)+- Max 1000 requests per batch (some APIs like Drive)+- Each request in batch counts toward quota++---++## Cloudflare Workers Configuration++```jsonc+// wrangler.jsonc+{+ "name": "google-workspace-mcp",+ "main": "src/index.ts",+ "compatibility_date": "2026-01-03",+ "compatibility_flags": ["nodejs_compat"],++ // Store OAuth tokens+ "kv_namespaces": [+ { "binding": "TOKENS", "id": "xxx" }+ ],++ // Or use D1 for structured storage+ "d1_databases": [+ { "binding": "DB", "database_name": "workspace-mcp", "database_id": "xxx" }+ ]+}+```++**Secrets to set:**+```bash+echo "your-client-id" | npx wrangler secret put GOOGLE_CLIENT_ID+echo "your-client-secret" | npx wrangler secret put GOOGLE_CLIENT_SECRET+# For service accounts:+cat service-account.json | npx wrangler secret put GOOGLE_SERVICE_ACCOUNT+```++---++## Common Errors++### Error: "invalid_grant" on Token Refresh+**Cause**: Refresh token revoked or expired (6 months of inactivity)+**Fix**: Re-authenticate user, request new refresh token++### Error: "access_denied" on OAuth+**Cause**: App not verified, or user not in test users list+**Fix**: Add user to OAuth consent screen test users, or complete app verification++### Error: "insufficientPermissions" (403)+**Cause**: Missing required scope+**Fix**: Check scopes in authorization URL, re-authenticate with correct scopes++### Error: "rateLimitExceeded" (403)+**Cause**: Quota exceeded+**Fix**: Implement exponential backoff, reduce request frequency, request quota increase++### Error: "notFound" (404) on Known Resource+**Cause**: Using wrong API version, or resource in trash+**Fix**: Check API version in URL, check trash for deleted items++---++## API-Specific Guides++Detailed patterns for each API are in the `references/` directory. Load these when working with specific APIs.++### Gmail API+See [references/gmail-api.md](references/gmail-api.md)+- Message CRUD, labels, threads+- MIME handling, attachments+- Push notifications (Pub/Sub)++### Calendar API+See [references/calendar-api.md](references/calendar-api.md)+- Events CRUD, recurring events+- Free/busy queries+- Calendar sharing++### Drive API+See [references/drive-api.md](references/drive-api.md)+- File upload/download+- Permissions, sharing+- Search queries++### Sheets API+See [references/sheets-api.md](references/sheets-api.md)+- Reading/writing cells+- A1 notation, ranges+- Batch updates++### Chat API+See [references/chat-api.md](references/chat-api.md)+- Bots, webhooks+- Cards v2, interactive forms+- Spaces, members, reactions++*(Additional API references added as MCP servers are built)*++---++## Package Versions (Verified 2026-01-03)++```json+{+ "devDependencies": {+ "@cloudflare/workers-types": "^4.20260103.0",+ "wrangler": "^4.54.0",+ "jose": "^5.9.6"+ }+}+```++---++## Official Documentation++- **Google Workspace APIs**: https://developers.google.com/workspace+- **OAuth 2.0**: https://developers.google.com/identity/protocols/oauth2+- **Service Accounts**: https://cloud.google.com/iam/docs/service-accounts+- **API Explorer**: https://developers.google.com/apis-explorer+- **Quotas Dashboard**: https://console.cloud.google.com/iam-admin/quotas++---++## Skill Roadmap++APIs documented as MCP servers are built:++- [ ] Gmail API+- [ ] Calendar API+- [ ] Drive API+- [ ] Sheets API+- [ ] Docs API+- [x] Chat API (migrated from google-chat-api skill)+- [ ] Meet API+- [ ] Forms API+- [ ] Tasks API+- [ ] Admin SDK+- [ ] People APIdiff --git a/skills/google-workspace/references/chat-api.md b/skills/google-workspace/references/chat-api.mdnew file mode 100644index 00000000..4c5f65f2--- /dev/null+++ b/skills/google-workspace/references/chat-api.md@@ -0,0 +1,363 @@+# Google Chat API Reference++**Last Updated**: 2026-01-03+**API Version**: v1 (stable)+**Cards**: v2 (v1 deprecated)++---++## Overview++Google Chat API enables building bots, webhooks, and integrations for Google Chat spaces.++**Two Integration Types:**+1. **Incoming Webhooks** - Send notifications (one-way, no auth needed)+2. **HTTP Endpoint Bots** - Interactive bots with Cards v2 (requires auth)++---++## Scopes++| Scope | Access |+|-------|--------|+| `chat.bot` | Bot-level access (default for bots) |+| `chat.spaces.readonly` | List/get spaces |+| `chat.spaces` | Create/update spaces |+| `chat.spaces.create` | Create spaces only |+| `chat.memberships.readonly` | List/get members |+| `chat.memberships` | Add/remove members |+| `chat.messages.readonly` | Read messages |+| `chat.messages` | Send/update messages |+| `chat.messages.reactions` | Add/remove reactions |++---++## Webhooks (Notifications Only)++No authentication required - just POST to webhook URL.++```typescript+async function sendNotification(webhookUrl: string, message: string) {+ await fetch(webhookUrl, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ text: message,+ cardsV2: [{+ cardId: `notif-${Date.now()}`,+ card: {+ header: { title: "Alert" },+ sections: [{+ widgets: [{+ textParagraph: { text: message }+ }]+ }]+ }+ }]+ })+ })+}+```++---++## Interactive Bot Handler++```typescript+export default {+ async fetch(request: Request, env: Env): Promise<Response> {+ const event = await request.json()++ switch (event.type) {+ case 'ADDED_TO_SPACE':+ return Response.json({ text: "Thanks for adding me!" })++ case 'MESSAGE':+ return handleMessage(event)++ case 'CARD_CLICKED':+ return handleCardClick(event)++ case 'REMOVED_FROM_SPACE':+ return new Response('OK')++ default:+ return Response.json({ text: "Unknown event" })+ }+ }+}+```++---++## Cards v2 Structure++```typescript+const card = {+ cardsV2: [{+ cardId: "unique-id",+ card: {+ header: {+ title: "Card Title",+ subtitle: "Optional subtitle",+ imageUrl: "https://..."+ },+ sections: [{+ header: "Section 1",+ widgets: [+ { textParagraph: { text: "Some text" } },+ { buttonList: { buttons: [...] } }+ ]+ }]+ }+ }]+}+```++**Widget Types:**+- `textParagraph` - Text content (supports Markdown and HTML)+- `buttonList` - Buttons (text or icon)+- `textInput` - Text input field+- `selectionInput` - Dropdowns, checkboxes, switches+- `dateTimePicker` - Date/time selection+- `divider` - Horizontal line+- `image` - Images+- `decoratedText` - Text with icon/button++**Limits:**+- Max 100 widgets per card (silently truncated)+- cardId must be unique++---++## Text Formatting++Cards v2 supports both Markdown and HTML:++```typescript+// Markdown (recommended for AI agents)+{ textParagraph: { text: "**bold** and *italic*\n\n- List item\n- Another" } }++// HTML+{ textParagraph: { text: "<b>bold</b> and <font color='#ea9999'>colored</font>" } }+```++**Markdown Support:**+- `**bold**`, `*italic*`+- `` `code` ``, ` ```code block``` `+- `- list item`, `1. ordered`+- `~strikethrough~`++---++## Spaces API++### List Spaces++```typescript+async function listSpaces(accessToken: string) {+ const response = await fetch(+ 'https://chat.googleapis.com/v1/spaces?pageSize=100',+ { headers: { Authorization: `Bearer ${accessToken}` } }+ )+ return response.json() // { spaces: [...], nextPageToken }+}+```++### Create Space++```typescript+async function createSpace(accessToken: string, displayName: string) {+ const response = await fetch('https://chat.googleapis.com/v1/spaces', {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${accessToken}`,+ 'Content-Type': 'application/json'+ },+ body: JSON.stringify({+ spaceType: 'SPACE', // or 'GROUP_CHAT', 'DIRECT_MESSAGE'+ displayName,+ spaceDetails: { description: 'Created via API' }+ })+ })+ return response.json()+}+```++### Search Spaces++```typescript+const params = new URLSearchParams({+ query: 'displayName:Project AND spaceType:SPACE',+ pageSize: '50'+})+const response = await fetch(+ `https://chat.googleapis.com/v1/spaces:search?${params}`,+ { headers: { Authorization: `Bearer ${accessToken}` } }+)+```++---++## Members API++### Add Member++```typescript+async function addMember(accessToken: string, spaceName: string, userEmail: string) {+ const response = await fetch(+ `https://chat.googleapis.com/v1/${spaceName}/members`,+ {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${accessToken}`,+ 'Content-Type': 'application/json'+ },+ body: JSON.stringify({+ member: { name: `users/${userEmail}`, type: 'HUMAN' },+ role: 'ROLE_MEMBER' // or 'ROLE_MANAGER'+ })+ }+ )+ return response.json()+}+```++### List Members++```typescript+const response = await fetch(+ `https://chat.googleapis.com/v1/${spaceName}/members?pageSize=100`,+ { headers: { Authorization: `Bearer ${accessToken}` } }+)+// Returns: { memberships: [...], nextPageToken }+```++---++## Reactions API++### Add Reaction++```typescript+async function addReaction(accessToken: string, messageName: string, emoji: string) {+ const response = await fetch(+ `https://chat.googleapis.com/v1/${messageName}/reactions`,+ {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${accessToken}`,+ 'Content-Type': 'application/json'+ },+ body: JSON.stringify({+ emoji: { unicode: emoji } // e.g., '👍'+ })+ }+ )+ return response.json()+}+```++---++## Rate Limits++| Operation | Per-Project | Per-Space |+|-----------|-------------|-----------|+| Read operations | 3,000/min | 15/sec |+| Message writes | 600/min | 1/sec |+| Membership writes | 300/min | - |+| Space writes | 60/min | - |+| Reactions | 600/min | - |++---++## Bearer Token Verification++For HTTP endpoint bots, verify the bearer token:++```typescript+async function verifyBearerToken(token: string): Promise<boolean> {+ // Verify token is from [email protected]+ // See full implementation in templates/bearer-token-verify.ts+ const response = await fetch(+ `https://oauth2.googleapis.com/tokeninfo?access_token=${token}`+ )+ const info = await response.json()+ return info.email === '[email protected]'+}+```++---++## Dialogs (Modals)++```typescript+function openDialog() {+ return {+ actionResponse: {+ type: "DIALOG",+ dialogAction: {+ dialog: {+ body: {+ sections: [{+ header: "Confirm Action",+ widgets: [+ { textParagraph: { text: "Are you sure?" } },+ {+ buttonList: {+ buttons: [+ { text: "Confirm", onClick: { action: { function: "confirm" } } },+ { text: "Cancel", onClick: { action: { function: "cancel" } } }+ ]+ }+ }+ ]+ }]+ }+ }+ }+ }+ }+}+```++---++## Form Validation Errors++Return correct format for validation errors:++```typescript+return Response.json({+ actionResponse: {+ type: "DIALOG",+ dialogAction: {+ actionStatus: {+ statusCode: "INVALID_ARGUMENT",+ userFacingMessage: "Email is required"+ }+ }+ }+})+```++---++## Common Errors++| Error | Cause | Fix |+|-------|-------|-----|+| 401 Unauthorized | Invalid/missing bearer token | Verify token correctly |+| 400 Invalid JSON | Wrong card schema | Check field names, nesting |+| Widgets don't render | Exceeded 100 widget limit | Split into multiple cards |+| "Unable to connect" | URL not accessible, timeout | Check worker is deployed, responds fast |+| 429 Rate limited | Quota exceeded | Implement exponential backoff |++---++## Official Docs++- **Chat API**: https://developers.google.com/workspace/chat+- **Cards v2 Reference**: https://developers.google.com/workspace/chat/api/reference/rest/v1/cards+- **Webhooks Guide**: https://developers.google.com/workspace/chat/quickstart/webhooksdiff --git a/skills/google-workspace/templates/oauth-worker.ts b/skills/google-workspace/templates/oauth-worker.tsnew file mode 100644index 00000000..b039835f--- /dev/null+++ b/skills/google-workspace/templates/oauth-worker.ts@@ -0,0 +1,176 @@+/**+ * Google Workspace OAuth Worker Template+ *+ * Handles OAuth 2.0 flow for Google Workspace APIs.+ * Stores tokens in Cloudflare KV.+ */++interface Env {+ GOOGLE_CLIENT_ID: string+ GOOGLE_CLIENT_SECRET: string+ BASE_URL: string+ TOKENS: KVNamespace+}++interface TokenResponse {+ access_token: string+ refresh_token?: string+ expires_in: number+ token_type: string+ scope: string+}++interface StoredTokens {+ access_token: string+ refresh_token: string+ expires_at: number+}++// Configure scopes for your use case+const SCOPES = [+ 'https://www.googleapis.com/auth/gmail.readonly',+ 'https://www.googleapis.com/auth/calendar.readonly',+ // Add more scopes as needed+]++export default {+ async fetch(request: Request, env: Env): Promise<Response> {+ const url = new URL(request.url)++ switch (url.pathname) {+ case '/auth':+ return handleAuth(env)+ case '/callback':+ return handleCallback(request, env)+ case '/api/example':+ return handleApiCall(request, env)+ default:+ return new Response('Not found', { status: 404 })+ }+ },+}++function handleAuth(env: Env): Response {+ const authUrl = new URL('https://accounts.google.com/o/oauth2/v2/auth')+ authUrl.searchParams.set('client_id', env.GOOGLE_CLIENT_ID)+ authUrl.searchParams.set('redirect_uri', `${env.BASE_URL}/callback`)+ authUrl.searchParams.set('response_type', 'code')+ authUrl.searchParams.set('scope', SCOPES.join(' '))+ authUrl.searchParams.set('access_type', 'offline')+ authUrl.searchParams.set('prompt', 'consent')++ return Response.redirect(authUrl.toString(), 302)+}++async function handleCallback(request: Request, env: Env): Promise<Response> {+ const url = new URL(request.url)+ const code = url.searchParams.get('code')+ const error = url.searchParams.get('error')++ if (error) {+ return new Response(`OAuth error: ${error}`, { status: 400 })+ }++ if (!code) {+ return new Response('Missing code parameter', { status: 400 })+ }++ // Exchange code for tokens+ const tokenResponse = await fetch('https://oauth2.googleapis.com/token', {+ method: 'POST',+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },+ body: new URLSearchParams({+ code,+ client_id: env.GOOGLE_CLIENT_ID,+ client_secret: env.GOOGLE_CLIENT_SECRET,+ redirect_uri: `${env.BASE_URL}/callback`,+ grant_type: 'authorization_code',+ }),+ })++ if (!tokenResponse.ok) {+ const error = await tokenResponse.text()+ return new Response(`Token exchange failed: ${error}`, { status: 400 })+ }++ const tokens: TokenResponse = await tokenResponse.json()++ // Get user info to use as key+ const userResponse = await fetch(+ 'https://www.googleapis.com/oauth2/v2/userinfo',+ { headers: { Authorization: `Bearer ${tokens.access_token}` } }+ )+ const user = await userResponse.json()++ // Store tokens+ const storedTokens: StoredTokens = {+ access_token: tokens.access_token,+ refresh_token: tokens.refresh_token!,+ expires_at: Date.now() + tokens.expires_in * 1000,+ }+ await env.TOKENS.put(`user:${user.id}`, JSON.stringify(storedTokens))++ return new Response(`Authenticated as ${user.email}`, { status: 200 })+}++async function getValidToken(userId: string, env: Env): Promise<string> {+ const stored = await env.TOKENS.get(`user:${userId}`)+ if (!stored) {+ throw new Error('No tokens found - user must authenticate')+ }++ const tokens: StoredTokens = JSON.parse(stored)++ // Check if token is expired (with 5 min buffer)+ if (Date.now() > tokens.expires_at - 300000) {+ // Refresh the token+ const refreshResponse = await fetch('https://oauth2.googleapis.com/token', {+ method: 'POST',+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },+ body: new URLSearchParams({+ refresh_token: tokens.refresh_token,+ client_id: env.GOOGLE_CLIENT_ID,+ client_secret: env.GOOGLE_CLIENT_SECRET,+ grant_type: 'refresh_token',+ }),+ })++ if (!refreshResponse.ok) {+ throw new Error('Token refresh failed - user must re-authenticate')+ }++ const newTokens: TokenResponse = await refreshResponse.json()++ // Update stored tokens+ tokens.access_token = newTokens.access_token+ tokens.expires_at = Date.now() + newTokens.expires_in * 1000+ if (newTokens.refresh_token) {+ tokens.refresh_token = newTokens.refresh_token+ }++ await env.TOKENS.put(`user:${userId}`, JSON.stringify(tokens))+ }++ return tokens.access_token+}++async function handleApiCall(request: Request, env: Env): Promise<Response> {+ // Get user ID from session/header (implement your auth)+ const userId = 'user-id-here'++ try {+ const accessToken = await getValidToken(userId, env)++ // Example: List Gmail labels+ const response = await fetch(+ 'https://gmail.googleapis.com/gmail/v1/users/me/labels',+ { headers: { Authorization: `Bearer ${accessToken}` } }+ )++ return new Response(await response.text(), {+ headers: { 'Content-Type': 'application/json' },+ })+ } catch (error: any) {+ return new Response(error.message, { status: 401 })+ }+}