@mcp-z/oauth-google 1.0.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -0
- package/dist/cjs/index.d.cts +2 -1
- package/dist/cjs/index.d.ts +2 -1
- package/dist/cjs/index.js +4 -0
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/lib/dcr-router.js.map +1 -1
- package/dist/cjs/lib/dcr-utils.js.map +1 -1
- package/dist/cjs/lib/dcr-verify.js.map +1 -1
- package/dist/cjs/lib/fetch-with-timeout.js.map +1 -1
- package/dist/cjs/lib/loopback-router.d.cts +8 -0
- package/dist/cjs/lib/loopback-router.d.ts +8 -0
- package/dist/cjs/lib/loopback-router.js +219 -0
- package/dist/cjs/lib/loopback-router.js.map +1 -0
- package/dist/cjs/lib/token-verifier.js.map +1 -1
- package/dist/cjs/providers/dcr.js.map +1 -1
- package/dist/cjs/providers/loopback-oauth.d.cts +15 -17
- package/dist/cjs/providers/loopback-oauth.d.ts +15 -17
- package/dist/cjs/providers/loopback-oauth.js +223 -156
- package/dist/cjs/providers/loopback-oauth.js.map +1 -1
- package/dist/cjs/providers/service-account.js.map +1 -1
- package/dist/cjs/schemas/index.js.map +1 -1
- package/dist/cjs/setup/config.d.cts +6 -1
- package/dist/cjs/setup/config.d.ts +6 -1
- package/dist/cjs/setup/config.js +3 -0
- package/dist/cjs/setup/config.js.map +1 -1
- package/dist/cjs/types.js.map +1 -1
- package/dist/esm/index.d.ts +2 -1
- package/dist/esm/index.js +1 -0
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/lib/dcr-router.js.map +1 -1
- package/dist/esm/lib/dcr-utils.js.map +1 -1
- package/dist/esm/lib/dcr-verify.js.map +1 -1
- package/dist/esm/lib/fetch-with-timeout.js.map +1 -1
- package/dist/esm/lib/loopback-router.d.ts +8 -0
- package/dist/esm/lib/loopback-router.js +32 -0
- package/dist/esm/lib/loopback-router.js.map +1 -0
- package/dist/esm/lib/token-verifier.js.map +1 -1
- package/dist/esm/providers/dcr.js.map +1 -1
- package/dist/esm/providers/loopback-oauth.d.ts +15 -17
- package/dist/esm/providers/loopback-oauth.js +152 -114
- package/dist/esm/providers/loopback-oauth.js.map +1 -1
- package/dist/esm/providers/service-account.js.map +1 -1
- package/dist/esm/schemas/index.js.map +1 -1
- package/dist/esm/setup/config.d.ts +6 -1
- package/dist/esm/setup/config.js +4 -0
- package/dist/esm/setup/config.js.map +1 -1
- package/dist/esm/types.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/Projects/ai/mcp-z/oauth/oauth-google/src/providers/service-account.ts"],"sourcesContent":["import { promises as fs } from 'fs';\nimport { OAuth2Client } from 'google-auth-library';\nimport { importPKCS8, SignJWT } from 'jose';\nimport type { AuthContext, EnrichedExtra, Logger, OAuth2TokenStorageProvider } from '../types.ts';\n\n/**\n * Service Account Key File Structure\n * Standard Google Cloud service account JSON key format\n */\ninterface ServiceAccountKey {\n type: 'service_account';\n project_id: string;\n private_key_id: string;\n private_key: string;\n client_email: string;\n client_id: string;\n auth_uri: string;\n token_uri: string;\n auth_provider_x509_cert_url?: string;\n client_x509_cert_url?: string;\n}\n\n/**\n * Service Account Provider Configuration\n */\nexport interface ServiceAccountConfig {\n /** Path to Google Cloud service account JSON key file */\n keyFilePath: string;\n /** OAuth scopes to request (e.g., ['https://www.googleapis.com/auth/gmail.readonly']) */\n scopes: string[];\n /** Logger for auth operations */\n logger: Logger;\n}\n\n/**\n * Token Exchange Response from Google OAuth endpoint\n */\ninterface TokenResponse {\n access_token: string;\n expires_in: number;\n token_type: string;\n}\n\n/**\n * ServiceAccountProvider implements OAuth2TokenStorageProvider using Google Service Accounts\n * with JWT-based (2-legged OAuth) authentication.\n *\n * This provider:\n * - Loads service account key file from disk\n * - Generates self-signed JWTs using RS256 algorithm\n * - Exchanges JWTs for access tokens at Google's token endpoint\n * - Does NOT store tokens (regenerates on each request)\n * - Provides single static identity (no account management)\n *\n * @example\n * ```typescript\n * const provider = new ServiceAccountProvider({\n * keyFilePath: '/path/to/service-account-key.json',\n * scopes: ['https://www.googleapis.com/auth/drive.readonly'],\n * });\n *\n * // Get authenticated OAuth2Client for googleapis\n * const auth = provider.toAuth('default');\n * const drive = google.drive({ version: 'v3', auth });\n * ```\n */\nexport class ServiceAccountProvider implements OAuth2TokenStorageProvider {\n private config: ServiceAccountConfig;\n private keyFilePath: string;\n private scopes: string[];\n private keyData?: ServiceAccountKey;\n private cachedToken?: { token: string; expiry: number };\n\n constructor(config: ServiceAccountConfig) {\n this.config = config;\n this.keyFilePath = config.keyFilePath;\n this.scopes = config.scopes;\n }\n\n /**\n * Load and parse service account key file from disk\n * Validates structure and caches for subsequent calls\n */\n private async loadKeyFile(): Promise<ServiceAccountKey> {\n // Return cached key data if already loaded\n if (this.keyData) {\n return this.keyData;\n }\n\n try {\n // Read key file from disk\n const fileContent = await fs.readFile(this.keyFilePath, 'utf-8');\n\n // Parse JSON\n let keyData: unknown;\n try {\n keyData = JSON.parse(fileContent);\n } catch (parseError) {\n throw new Error(`Failed to parse service account key file as JSON: ${this.keyFilePath}\\n` + `Error: ${parseError instanceof Error ? parseError.message : String(parseError)}`);\n }\n\n // Validate structure\n this.keyData = this.validateKeyFile(keyData);\n return this.keyData;\n } catch (error) {\n // Handle file not found\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new Error(`Service account key file not found: ${this.keyFilePath}\\nMake sure GOOGLE_SERVICE_ACCOUNT_KEY_FILE points to a valid file path.`);\n }\n\n // Handle permission errors\n if ((error as NodeJS.ErrnoException).code === 'EACCES') {\n throw new Error(`Permission denied reading service account key file: ${this.keyFilePath}\\nCheck file permissions (should be readable by current user).`);\n }\n\n // Re-throw other errors\n throw error;\n }\n }\n\n /**\n * Validate service account key file structure\n * Ensures all required fields are present and correctly typed\n */\n private validateKeyFile(data: unknown): ServiceAccountKey {\n if (!data || typeof data !== 'object') {\n throw new Error('Service account key file must contain a JSON object');\n }\n\n const obj = data as Record<string, unknown>;\n\n // Validate type field\n if (obj.type !== 'service_account') {\n throw new Error(`Invalid service account key file: Expected type \"service_account\", got \"${obj.type}\"\\nMake sure you downloaded a service account key, not an OAuth client credential.`);\n }\n\n // Validate required string fields\n const requiredFields: Array<keyof ServiceAccountKey> = ['project_id', 'private_key_id', 'private_key', 'client_email', 'client_id', 'auth_uri', 'token_uri'];\n\n const missingFields = requiredFields.filter((field) => typeof obj[field] !== 'string' || !obj[field]);\n\n if (missingFields.length > 0) {\n throw new Error(`Service account key file is missing required fields: ${missingFields.join(', ')}\\nMake sure you downloaded a complete service account key file from Google Cloud Console.`);\n }\n\n // Validate private key format\n const privateKey = obj.private_key as string;\n if (!privateKey.includes('BEGIN PRIVATE KEY') || !privateKey.includes('END PRIVATE KEY')) {\n throw new Error('Service account private_key field does not contain a valid PEM-formatted key.\\n' + 'Expected format: -----BEGIN PRIVATE KEY-----...-----END PRIVATE KEY-----');\n }\n\n return obj as unknown as ServiceAccountKey;\n }\n\n /**\n * Generate signed JWT (JSON Web Token) for service account authentication\n * Uses RS256 algorithm with private key from key file\n */\n private async generateJWT(): Promise<string> {\n const keyData = await this.loadKeyFile();\n\n // Import private key using jose\n const privateKey = await importPKCS8(keyData.private_key, 'RS256');\n\n // Current time\n const now = Math.floor(Date.now() / 1000);\n\n // Create JWT with required claims for Google OAuth\n const jwt = await new SignJWT({\n iss: keyData.client_email, // Issuer: service account email\n scope: this.scopes.join(' '), // Scopes: space-separated\n aud: 'https://oauth2.googleapis.com/token', // Audience: token endpoint\n exp: now + 3600, // Expiration: 1 hour from now\n iat: now, // Issued at: current time\n })\n .setProtectedHeader({ alg: 'RS256', typ: 'JWT' })\n .sign(privateKey);\n\n return jwt;\n }\n\n /**\n * Exchange signed JWT for access token at Google OAuth endpoint\n * POST to https://oauth2.googleapis.com/token with grant_type=jwt-bearer\n */\n private async exchangeJWT(jwt: string): Promise<{ token: string; expiry: number }> {\n const tokenEndpoint = 'https://oauth2.googleapis.com/token';\n\n try {\n const response = await fetch(tokenEndpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: new URLSearchParams({\n grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',\n assertion: jwt,\n }),\n });\n\n // Handle non-2xx responses\n if (!response.ok) {\n const errorText = await response.text();\n let errorMessage: string;\n\n try {\n const errorJson = JSON.parse(errorText);\n errorMessage = errorJson.error_description || errorJson.error || errorText;\n } catch {\n errorMessage = errorText;\n }\n\n // 400: Invalid JWT (malformed claims, expired, etc.)\n if (response.status === 400) {\n throw new Error(`Invalid service account JWT: ${errorMessage}\\nThis usually means the JWT claims are malformed or the key file is invalid.`);\n }\n\n // 401: Unauthorized (revoked service account, wrong scopes, etc.)\n if (response.status === 401) {\n throw new Error(`Service account authentication failed: ${errorMessage}\\nThe service account may have been disabled or deleted. Check Google Cloud Console.`);\n }\n\n // Other errors\n throw new Error(`Token exchange failed (HTTP ${response.status}): ${errorMessage}`);\n }\n\n // Parse successful response\n const tokenData = (await response.json()) as TokenResponse;\n\n // Calculate expiry timestamp (token expires in ~1 hour)\n const expiry = Date.now() + (tokenData.expires_in - 60) * 1000; // Subtract 60s for safety margin\n\n return {\n token: tokenData.access_token,\n expiry,\n };\n } catch (error) {\n // Network errors\n if (error instanceof TypeError && error.message.includes('fetch')) {\n throw new Error('Network error connecting to Google OAuth endpoint. Check internet connection.');\n }\n\n // Re-throw other errors\n throw error;\n }\n }\n\n /**\n * Get access token for Google APIs\n * Generates fresh JWT and exchanges for access token on each call\n *\n * Note: accountId parameter is ignored for service accounts (service account is single static identity)\n */\n async getAccessToken(_accountId?: string): Promise<string> {\n // Check if we have a valid cached token (optional optimization)\n if (this.cachedToken && this.cachedToken.expiry > Date.now()) {\n return this.cachedToken.token;\n }\n\n try {\n // Generate JWT\n const jwt = await this.generateJWT();\n\n // Exchange for access token\n const { token, expiry } = await this.exchangeJWT(jwt);\n\n // Cache token for subsequent calls (optional optimization)\n this.cachedToken = { token, expiry };\n\n return token;\n } catch (error) {\n // Add context to errors\n throw new Error(`Failed to get service account access token: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n /**\n * Get OAuth2Client with service account credentials for googleapis\n * This is the CRITICAL method that servers use to get authenticated API clients\n *\n * Service account ONLY works with accountId='service-account' (single static identity)\n *\n @param accountId - Account identifier (must be 'service-account' or undefined)\n * @returns OAuth2Client instance with access token credentials set\n */\n toAuth(accountId?: string): OAuth2Client {\n // Service account ONLY works with 'service-account' account ID\n if (accountId !== undefined && accountId !== 'service-account') {\n throw new Error(`ServiceAccountProvider only supports accountId='service-account', got '${accountId}'. Service account uses a single static identity pattern.`);\n }\n\n // Create OAuth2Client instance (no client ID/secret needed for service accounts)\n const client = new OAuth2Client();\n\n // Override getRequestMetadataAsync to provide authentication headers for each request\n // This is the method googleapis calls to get auth headers - can be async and fetch tokens on-demand\n (\n client as OAuth2Client & {\n getRequestMetadataAsync: (url?: string) => Promise<{ headers: Headers | Map<string, string> }>;\n }\n ).getRequestMetadataAsync = async (_url?: string) => {\n try {\n // Get fresh access token (can be async, will trigger JWT generation if needed)\n const token = await this.getAccessToken();\n\n // Update client credentials for consistency (other googleapis methods might check these)\n client.credentials = {\n access_token: token,\n token_type: 'Bearer',\n };\n\n // Return headers as Headers instance for proper TypeScript types\n const headers = new Headers();\n headers.set('authorization', `Bearer ${token}`);\n return { headers };\n } catch (error) {\n this.config.logger?.error('Failed to get service account access token for API request', { error });\n throw error;\n }\n };\n\n // Override getAccessToken to support googleapis client API and direct token access\n client.getAccessToken = async () => {\n try {\n const token = await this.getAccessToken();\n return { token };\n } catch (error) {\n this.config.logger?.error('Failed to get service account access token', { error });\n throw error;\n }\n };\n\n this.config.logger?.debug(`ServiceAccountProvider: OAuth2Client created for ${accountId}`);\n return client;\n }\n\n /**\n * Get service account email address\n * Used for account registration and display\n *\n * Note: accountId parameter is ignored for service accounts\n * @returns Service account email from key file (e.g., \"service-account@project.iam.gserviceaccount.com\")\n */\n async getUserEmail(_accountId?: string): Promise<string> {\n const keyData = await this.loadKeyFile();\n return keyData.client_email;\n }\n\n /**\n * Create middleware wrapper for single-user authentication\n * This is the CRITICAL method that integrates service account auth into MCP servers\n *\n * Middleware wraps tool, resource, and prompt handlers and injects authContext into extra parameter.\n * Handlers receive OAuth2Client via extra.authContext.auth for API calls.\n *\n * @returns Object with withToolAuth, withResourceAuth, withPromptAuth methods\n *\n * @example\n * ```typescript\n * // Server registration\n * const authMiddleware = provider.authMiddleware();\n * const tools = toolFactories.map(f => f()).map(authMiddleware.withToolAuth);\n * const resources = resourceFactories.map(f => f()).map(authMiddleware.withResourceAuth);\n * const prompts = promptFactories.map(f => f()).map(authMiddleware.withPromptAuth);\n *\n * // Tool handler receives auth\n * async function handler({ id }: In, extra: EnrichedExtra) {\n * // extra.authContext.auth is OAuth2Client (from middleware)\n * const gmail = google.gmail({ version: 'v1', auth: extra.authContext.auth });\n * }\n * ```\n */\n authMiddleware() {\n // Shared wrapper logic - extracts extra parameter from specified position\n // Generic T captures the actual module type; handler is cast from unknown to callable\n const wrapAtPosition = <T extends { name: string; handler: unknown; [key: string]: unknown }>(module: T, extraPosition: number): T => {\n const originalHandler = module.handler as (...args: unknown[]) => Promise<unknown>;\n\n const wrappedHandler = async (...allArgs: unknown[]) => {\n // Extract extra from the correct position\n const extra = allArgs[extraPosition] as EnrichedExtra;\n\n try {\n // Use fixed accountId for storage isolation (like device-code pattern)\n const accountId = 'service-account';\n\n // Get service account email for logging/display\n const serviceEmail = await this.getUserEmail();\n\n // Get access token (generates JWT and exchanges if needed)\n await this.getAccessToken();\n\n // Create OAuth2Client with service account credentials\n const auth = this.toAuth(accountId);\n\n // Inject authContext and logger into extra parameter\n (extra as { authContext?: AuthContext }).authContext = {\n auth, // OAuth2Client for googleapis\n accountId, // 'service-account' (fixed, not service email)\n metadata: { serviceEmail }, // Keep email for logging/reference\n };\n (extra as { logger?: unknown }).logger = this.config.logger;\n\n // Call original handler with all args\n return await originalHandler(...allArgs);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n\n // Provide specific, actionable error messages based on error type\n if (message.includes('key file not found')) {\n throw new Error(`Service account setup error: Key file '${this.keyFilePath}' not found.\\n• Set GOOGLE_SERVICE_ACCOUNT_KEY_FILE environment variable\\n• Or ensure the file path exists and is accessible`);\n }\n if (message.includes('Forbidden') || message.includes('access_denied')) {\n throw new Error(\n 'Service account permission error: The service account does not have required permissions.\\n' + '• Ensure the service account has been granted the necessary roles\\n' + '• Check that required API scopes are enabled in Google Cloud Console\\n' + '• Verify the service account is active (not disabled)'\n );\n }\n if (message.includes('invalid_grant') || message.includes('JWT')) {\n throw new Error('Service account authentication error: Invalid credentials or expired tokens.\\n' + '• Verify your service account key file is valid and not expired\\n' + '• Check that the service account email and project match your GCP setup\\n' + '• Try regenerating the key file in Google Cloud Console');\n }\n if (message.includes('Network error') || message.includes('fetch')) {\n throw new Error('Service account connection error: Unable to reach Google authentication services.\\n' + '• Check your internet connection\\n' + '• Verify firewall/proxy settings allow HTTPS to oauth2.googleapis.com\\n' + '• Try again in a few moments (may be temporary service issue)');\n }\n // Generic fallback with original error\n throw new Error(`Service account authentication failed: ${message}`);\n }\n };\n\n return {\n ...module,\n handler: wrappedHandler,\n } as T;\n };\n\n return {\n // Use structural constraints to avoid contravariance check on handler type.\n // wrapAtPosition is now generic and returns T directly.\n withToolAuth: <T extends { name: string; config: unknown; handler: unknown }>(module: T) => wrapAtPosition(module, 1),\n withResourceAuth: <T extends { name: string; template?: unknown; config?: unknown; handler: unknown }>(module: T) => wrapAtPosition(module, 2),\n withPromptAuth: <T extends { name: string; config: unknown; handler: unknown }>(module: T) => wrapAtPosition(module, 0),\n };\n }\n}\n"],"names":["promises","fs","OAuth2Client","importPKCS8","SignJWT","ServiceAccountProvider","loadKeyFile","keyData","fileContent","readFile","keyFilePath","JSON","parse","parseError","Error","message","String","validateKeyFile","error","code","data","obj","type","requiredFields","missingFields","filter","field","length","join","privateKey","private_key","includes","generateJWT","now","Math","floor","Date","jwt","iss","client_email","scope","scopes","aud","exp","iat","setProtectedHeader","alg","typ","sign","exchangeJWT","tokenEndpoint","response","fetch","method","headers","body","URLSearchParams","grant_type","assertion","ok","errorText","text","errorMessage","errorJson","error_description","status","tokenData","json","expiry","expires_in","token","access_token","TypeError","getAccessToken","_accountId","cachedToken","toAuth","accountId","undefined","client","getRequestMetadataAsync","_url","credentials","token_type","Headers","set","config","logger","debug","getUserEmail","authMiddleware","wrapAtPosition","module","extraPosition","originalHandler","handler","wrappedHandler","allArgs","extra","serviceEmail","auth","authContext","metadata","withToolAuth","withResourceAuth","withPromptAuth"],"mappings":"AAAA,SAASA,YAAYC,EAAE,QAAQ,KAAK;AACpC,SAASC,YAAY,QAAQ,sBAAsB;AACnD,SAASC,WAAW,EAAEC,OAAO,QAAQ,OAAO;AAyC5C;;;;;;;;;;;;;;;;;;;;;;CAsBC,GACD,OAAO,MAAMC;IAaX;;;GAGC,GACD,MAAcC,cAA0C;QACtD,2CAA2C;QAC3C,IAAI,IAAI,CAACC,OAAO,EAAE;YAChB,OAAO,IAAI,CAACA,OAAO;QACrB;QAEA,IAAI;YACF,0BAA0B;YAC1B,MAAMC,cAAc,MAAMP,GAAGQ,QAAQ,CAAC,IAAI,CAACC,WAAW,EAAE;YAExD,aAAa;YACb,IAAIH;YACJ,IAAI;gBACFA,UAAUI,KAAKC,KAAK,CAACJ;YACvB,EAAE,OAAOK,YAAY;gBACnB,MAAM,IAAIC,MAAM,CAAC,kDAAkD,EAAE,IAAI,CAACJ,WAAW,CAAC,EAAE,CAAC,GAAG,CAAC,OAAO,EAAEG,sBAAsBC,QAAQD,WAAWE,OAAO,GAAGC,OAAOH,aAAa;YAC/K;YAEA,qBAAqB;YACrB,IAAI,CAACN,OAAO,GAAG,IAAI,CAACU,eAAe,CAACV;YACpC,OAAO,IAAI,CAACA,OAAO;QACrB,EAAE,OAAOW,OAAO;YACd,wBAAwB;YAC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AIjB,MAAM,wFAAwF,uCAAuC,4EAA4E;oBAC7N;oBACA,uCAAuC;oBACvC,MAAM,IAAIA,MAAM,CAAC,uCAAuC,EAAEC,SAAS;gBACrE;YACF;YAEA,OAAO;gBACL,GAAG6E,MAAM;gBACTG,SAASC;YACX;QACF;QAEA,OAAO;YACL,4EAA4E;YAC5E,wDAAwD;YACxDO,cAAc,CAAgEX,SAAcD,eAAeC,QAAQ;YACnHY,kBAAkB,CAAqFZ,SAAcD,eAAeC,QAAQ;YAC5Ia,gBAAgB,CAAgEb,SAAcD,eAAeC,QAAQ;QACvH;IACF;IAhXA,YAAYN,MAA4B,CAAE;QACxC,IAAI,CAACA,MAAM,GAAGA;QACd,IAAI,CAAC5E,WAAW,GAAG4E,OAAO5E,WAAW;QACrC,IAAI,CAAC+B,MAAM,GAAG6C,OAAO7C,MAAM;IAC7B;AA6WF"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/Projects/mcp-z/oauth-google/src/providers/service-account.ts"],"sourcesContent":["import { promises as fs } from 'fs';\nimport { OAuth2Client } from 'google-auth-library';\nimport { importPKCS8, SignJWT } from 'jose';\nimport type { AuthContext, EnrichedExtra, Logger, OAuth2TokenStorageProvider } from '../types.ts';\n\n/**\n * Service Account Key File Structure\n * Standard Google Cloud service account JSON key format\n */\ninterface ServiceAccountKey {\n type: 'service_account';\n project_id: string;\n private_key_id: string;\n private_key: string;\n client_email: string;\n client_id: string;\n auth_uri: string;\n token_uri: string;\n auth_provider_x509_cert_url?: string;\n client_x509_cert_url?: string;\n}\n\n/**\n * Service Account Provider Configuration\n */\nexport interface ServiceAccountConfig {\n /** Path to Google Cloud service account JSON key file */\n keyFilePath: string;\n /** OAuth scopes to request (e.g., ['https://www.googleapis.com/auth/gmail.readonly']) */\n scopes: string[];\n /** Logger for auth operations */\n logger: Logger;\n}\n\n/**\n * Token Exchange Response from Google OAuth endpoint\n */\ninterface TokenResponse {\n access_token: string;\n expires_in: number;\n token_type: string;\n}\n\n/**\n * ServiceAccountProvider implements OAuth2TokenStorageProvider using Google Service Accounts\n * with JWT-based (2-legged OAuth) authentication.\n *\n * This provider:\n * - Loads service account key file from disk\n * - Generates self-signed JWTs using RS256 algorithm\n * - Exchanges JWTs for access tokens at Google's token endpoint\n * - Does NOT store tokens (regenerates on each request)\n * - Provides single static identity (no account management)\n *\n * @example\n * ```typescript\n * const provider = new ServiceAccountProvider({\n * keyFilePath: '/path/to/service-account-key.json',\n * scopes: ['https://www.googleapis.com/auth/drive.readonly'],\n * });\n *\n * // Get authenticated OAuth2Client for googleapis\n * const auth = provider.toAuth('default');\n * const drive = google.drive({ version: 'v3', auth });\n * ```\n */\nexport class ServiceAccountProvider implements OAuth2TokenStorageProvider {\n private config: ServiceAccountConfig;\n private keyFilePath: string;\n private scopes: string[];\n private keyData?: ServiceAccountKey;\n private cachedToken?: { token: string; expiry: number };\n\n constructor(config: ServiceAccountConfig) {\n this.config = config;\n this.keyFilePath = config.keyFilePath;\n this.scopes = config.scopes;\n }\n\n /**\n * Load and parse service account key file from disk\n * Validates structure and caches for subsequent calls\n */\n private async loadKeyFile(): Promise<ServiceAccountKey> {\n // Return cached key data if already loaded\n if (this.keyData) {\n return this.keyData;\n }\n\n try {\n // Read key file from disk\n const fileContent = await fs.readFile(this.keyFilePath, 'utf-8');\n\n // Parse JSON\n let keyData: unknown;\n try {\n keyData = JSON.parse(fileContent);\n } catch (parseError) {\n throw new Error(`Failed to parse service account key file as JSON: ${this.keyFilePath}\\n` + `Error: ${parseError instanceof Error ? parseError.message : String(parseError)}`);\n }\n\n // Validate structure\n this.keyData = this.validateKeyFile(keyData);\n return this.keyData;\n } catch (error) {\n // Handle file not found\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new Error(`Service account key file not found: ${this.keyFilePath}\\nMake sure GOOGLE_SERVICE_ACCOUNT_KEY_FILE points to a valid file path.`);\n }\n\n // Handle permission errors\n if ((error as NodeJS.ErrnoException).code === 'EACCES') {\n throw new Error(`Permission denied reading service account key file: ${this.keyFilePath}\\nCheck file permissions (should be readable by current user).`);\n }\n\n // Re-throw other errors\n throw error;\n }\n }\n\n /**\n * Validate service account key file structure\n * Ensures all required fields are present and correctly typed\n */\n private validateKeyFile(data: unknown): ServiceAccountKey {\n if (!data || typeof data !== 'object') {\n throw new Error('Service account key file must contain a JSON object');\n }\n\n const obj = data as Record<string, unknown>;\n\n // Validate type field\n if (obj.type !== 'service_account') {\n throw new Error(`Invalid service account key file: Expected type \"service_account\", got \"${obj.type}\"\\nMake sure you downloaded a service account key, not an OAuth client credential.`);\n }\n\n // Validate required string fields\n const requiredFields: Array<keyof ServiceAccountKey> = ['project_id', 'private_key_id', 'private_key', 'client_email', 'client_id', 'auth_uri', 'token_uri'];\n\n const missingFields = requiredFields.filter((field) => typeof obj[field] !== 'string' || !obj[field]);\n\n if (missingFields.length > 0) {\n throw new Error(`Service account key file is missing required fields: ${missingFields.join(', ')}\\nMake sure you downloaded a complete service account key file from Google Cloud Console.`);\n }\n\n // Validate private key format\n const privateKey = obj.private_key as string;\n if (!privateKey.includes('BEGIN PRIVATE KEY') || !privateKey.includes('END PRIVATE KEY')) {\n throw new Error('Service account private_key field does not contain a valid PEM-formatted key.\\n' + 'Expected format: -----BEGIN PRIVATE KEY-----...-----END PRIVATE KEY-----');\n }\n\n return obj as unknown as ServiceAccountKey;\n }\n\n /**\n * Generate signed JWT (JSON Web Token) for service account authentication\n * Uses RS256 algorithm with private key from key file\n */\n private async generateJWT(): Promise<string> {\n const keyData = await this.loadKeyFile();\n\n // Import private key using jose\n const privateKey = await importPKCS8(keyData.private_key, 'RS256');\n\n // Current time\n const now = Math.floor(Date.now() / 1000);\n\n // Create JWT with required claims for Google OAuth\n const jwt = await new SignJWT({\n iss: keyData.client_email, // Issuer: service account email\n scope: this.scopes.join(' '), // Scopes: space-separated\n aud: 'https://oauth2.googleapis.com/token', // Audience: token endpoint\n exp: now + 3600, // Expiration: 1 hour from now\n iat: now, // Issued at: current time\n })\n .setProtectedHeader({ alg: 'RS256', typ: 'JWT' })\n .sign(privateKey);\n\n return jwt;\n }\n\n /**\n * Exchange signed JWT for access token at Google OAuth endpoint\n * POST to https://oauth2.googleapis.com/token with grant_type=jwt-bearer\n */\n private async exchangeJWT(jwt: string): Promise<{ token: string; expiry: number }> {\n const tokenEndpoint = 'https://oauth2.googleapis.com/token';\n\n try {\n const response = await fetch(tokenEndpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: new URLSearchParams({\n grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',\n assertion: jwt,\n }),\n });\n\n // Handle non-2xx responses\n if (!response.ok) {\n const errorText = await response.text();\n let errorMessage: string;\n\n try {\n const errorJson = JSON.parse(errorText);\n errorMessage = errorJson.error_description || errorJson.error || errorText;\n } catch {\n errorMessage = errorText;\n }\n\n // 400: Invalid JWT (malformed claims, expired, etc.)\n if (response.status === 400) {\n throw new Error(`Invalid service account JWT: ${errorMessage}\\nThis usually means the JWT claims are malformed or the key file is invalid.`);\n }\n\n // 401: Unauthorized (revoked service account, wrong scopes, etc.)\n if (response.status === 401) {\n throw new Error(`Service account authentication failed: ${errorMessage}\\nThe service account may have been disabled or deleted. Check Google Cloud Console.`);\n }\n\n // Other errors\n throw new Error(`Token exchange failed (HTTP ${response.status}): ${errorMessage}`);\n }\n\n // Parse successful response\n const tokenData = (await response.json()) as TokenResponse;\n\n // Calculate expiry timestamp (token expires in ~1 hour)\n const expiry = Date.now() + (tokenData.expires_in - 60) * 1000; // Subtract 60s for safety margin\n\n return {\n token: tokenData.access_token,\n expiry,\n };\n } catch (error) {\n // Network errors\n if (error instanceof TypeError && error.message.includes('fetch')) {\n throw new Error('Network error connecting to Google OAuth endpoint. Check internet connection.');\n }\n\n // Re-throw other errors\n throw error;\n }\n }\n\n /**\n * Get access token for Google APIs\n * Generates fresh JWT and exchanges for access token on each call\n *\n * Note: accountId parameter is ignored for service accounts (service account is single static identity)\n */\n async getAccessToken(_accountId?: string): Promise<string> {\n // Check if we have a valid cached token (optional optimization)\n if (this.cachedToken && this.cachedToken.expiry > Date.now()) {\n return this.cachedToken.token;\n }\n\n try {\n // Generate JWT\n const jwt = await this.generateJWT();\n\n // Exchange for access token\n const { token, expiry } = await this.exchangeJWT(jwt);\n\n // Cache token for subsequent calls (optional optimization)\n this.cachedToken = { token, expiry };\n\n return token;\n } catch (error) {\n // Add context to errors\n throw new Error(`Failed to get service account access token: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n /**\n * Get OAuth2Client with service account credentials for googleapis\n * This is the CRITICAL method that servers use to get authenticated API clients\n *\n * Service account ONLY works with accountId='service-account' (single static identity)\n *\n @param accountId - Account identifier (must be 'service-account' or undefined)\n * @returns OAuth2Client instance with access token credentials set\n */\n toAuth(accountId?: string): OAuth2Client {\n // Service account ONLY works with 'service-account' account ID\n if (accountId !== undefined && accountId !== 'service-account') {\n throw new Error(`ServiceAccountProvider only supports accountId='service-account', got '${accountId}'. Service account uses a single static identity pattern.`);\n }\n\n // Create OAuth2Client instance (no client ID/secret needed for service accounts)\n const client = new OAuth2Client();\n\n // Override getRequestMetadataAsync to provide authentication headers for each request\n // This is the method googleapis calls to get auth headers - can be async and fetch tokens on-demand\n (\n client as OAuth2Client & {\n getRequestMetadataAsync: (url?: string) => Promise<{ headers: Headers | Map<string, string> }>;\n }\n ).getRequestMetadataAsync = async (_url?: string) => {\n try {\n // Get fresh access token (can be async, will trigger JWT generation if needed)\n const token = await this.getAccessToken();\n\n // Update client credentials for consistency (other googleapis methods might check these)\n client.credentials = {\n access_token: token,\n token_type: 'Bearer',\n };\n\n // Return headers as Headers instance for proper TypeScript types\n const headers = new Headers();\n headers.set('authorization', `Bearer ${token}`);\n return { headers };\n } catch (error) {\n this.config.logger?.error('Failed to get service account access token for API request', { error });\n throw error;\n }\n };\n\n // Override getAccessToken to support googleapis client API and direct token access\n client.getAccessToken = async () => {\n try {\n const token = await this.getAccessToken();\n return { token };\n } catch (error) {\n this.config.logger?.error('Failed to get service account access token', { error });\n throw error;\n }\n };\n\n this.config.logger?.debug(`ServiceAccountProvider: OAuth2Client created for ${accountId}`);\n return client;\n }\n\n /**\n * Get service account email address\n * Used for account registration and display\n *\n * Note: accountId parameter is ignored for service accounts\n * @returns Service account email from key file (e.g., \"service-account@project.iam.gserviceaccount.com\")\n */\n async getUserEmail(_accountId?: string): Promise<string> {\n const keyData = await this.loadKeyFile();\n return keyData.client_email;\n }\n\n /**\n * Create middleware wrapper for single-user authentication\n * This is the CRITICAL method that integrates service account auth into MCP servers\n *\n * Middleware wraps tool, resource, and prompt handlers and injects authContext into extra parameter.\n * Handlers receive OAuth2Client via extra.authContext.auth for API calls.\n *\n * @returns Object with withToolAuth, withResourceAuth, withPromptAuth methods\n *\n * @example\n * ```typescript\n * // Server registration\n * const authMiddleware = provider.authMiddleware();\n * const tools = toolFactories.map(f => f()).map(authMiddleware.withToolAuth);\n * const resources = resourceFactories.map(f => f()).map(authMiddleware.withResourceAuth);\n * const prompts = promptFactories.map(f => f()).map(authMiddleware.withPromptAuth);\n *\n * // Tool handler receives auth\n * async function handler({ id }: In, extra: EnrichedExtra) {\n * // extra.authContext.auth is OAuth2Client (from middleware)\n * const gmail = google.gmail({ version: 'v1', auth: extra.authContext.auth });\n * }\n * ```\n */\n authMiddleware() {\n // Shared wrapper logic - extracts extra parameter from specified position\n // Generic T captures the actual module type; handler is cast from unknown to callable\n const wrapAtPosition = <T extends { name: string; handler: unknown; [key: string]: unknown }>(module: T, extraPosition: number): T => {\n const originalHandler = module.handler as (...args: unknown[]) => Promise<unknown>;\n\n const wrappedHandler = async (...allArgs: unknown[]) => {\n // Extract extra from the correct position\n const extra = allArgs[extraPosition] as EnrichedExtra;\n\n try {\n // Use fixed accountId for storage isolation (like device-code pattern)\n const accountId = 'service-account';\n\n // Get service account email for logging/display\n const serviceEmail = await this.getUserEmail();\n\n // Get access token (generates JWT and exchanges if needed)\n await this.getAccessToken();\n\n // Create OAuth2Client with service account credentials\n const auth = this.toAuth(accountId);\n\n // Inject authContext and logger into extra parameter\n (extra as { authContext?: AuthContext }).authContext = {\n auth, // OAuth2Client for googleapis\n accountId, // 'service-account' (fixed, not service email)\n metadata: { serviceEmail }, // Keep email for logging/reference\n };\n (extra as { logger?: unknown }).logger = this.config.logger;\n\n // Call original handler with all args\n return await originalHandler(...allArgs);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n\n // Provide specific, actionable error messages based on error type\n if (message.includes('key file not found')) {\n throw new Error(`Service account setup error: Key file '${this.keyFilePath}' not found.\\n• Set GOOGLE_SERVICE_ACCOUNT_KEY_FILE environment variable\\n• Or ensure the file path exists and is accessible`);\n }\n if (message.includes('Forbidden') || message.includes('access_denied')) {\n throw new Error(\n 'Service account permission error: The service account does not have required permissions.\\n' + '• Ensure the service account has been granted the necessary roles\\n' + '• Check that required API scopes are enabled in Google Cloud Console\\n' + '• Verify the service account is active (not disabled)'\n );\n }\n if (message.includes('invalid_grant') || message.includes('JWT')) {\n throw new Error('Service account authentication error: Invalid credentials or expired tokens.\\n' + '• Verify your service account key file is valid and not expired\\n' + '• Check that the service account email and project match your GCP setup\\n' + '• Try regenerating the key file in Google Cloud Console');\n }\n if (message.includes('Network error') || message.includes('fetch')) {\n throw new Error('Service account connection error: Unable to reach Google authentication services.\\n' + '• Check your internet connection\\n' + '• Verify firewall/proxy settings allow HTTPS to oauth2.googleapis.com\\n' + '• Try again in a few moments (may be temporary service issue)');\n }\n // Generic fallback with original error\n throw new Error(`Service account authentication failed: ${message}`);\n }\n };\n\n return {\n ...module,\n handler: wrappedHandler,\n } as T;\n };\n\n return {\n // Use structural constraints to avoid contravariance check on handler type.\n // wrapAtPosition is now generic and returns T directly.\n withToolAuth: <T extends { name: string; config: unknown; handler: unknown }>(module: T) => wrapAtPosition(module, 1),\n withResourceAuth: <T extends { name: string; template?: unknown; config?: unknown; handler: unknown }>(module: T) => wrapAtPosition(module, 2),\n withPromptAuth: <T extends { name: string; config: unknown; handler: unknown }>(module: T) => wrapAtPosition(module, 0),\n };\n }\n}\n"],"names":["promises","fs","OAuth2Client","importPKCS8","SignJWT","ServiceAccountProvider","loadKeyFile","keyData","fileContent","readFile","keyFilePath","JSON","parse","parseError","Error","message","String","validateKeyFile","error","code","data","obj","type","requiredFields","missingFields","filter","field","length","join","privateKey","private_key","includes","generateJWT","now","Math","floor","Date","jwt","iss","client_email","scope","scopes","aud","exp","iat","setProtectedHeader","alg","typ","sign","exchangeJWT","tokenEndpoint","response","fetch","method","headers","body","URLSearchParams","grant_type","assertion","ok","errorText","text","errorMessage","errorJson","error_description","status","tokenData","json","expiry","expires_in","token","access_token","TypeError","getAccessToken","_accountId","cachedToken","toAuth","accountId","undefined","client","getRequestMetadataAsync","_url","credentials","token_type","Headers","set","config","logger","debug","getUserEmail","authMiddleware","wrapAtPosition","module","extraPosition","originalHandler","handler","wrappedHandler","allArgs","extra","serviceEmail","auth","authContext","metadata","withToolAuth","withResourceAuth","withPromptAuth"],"mappings":"AAAA,SAASA,YAAYC,EAAE,QAAQ,KAAK;AACpC,SAASC,YAAY,QAAQ,sBAAsB;AACnD,SAASC,WAAW,EAAEC,OAAO,QAAQ,OAAO;AAyC5C;;;;;;;;;;;;;;;;;;;;;;CAsBC,GACD,OAAO,MAAMC;IAaX;;;GAGC,GACD,MAAcC,cAA0C;QACtD,2CAA2C;QAC3C,IAAI,IAAI,CAACC,OAAO,EAAE;YAChB,OAAO,IAAI,CAACA,OAAO;QACrB;QAEA,IAAI;YACF,0BAA0B;YAC1B,MAAMC,cAAc,MAAMP,GAAGQ,QAAQ,CAAC,IAAI,CAACC,WAAW,EAAE;YAExD,aAAa;YACb,IAAIH;YACJ,IAAI;gBACFA,UAAUI,KAAKC,KAAK,CAACJ;YACvB,EAAE,OAAOK,YAAY;gBACnB,MAAM,IAAIC,MAAM,CAAC,kDAAkD,EAAE,IAAI,CAACJ,WAAW,CAAC,EAAE,CAAC,GAAG,CAAC,OAAO,EAAEG,sBAAsBC,QAAQD,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B,QAAQgB,QAAQ,CAAC,QAAQ;wBAChE,MAAM,IAAIjB,MAAM,mFAAmF,sEAAsE,8EAA8E;oBACzP;oBACA,IAAIC,QAAQgB,QAAQ,CAAC,oBAAoBhB,QAAQgB,QAAQ,CAAC,UAAU;wBAClE,MAAM,IAAIjB,MAAM,wFAAwF,uCAAuC,4EAA4E;oBAC7N;oBACA,uCAAuC;oBACvC,MAAM,IAAIA,MAAM,CAAC,uCAAuC,EAAEC,SAAS;gBACrE;YACF;YAEA,OAAO;gBACL,GAAG6E,MAAM;gBACTG,SAASC;YACX;QACF;QAEA,OAAO;YACL,4EAA4E;YAC5E,wDAAwD;YACxDO,cAAc,CAAgEX,SAAcD,eAAeC,QAAQ;YACnHY,kBAAkB,CAAqFZ,SAAcD,eAAeC,QAAQ;YAC5Ia,gBAAgB,CAAgEb,SAAcD,eAAeC,QAAQ;QACvH;IACF;IAhXA,YAAYN,MAA4B,CAAE;QACxC,IAAI,CAACA,MAAM,GAAGA;QACd,IAAI,CAAC5E,WAAW,GAAG4E,OAAO5E,WAAW;QACrC,IAAI,CAAC+B,MAAM,GAAG6C,OAAO7C,MAAM;IAC7B;AA6WF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/Projects/
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/Projects/mcp-z/oauth-google/src/schemas/index.ts"],"sourcesContent":["import { z } from 'zod';\n\nexport const AuthRequiredBranchSchema = z.object({\n type: z.literal('auth_required'),\n provider: z.string(),\n message: z.string(),\n url: z.string().optional(),\n});\nexport type AuthRequiredBranch = z.infer<typeof AuthRequiredBranchSchema>;\n\nexport const AuthRequiredSchema = z\n .object({\n type: z.literal('auth_required'),\n provider: z.string().describe('OAuth provider name (e.g., \"google\")'),\n message: z.string().describe('Human-readable message explaining why auth is needed'),\n url: z.string().url().describe('Authentication URL to open in browser'),\n flow: z.string().optional().describe('Authentication flow type (e.g., \"auth_url\", \"device_code\")'),\n instructions: z.string().describe('Clear instructions for the user'),\n user_code: z.string().optional().describe('Code user must enter at verification URL (device flows only)'),\n expires_in: z.number().optional().describe('Seconds until code expires (device flows only)'),\n accountId: z.string().optional().describe('Account identifier (email) that requires authentication'),\n })\n .describe('Authentication required with clear actionable instructions for user');\n\nexport type AuthRequired = z.infer<typeof AuthRequiredSchema>;\n"],"names":["z","AuthRequiredBranchSchema","object","type","literal","provider","string","message","url","optional","AuthRequiredSchema","describe","flow","instructions","user_code","expires_in","number","accountId"],"mappings":"AAAA,SAASA,CAAC,QAAQ,MAAM;AAExB,OAAO,MAAMC,2BAA2BD,EAAEE,MAAM,CAAC;IAC/CC,MAAMH,EAAEI,OAAO,CAAC;IAChBC,UAAUL,EAAEM,MAAM;IAClBC,SAASP,EAAEM,MAAM;IACjBE,KAAKR,EAAEM,MAAM,GAAGG,QAAQ;AAC1B,GAAG;AAGH,OAAO,MAAMC,qBAAqBV,EAC/BE,MAAM,CAAC;IACNC,MAAMH,EAAEI,OAAO,CAAC;IAChBC,UAAUL,EAAEM,MAAM,GAAGK,QAAQ,CAAC;IAC9BJ,SAASP,EAAEM,MAAM,GAAGK,QAAQ,CAAC;IAC7BH,KAAKR,EAAEM,MAAM,GAAGE,GAAG,GAAGG,QAAQ,CAAC;IAC/BC,MAAMZ,EAAEM,MAAM,GAAGG,QAAQ,GAAGE,QAAQ,CAAC;IACrCE,cAAcb,EAAEM,MAAM,GAAGK,QAAQ,CAAC;IAClCG,WAAWd,EAAEM,MAAM,GAAGG,QAAQ,GAAGE,QAAQ,CAAC;IAC1CI,YAAYf,EAAEgB,MAAM,GAAGP,QAAQ,GAAGE,QAAQ,CAAC;IAC3CM,WAAWjB,EAAEM,MAAM,GAAGG,QAAQ,GAAGE,QAAQ,CAAC;AAC5C,GACCA,QAAQ,CAAC,uEAAuE"}
|
|
@@ -9,8 +9,12 @@ import type { DcrConfig, OAuthConfig } from '../types.js';
|
|
|
9
9
|
export type { DcrConfig, OAuthConfig };
|
|
10
10
|
/**
|
|
11
11
|
* Transport type for MCP servers
|
|
12
|
+
*
|
|
13
|
+
* @typedef {('stdio' | 'http')} TransportType
|
|
14
|
+
* @property {'stdio'} stdio - Standard input/output transport for CLI applications
|
|
15
|
+
* @property {'http'} http - HTTP transport for web-based applications
|
|
12
16
|
*/
|
|
13
|
-
type TransportType = 'stdio' | 'http';
|
|
17
|
+
export type TransportType = 'stdio' | 'http';
|
|
14
18
|
/**
|
|
15
19
|
* Parse Google OAuth configuration from CLI arguments and environment variables.
|
|
16
20
|
*
|
|
@@ -34,6 +38,7 @@ type TransportType = 'stdio' | 'http';
|
|
|
34
38
|
* @param args - CLI arguments array (typically process.argv)
|
|
35
39
|
* @param env - Environment variables object (typically process.env)
|
|
36
40
|
* @param transport - Optional transport type. If 'stdio' and auth mode is 'dcr', throws an error.
|
|
41
|
+
* See {@link TransportType} for valid values.
|
|
37
42
|
* @returns Parsed Google OAuth configuration
|
|
38
43
|
* @throws Error if required environment variables are missing, values are invalid, or DCR is used with stdio transport
|
|
39
44
|
*
|
package/dist/esm/setup/config.js
CHANGED
|
@@ -50,6 +50,7 @@ import { parseArgs } from 'util';
|
|
|
50
50
|
* @param args - CLI arguments array (typically process.argv)
|
|
51
51
|
* @param env - Environment variables object (typically process.env)
|
|
52
52
|
* @param transport - Optional transport type. If 'stdio' and auth mode is 'dcr', throws an error.
|
|
53
|
+
* See {@link TransportType} for valid values.
|
|
53
54
|
* @returns Parsed Google OAuth configuration
|
|
54
55
|
* @throws Error if required environment variables are missing, values are invalid, or DCR is used with stdio transport
|
|
55
56
|
*
|
|
@@ -126,6 +127,9 @@ import { parseArgs } from 'util';
|
|
|
126
127
|
const cliRedirectUri = typeof values['redirect-uri'] === 'string' ? values['redirect-uri'] : undefined;
|
|
127
128
|
const envRedirectUri = env.REDIRECT_URI;
|
|
128
129
|
const redirectUri = cliRedirectUri !== null && cliRedirectUri !== void 0 ? cliRedirectUri : envRedirectUri;
|
|
130
|
+
if (redirectUri && transport === 'stdio') {
|
|
131
|
+
throw new Error('REDIRECT_URI requires HTTP transport. The OAuth callback must be served over HTTP.');
|
|
132
|
+
}
|
|
129
133
|
const clientId = requiredEnv('GOOGLE_CLIENT_ID');
|
|
130
134
|
const clientSecret = env.GOOGLE_CLIENT_SECRET;
|
|
131
135
|
let serviceAccountKeyFile;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/Projects/ai/mcp-z/oauth/oauth-google/src/setup/config.ts"],"sourcesContent":["/**\n * Google OAuth configuration parsing from CLI arguments and environment variables.\n *\n * This module provides utilities to parse Google OAuth configuration from\n * CLI arguments and environment variables, following the same pattern as @mcp-z/server's\n * parseConfig().\n */\n\nimport { resolve } from 'path';\nimport { parseArgs } from 'util';\nimport type { DcrConfig, OAuthConfig } from '../types.ts';\n\n// Re-export for direct imports from config.ts\nexport type { DcrConfig, OAuthConfig };\n\n/**\n * auth mode type (from OAuthConfig)\n */\ntype AuthMode = 'loopback-oauth' | 'service-account' | 'dcr';\n\n/**\n * Parse auth mode string into auth mode.\n *\n * @param value - Auth mode string ('loopback-oauth', 'service-account', or 'dcr')\n * @returns Parsed auth mode\n * @throws Error if value is invalid\n *\n * @example Valid formats\n * ```typescript\n * parseAuthMode('loopback-oauth') // { auth: 'loopback-oauth' }\n * parseAuthMode('service-account') // { auth: 'service-account' }\n * parseAuthMode('dcr') // { auth: 'dcr' }\n * ```\n */\nfunction parseAuthMode(value: string): {\n auth: AuthMode;\n} {\n if (value !== 'loopback-oauth' && value !== 'service-account' && value !== 'dcr') {\n throw new Error(`Invalid --auth value: \"${value}\". Valid values: loopback-oauth, service-account, dcr`);\n }\n\n return {\n auth: value as AuthMode,\n };\n}\n\n/**\n * Transport type for MCP servers\n */\ntype TransportType = 'stdio' | 'http';\n\n/**\n * Parse Google OAuth configuration from CLI arguments and environment variables.\n *\n * CLI Arguments:\n * - --auth: Auth mode ('loopback-oauth' | 'service-account' | 'dcr')\n * - Default: 'loopback-oauth' (if flag is omitted)\n * - --headless: Disable browser opening for OAuth flow (default: false, true in test env)\n * - --redirect-uri: Override OAuth redirect URI (default: ephemeral loopback)\n * - --service-account-key-file: Service account key file path (required for service-account mode)\n *\n * Required environment variables:\n * - GOOGLE_CLIENT_ID: OAuth 2.0 client ID from Google Cloud Console\n *\n * Optional environment variables:\n * - GOOGLE_CLIENT_SECRET: OAuth 2.0 client secret (optional for public clients)\n * - AUTH_MODE: Auth mode (same format as --auth flag)\n * - HEADLESS: Headless mode flag ('true' to enable)\n * - REDIRECT_URI: OAuth redirect URI (overridden by --redirect-uri CLI flag)\n * - GOOGLE_SERVICE_ACCOUNT_KEY_FILE: Service account key file (for service-account mode)\n *\n * @param args - CLI arguments array (typically process.argv)\n * @param env - Environment variables object (typically process.env)\n * @param transport - Optional transport type. If 'stdio' and auth mode is 'dcr', throws an error.\n * @returns Parsed Google OAuth configuration\n * @throws Error if required environment variables are missing, values are invalid, or DCR is used with stdio transport\n *\n * @example Default mode (no flags)\n * ```typescript\n * const config = parseConfig(process.argv, process.env);\n * // { auth: 'loopback-oauth' }\n * ```\n *\n * @example Override auth mode\n * ```typescript\n * parseConfig(['--auth=loopback-oauth'], process.env);\n * parseConfig(['--auth=service-account'], process.env);\n * parseConfig(['--auth=dcr'], process.env);\n * ```\n *\n * @example With transport validation\n * ```typescript\n * parseConfig(['--auth=dcr'], process.env, 'http'); // OK\n * parseConfig(['--auth=dcr'], process.env, 'stdio'); // Throws error\n * ```\n *\n * Valid auth modes:\n * - loopback-oauth (default)\n * - service-account\n * - dcr (HTTP transport only)\n */\nexport function parseConfig(args: string[], env: Record<string, string | undefined>, transport?: TransportType): OAuthConfig {\n function requiredEnv(key: string): string {\n const value = env[key];\n if (!value) {\n throw new Error(`Environment variable ${key} is required for Google OAuth`);\n }\n return value;\n }\n\n // Parse CLI arguments\n const { values } = parseArgs({\n args,\n options: {\n auth: { type: 'string' },\n headless: { type: 'boolean' },\n 'redirect-uri': { type: 'string' },\n 'service-account-key-file': { type: 'string' },\n },\n strict: false, // Allow other arguments\n allowPositionals: true,\n });\n\n const authArg = typeof values.auth === 'string' ? values.auth : undefined;\n const envAuthMode = env.AUTH_MODE;\n const mode = authArg || envAuthMode;\n\n let auth: AuthMode;\n\n if (mode) {\n const parsed = parseAuthMode(mode);\n auth = parsed.auth;\n } else {\n // DEFAULT: No flags provided, use loopback-oauth\n auth = 'loopback-oauth';\n }\n\n // Validate: DCR only works with HTTP transport\n if (auth === 'dcr' && transport === 'stdio') {\n throw new Error('DCR authentication mode requires HTTP transport. DCR is not supported with stdio transport.');\n }\n\n const cliHeadless = typeof values.headless === 'boolean' ? values.headless : undefined;\n const envHeadless = env.HEADLESS === 'true' ? true : env.HEADLESS === 'false' ? false : undefined;\n const headless = cliHeadless ?? envHeadless ?? false;\n\n const cliRedirectUri = typeof values['redirect-uri'] === 'string' ? values['redirect-uri'] : undefined;\n const envRedirectUri = env.REDIRECT_URI;\n const redirectUri = cliRedirectUri ?? envRedirectUri;\n\n const clientId = requiredEnv('GOOGLE_CLIENT_ID');\n const clientSecret = env.GOOGLE_CLIENT_SECRET;\n\n let serviceAccountKeyFile: string | undefined;\n if (auth === 'service-account') {\n const cliKeyFile = typeof values['service-account-key-file'] === 'string' ? values['service-account-key-file'] : undefined;\n serviceAccountKeyFile = cliKeyFile ?? env.GOOGLE_SERVICE_ACCOUNT_KEY_FILE;\n\n if (!serviceAccountKeyFile) {\n throw new Error('GOOGLE_SERVICE_ACCOUNT_KEY_FILE environment variable is required when using service account authentication. ' + 'Example: export GOOGLE_SERVICE_ACCOUNT_KEY_FILE=./service-account.json');\n }\n\n // Resolve relative paths now since cwd can change during execution\n serviceAccountKeyFile = resolve(serviceAccountKeyFile);\n }\n\n return {\n clientId,\n ...(clientSecret && { clientSecret }),\n auth,\n headless,\n ...(redirectUri && { redirectUri }),\n ...(serviceAccountKeyFile && { serviceAccountKeyFile }),\n };\n}\n\n/**\n * Build production configuration from process globals.\n * Entry point for production server.\n */\nexport function createConfig(): OAuthConfig {\n return parseConfig(process.argv, process.env);\n}\n\n/**\n * Parse DCR configuration from CLI arguments and environment variables.\n *\n * CLI Arguments:\n * - --dcr-mode: DCR mode ('self-hosted' | 'external')\n * - Default: 'self-hosted' (if flag is omitted)\n * - --dcr-verify-url: External verification endpoint URL (required for external mode)\n * - --dcr-store-uri: DCR client storage URI (required for self-hosted mode)\n *\n * Required environment variables:\n * - GOOGLE_CLIENT_ID: OAuth 2.0 client ID from Google Cloud Console\n *\n * Optional environment variables:\n * - GOOGLE_CLIENT_SECRET: OAuth 2.0 client secret (optional for public clients)\n * - DCR_MODE: DCR mode (same format as --dcr-mode flag)\n * - DCR_VERIFY_URL: External verification URL (same as --dcr-verify-url flag)\n * - DCR_STORE_URI: DCR storage URI (same as --dcr-store-uri flag)\n *\n * @param args - CLI arguments array (typically process.argv)\n * @param env - Environment variables object (typically process.env)\n * @param scope - OAuth scopes to request (space-separated)\n * @returns Parsed DCR configuration\n * @throws Error if required environment variables are missing or validation fails\n *\n * @example Self-hosted mode\n * ```typescript\n * const config = parseDcrConfig(\n * ['--dcr-mode=self-hosted', '--dcr-store-uri=file:///path/to/store.json'],\n * process.env,\n * 'https://www.googleapis.com/auth/drive.readonly'\n * );\n * ```\n *\n * @example External mode\n * ```typescript\n * const config = parseDcrConfig(\n * ['--dcr-mode=external', '--dcr-verify-url=https://auth0.example.com/verify'],\n * process.env,\n * 'https://www.googleapis.com/auth/drive.readonly'\n * );\n * ```\n */\nexport function parseDcrConfig(args: string[], env: Record<string, string | undefined>, scope: string): DcrConfig {\n function requiredEnv(key: string): string {\n const value = env[key];\n if (!value) {\n throw new Error(`Environment variable ${key} is required for DCR configuration`);\n }\n return value;\n }\n\n const { values } = parseArgs({\n args,\n options: {\n 'dcr-mode': { type: 'string' },\n 'dcr-verify-url': { type: 'string' },\n 'dcr-store-uri': { type: 'string' },\n },\n strict: false,\n allowPositionals: true,\n });\n\n const cliMode = typeof values['dcr-mode'] === 'string' ? values['dcr-mode'] : undefined;\n const envMode = env.DCR_MODE;\n const mode = cliMode || envMode || 'self-hosted';\n\n if (mode !== 'self-hosted' && mode !== 'external') {\n throw new Error(`Invalid --dcr-mode value: \"${mode}\". Valid values: self-hosted, external`);\n }\n\n const cliVerifyUrl = typeof values['dcr-verify-url'] === 'string' ? values['dcr-verify-url'] : undefined;\n const envVerifyUrl = env.DCR_VERIFY_URL;\n const verifyUrl = cliVerifyUrl || envVerifyUrl;\n\n const cliStoreUri = typeof values['dcr-store-uri'] === 'string' ? values['dcr-store-uri'] : undefined;\n const envStoreUri = env.DCR_STORE_URI;\n const storeUri = cliStoreUri || envStoreUri;\n\n if (mode === 'external' && !verifyUrl) {\n throw new Error('DCR external mode requires --dcr-verify-url or DCR_VERIFY_URL environment variable');\n }\n\n const clientId = requiredEnv('GOOGLE_CLIENT_ID');\n const clientSecret = env.GOOGLE_CLIENT_SECRET;\n\n return {\n mode,\n ...(verifyUrl && { verifyUrl }),\n ...(storeUri && { storeUri }),\n clientId,\n ...(clientSecret && { clientSecret }),\n scope,\n };\n}\n"],"names":["resolve","parseArgs","parseAuthMode","value","Error","auth","parseConfig","args","env","transport","cliHeadless","requiredEnv","key","values","options","type","headless","strict","allowPositionals","authArg","undefined","envAuthMode","AUTH_MODE","mode","parsed","envHeadless","HEADLESS","cliRedirectUri","envRedirectUri","REDIRECT_URI","redirectUri","clientId","clientSecret","GOOGLE_CLIENT_SECRET","serviceAccountKeyFile","cliKeyFile","GOOGLE_SERVICE_ACCOUNT_KEY_FILE","createConfig","process","argv","parseDcrConfig","scope","cliMode","envMode","DCR_MODE","cliVerifyUrl","envVerifyUrl","DCR_VERIFY_URL","verifyUrl","cliStoreUri","envStoreUri","DCR_STORE_URI","storeUri"],"mappings":"AAAA;;;;;;CAMC,GAED,SAASA,OAAO,QAAQ,OAAO;AAC/B,SAASC,SAAS,QAAQ,OAAO;AAWjC;;;;;;;;;;;;;CAaC,GACD,SAASC,cAAcC,KAAa;IAGlC,IAAIA,UAAU,oBAAoBA,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E,GAAGZ,UAAU;QAC3BM;QACAO,SAAS;YACP,YAAY;gBAAEC,MAAM;YAAS;YAC7B,kBAAkB;gBAAEA,MAAM;YAAS;YACnC,iBAAiB;gBAAEA,MAAM;YAAS;QACpC;QACAE,QAAQ;QACRC,kBAAkB;IACpB;IAEA,MAAMwB,UAAU,OAAO7B,MAAM,CAAC,WAAW,KAAK,WAAWA,MAAM,CAAC,WAAW,GAAGO;IAC9E,MAAMuB,UAAUnC,IAAIoC,QAAQ;IAC5B,MAAMrB,OAAOmB,WAAWC,WAAW;IAEnC,IAAIpB,SAAS,iBAAiBA,SAAS,YAAY;QACjD,MAAM,IAAInB,MAAM,CAAC,2BAA2B,EAAEmB,KAAK,sCAAsC,CAAC;IAC5F;IAEA,MAAMsB,eAAe,OAAOhC,MAAM,CAAC,iBAAiB,KAAK,WAAWA,MAAM,CAAC,iBAAiB,GAAGO;IAC/F,MAAM0B,eAAetC,IAAIuC,cAAc;IACvC,MAAMC,YAAYH,gBAAgBC;IAElC,MAAMG,cAAc,OAAOpC,MAAM,CAAC,gBAAgB,KAAK,WAAWA,MAAM,CAAC,gBAAgB,GAAGO;IAC5F,MAAM8B,cAAc1C,IAAI2C,aAAa;IACrC,MAAMC,WAAWH,eAAeC;IAEhC,IAAI3B,SAAS,cAAc,CAACyB,WAAW;QACrC,MAAM,IAAI5C,MAAM;IAClB;IAEA,MAAM2B,WAAWpB,YAAY;IAC7B,MAAMqB,eAAexB,IAAIyB,oBAAoB;IAE7C,OAAO;QACLV;QACA,GAAIyB,aAAa;YAAEA;QAAU,CAAC;QAC9B,GAAII,YAAY;YAAEA;QAAS,CAAC;QAC5BrB;QACA,GAAIC,gBAAgB;YAAEA;QAAa,CAAC;QACpCS;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/Projects/mcp-z/oauth-google/src/setup/config.ts"],"sourcesContent":["/**\n * Google OAuth configuration parsing from CLI arguments and environment variables.\n *\n * This module provides utilities to parse Google OAuth configuration from\n * CLI arguments and environment variables, following the same pattern as @mcp-z/server's\n * parseConfig().\n */\n\nimport { resolve } from 'path';\nimport { parseArgs } from 'util';\nimport type { DcrConfig, OAuthConfig } from '../types.ts';\n\n// Re-export for direct imports from config.ts\nexport type { DcrConfig, OAuthConfig };\n\n/**\n * auth mode type (from OAuthConfig)\n */\ntype AuthMode = 'loopback-oauth' | 'service-account' | 'dcr';\n\n/**\n * Parse auth mode string into auth mode.\n *\n * @param value - Auth mode string ('loopback-oauth', 'service-account', or 'dcr')\n * @returns Parsed auth mode\n * @throws Error if value is invalid\n *\n * @example Valid formats\n * ```typescript\n * parseAuthMode('loopback-oauth') // { auth: 'loopback-oauth' }\n * parseAuthMode('service-account') // { auth: 'service-account' }\n * parseAuthMode('dcr') // { auth: 'dcr' }\n * ```\n */\nfunction parseAuthMode(value: string): {\n auth: AuthMode;\n} {\n if (value !== 'loopback-oauth' && value !== 'service-account' && value !== 'dcr') {\n throw new Error(`Invalid --auth value: \"${value}\". Valid values: loopback-oauth, service-account, dcr`);\n }\n\n return {\n auth: value as AuthMode,\n };\n}\n\n/**\n * Transport type for MCP servers\n *\n * @typedef {('stdio' | 'http')} TransportType\n * @property {'stdio'} stdio - Standard input/output transport for CLI applications\n * @property {'http'} http - HTTP transport for web-based applications\n */\nexport type TransportType = 'stdio' | 'http';\n\n/**\n * Parse Google OAuth configuration from CLI arguments and environment variables.\n *\n * CLI Arguments:\n * - --auth: Auth mode ('loopback-oauth' | 'service-account' | 'dcr')\n * - Default: 'loopback-oauth' (if flag is omitted)\n * - --headless: Disable browser opening for OAuth flow (default: false, true in test env)\n * - --redirect-uri: Override OAuth redirect URI (default: ephemeral loopback)\n * - --service-account-key-file: Service account key file path (required for service-account mode)\n *\n * Required environment variables:\n * - GOOGLE_CLIENT_ID: OAuth 2.0 client ID from Google Cloud Console\n *\n * Optional environment variables:\n * - GOOGLE_CLIENT_SECRET: OAuth 2.0 client secret (optional for public clients)\n * - AUTH_MODE: Auth mode (same format as --auth flag)\n * - HEADLESS: Headless mode flag ('true' to enable)\n * - REDIRECT_URI: OAuth redirect URI (overridden by --redirect-uri CLI flag)\n * - GOOGLE_SERVICE_ACCOUNT_KEY_FILE: Service account key file (for service-account mode)\n *\n * @param args - CLI arguments array (typically process.argv)\n * @param env - Environment variables object (typically process.env)\n * @param transport - Optional transport type. If 'stdio' and auth mode is 'dcr', throws an error.\n * See {@link TransportType} for valid values.\n * @returns Parsed Google OAuth configuration\n * @throws Error if required environment variables are missing, values are invalid, or DCR is used with stdio transport\n *\n * @example Default mode (no flags)\n * ```typescript\n * const config = parseConfig(process.argv, process.env);\n * // { auth: 'loopback-oauth' }\n * ```\n *\n * @example Override auth mode\n * ```typescript\n * parseConfig(['--auth=loopback-oauth'], process.env);\n * parseConfig(['--auth=service-account'], process.env);\n * parseConfig(['--auth=dcr'], process.env);\n * ```\n *\n * @example With transport validation\n * ```typescript\n * parseConfig(['--auth=dcr'], process.env, 'http'); // OK\n * parseConfig(['--auth=dcr'], process.env, 'stdio'); // Throws error\n * ```\n *\n * Valid auth modes:\n * - loopback-oauth (default)\n * - service-account\n * - dcr (HTTP transport only)\n */\nexport function parseConfig(args: string[], env: Record<string, string | undefined>, transport?: TransportType): OAuthConfig {\n function requiredEnv(key: string): string {\n const value = env[key];\n if (!value) {\n throw new Error(`Environment variable ${key} is required for Google OAuth`);\n }\n return value;\n }\n\n // Parse CLI arguments\n const { values } = parseArgs({\n args,\n options: {\n auth: { type: 'string' },\n headless: { type: 'boolean' },\n 'redirect-uri': { type: 'string' },\n 'service-account-key-file': { type: 'string' },\n },\n strict: false, // Allow other arguments\n allowPositionals: true,\n });\n\n const authArg = typeof values.auth === 'string' ? values.auth : undefined;\n const envAuthMode = env.AUTH_MODE;\n const mode = authArg || envAuthMode;\n\n let auth: AuthMode;\n\n if (mode) {\n const parsed = parseAuthMode(mode);\n auth = parsed.auth;\n } else {\n // DEFAULT: No flags provided, use loopback-oauth\n auth = 'loopback-oauth';\n }\n\n // Validate: DCR only works with HTTP transport\n if (auth === 'dcr' && transport === 'stdio') {\n throw new Error('DCR authentication mode requires HTTP transport. DCR is not supported with stdio transport.');\n }\n\n const cliHeadless = typeof values.headless === 'boolean' ? values.headless : undefined;\n const envHeadless = env.HEADLESS === 'true' ? true : env.HEADLESS === 'false' ? false : undefined;\n const headless = cliHeadless ?? envHeadless ?? false;\n\n const cliRedirectUri = typeof values['redirect-uri'] === 'string' ? values['redirect-uri'] : undefined;\n const envRedirectUri = env.REDIRECT_URI;\n const redirectUri = cliRedirectUri ?? envRedirectUri;\n if (redirectUri && transport === 'stdio') {\n throw new Error('REDIRECT_URI requires HTTP transport. The OAuth callback must be served over HTTP.');\n }\n\n const clientId = requiredEnv('GOOGLE_CLIENT_ID');\n const clientSecret = env.GOOGLE_CLIENT_SECRET;\n\n let serviceAccountKeyFile: string | undefined;\n if (auth === 'service-account') {\n const cliKeyFile = typeof values['service-account-key-file'] === 'string' ? values['service-account-key-file'] : undefined;\n serviceAccountKeyFile = cliKeyFile ?? env.GOOGLE_SERVICE_ACCOUNT_KEY_FILE;\n\n if (!serviceAccountKeyFile) {\n throw new Error('GOOGLE_SERVICE_ACCOUNT_KEY_FILE environment variable is required when using service account authentication. ' + 'Example: export GOOGLE_SERVICE_ACCOUNT_KEY_FILE=./service-account.json');\n }\n\n // Resolve relative paths now since cwd can change during execution\n serviceAccountKeyFile = resolve(serviceAccountKeyFile);\n }\n\n return {\n clientId,\n ...(clientSecret && { clientSecret }),\n auth,\n headless,\n ...(redirectUri && { redirectUri }),\n ...(serviceAccountKeyFile && { serviceAccountKeyFile }),\n };\n}\n\n/**\n * Build production configuration from process globals.\n * Entry point for production server.\n */\nexport function createConfig(): OAuthConfig {\n return parseConfig(process.argv, process.env);\n}\n\n/**\n * Parse DCR configuration from CLI arguments and environment variables.\n *\n * CLI Arguments:\n * - --dcr-mode: DCR mode ('self-hosted' | 'external')\n * - Default: 'self-hosted' (if flag is omitted)\n * - --dcr-verify-url: External verification endpoint URL (required for external mode)\n * - --dcr-store-uri: DCR client storage URI (required for self-hosted mode)\n *\n * Required environment variables:\n * - GOOGLE_CLIENT_ID: OAuth 2.0 client ID from Google Cloud Console\n *\n * Optional environment variables:\n * - GOOGLE_CLIENT_SECRET: OAuth 2.0 client secret (optional for public clients)\n * - DCR_MODE: DCR mode (same format as --dcr-mode flag)\n * - DCR_VERIFY_URL: External verification URL (same as --dcr-verify-url flag)\n * - DCR_STORE_URI: DCR storage URI (same as --dcr-store-uri flag)\n *\n * @param args - CLI arguments array (typically process.argv)\n * @param env - Environment variables object (typically process.env)\n * @param scope - OAuth scopes to request (space-separated)\n * @returns Parsed DCR configuration\n * @throws Error if required environment variables are missing or validation fails\n *\n * @example Self-hosted mode\n * ```typescript\n * const config = parseDcrConfig(\n * ['--dcr-mode=self-hosted', '--dcr-store-uri=file:///path/to/store.json'],\n * process.env,\n * 'https://www.googleapis.com/auth/drive.readonly'\n * );\n * ```\n *\n * @example External mode\n * ```typescript\n * const config = parseDcrConfig(\n * ['--dcr-mode=external', '--dcr-verify-url=https://auth0.example.com/verify'],\n * process.env,\n * 'https://www.googleapis.com/auth/drive.readonly'\n * );\n * ```\n */\nexport function parseDcrConfig(args: string[], env: Record<string, string | undefined>, scope: string): DcrConfig {\n function requiredEnv(key: string): string {\n const value = env[key];\n if (!value) {\n throw new Error(`Environment variable ${key} is required for DCR configuration`);\n }\n return value;\n }\n\n const { values } = parseArgs({\n args,\n options: {\n 'dcr-mode': { type: 'string' },\n 'dcr-verify-url': { type: 'string' },\n 'dcr-store-uri': { type: 'string' },\n },\n strict: false,\n allowPositionals: true,\n });\n\n const cliMode = typeof values['dcr-mode'] === 'string' ? values['dcr-mode'] : undefined;\n const envMode = env.DCR_MODE;\n const mode = cliMode || envMode || 'self-hosted';\n\n if (mode !== 'self-hosted' && mode !== 'external') {\n throw new Error(`Invalid --dcr-mode value: \"${mode}\". Valid values: self-hosted, external`);\n }\n\n const cliVerifyUrl = typeof values['dcr-verify-url'] === 'string' ? values['dcr-verify-url'] : undefined;\n const envVerifyUrl = env.DCR_VERIFY_URL;\n const verifyUrl = cliVerifyUrl || envVerifyUrl;\n\n const cliStoreUri = typeof values['dcr-store-uri'] === 'string' ? values['dcr-store-uri'] : undefined;\n const envStoreUri = env.DCR_STORE_URI;\n const storeUri = cliStoreUri || envStoreUri;\n\n if (mode === 'external' && !verifyUrl) {\n throw new Error('DCR external mode requires --dcr-verify-url or DCR_VERIFY_URL environment variable');\n }\n\n const clientId = requiredEnv('GOOGLE_CLIENT_ID');\n const clientSecret = env.GOOGLE_CLIENT_SECRET;\n\n return {\n mode,\n ...(verifyUrl && { verifyUrl }),\n ...(storeUri && { storeUri }),\n clientId,\n ...(clientSecret && { clientSecret }),\n scope,\n };\n}\n"],"names":["resolve","parseArgs","parseAuthMode","value","Error","auth","parseConfig","args","env","transport","cliHeadless","requiredEnv","key","values","options","type","headless","strict","allowPositionals","authArg","undefined","envAuthMode","AUTH_MODE","mode","parsed","envHeadless","HEADLESS","cliRedirectUri","envRedirectUri","REDIRECT_URI","redirectUri","clientId","clientSecret","GOOGLE_CLIENT_SECRET","serviceAccountKeyFile","cliKeyFile","GOOGLE_SERVICE_ACCOUNT_KEY_FILE","createConfig","process","argv","parseDcrConfig","scope","cliMode","envMode","DCR_MODE","cliVerifyUrl","envVerifyUrl","DCR_VERIFY_URL","verifyUrl","cliStoreUri","envStoreUri","DCR_STORE_URI","storeUri"],"mappings":"AAAA;;;;;;CAMC,GAED,SAASA,OAAO,QAAQ,OAAO;AAC/B,SAASC,SAAS,QAAQ,OAAO;AAWjC;;;;;;;;;;;;;CAaC,GACD,SAASC,cAAcC,KAAa;IAGlC,IAAIA,UAAU,oBAAoBA,UAAU,qBAAqBA,UAAU,OAAO;QAChF,MAAM,IAAIC,MAAM,CAAC,uBAAuB,EAAED,MAAM,qDAAqD,CAAC;IACxG;IAEA,OAAO;QACLE,MAAMF;IACR;AACF;AAWA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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gBAAEA,MAAM;YAAS;QACpC;QACAE,QAAQ;QACRC,kBAAkB;IACpB;IAEA,MAAMwB,UAAU,OAAO7B,MAAM,CAAC,WAAW,KAAK,WAAWA,MAAM,CAAC,WAAW,GAAGO;IAC9E,MAAMuB,UAAUnC,IAAIoC,QAAQ;IAC5B,MAAMrB,OAAOmB,WAAWC,WAAW;IAEnC,IAAIpB,SAAS,iBAAiBA,SAAS,YAAY;QACjD,MAAM,IAAInB,MAAM,CAAC,2BAA2B,EAAEmB,KAAK,sCAAsC,CAAC;IAC5F;IAEA,MAAMsB,eAAe,OAAOhC,MAAM,CAAC,iBAAiB,KAAK,WAAWA,MAAM,CAAC,iBAAiB,GAAGO;IAC/F,MAAM0B,eAAetC,IAAIuC,cAAc;IACvC,MAAMC,YAAYH,gBAAgBC;IAElC,MAAMG,cAAc,OAAOpC,MAAM,CAAC,gBAAgB,KAAK,WAAWA,MAAM,CAAC,gBAAgB,GAAGO;IAC5F,MAAM8B,cAAc1C,IAAI2C,aAAa;IACrC,MAAMC,WAAWH,eAAeC;IAEhC,IAAI3B,SAAS,cAAc,CAACyB,WAAW;QACrC,MAAM,IAAI5C,MAAM;IAClB;IAEA,MAAM2B,WAAWpB,YAAY;IAC7B,MAAMqB,eAAexB,IAAIyB,oBAAoB;IAE7C,OAAO;QACLV;QACA,GAAIyB,aAAa;YAAEA;QAAU,CAAC;QAC9B,GAAII,YAAY;YAAEA;QAAS,CAAC;QAC5BrB;QACA,GAAIC,gBAAgB;YAAEA;QAAa,CAAC;QACpCS;IACF;AACF"}
|
package/dist/esm/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/Projects/
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/Projects/mcp-z/oauth-google/src/types.ts"],"sourcesContent":["/**\n * Standalone types for Google OAuth\n * No dependencies on other @mcp-z packages except @mcp-z/oauth\n */\n\n// Shared types from base @mcp-z/oauth package\nimport type { AuthFlowDescriptor, CachedToken, DcrClientInformation, DcrClientMetadata, Logger, OAuth2TokenStorageProvider, ProviderTokens, ToolHandler, ToolModule, UserAuthProvider } from '@mcp-z/oauth';\nimport type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js';\nimport type { ServerNotification, ServerRequest } from '@modelcontextprotocol/sdk/types.js';\nimport type { OAuth2Client } from 'google-auth-library';\nimport type { Keyv } from 'keyv';\n\n// Re-export only essential shared types for public API\nexport type { Logger, CachedToken, ToolModule, ProviderTokens, DcrClientMetadata, DcrClientInformation };\n\n// Re-export error class\nexport { AuthRequiredError } from '@mcp-z/oauth';\n\n// Re-export additional types for internal package use\nexport type { ToolHandler, AuthFlowDescriptor, OAuth2TokenStorageProvider, UserAuthProvider, RequestHandlerExtra, ServerRequest, ServerNotification };\n\n/**\n * Google service types that support OAuth\n * OAuth clients support all Google services provided by googleapis\n * @public\n */\nexport type GoogleService = string;\n\n// =============================================================================\n// Configuration Types\n// =============================================================================\n\n/**\n * OAuth client configuration for upstream provider\n * @public\n */\nexport interface OAuthClientConfig {\n /** OAuth client ID for upstream provider */\n clientId: string;\n /** OAuth client secret (optional for some flows) */\n clientSecret?: string;\n}\n\n/**\n * Google OAuth configuration interface.\n * @public\n */\nexport interface OAuthConfig {\n clientId: string;\n /** Optional for public clients */\n clientSecret?: string;\n auth: 'loopback-oauth' | 'service-account' | 'dcr';\n /** No browser interaction when true */\n headless: boolean;\n /** Defaults to ephemeral loopback */\n redirectUri?: string;\n /** Required when auth === 'service-account' */\n serviceAccountKeyFile?: string;\n}\n\n/**\n * DCR configuration for dynamic client registration\n * @public\n */\nexport interface DcrConfig {\n /** DCR mode: self-hosted (runs own OAuth server) or external (uses Auth0/Stitch) */\n mode: 'self-hosted' | 'external';\n /** External verification endpoint URL (required for external mode) */\n verifyUrl?: string;\n /** DCR client storage URI (required for self-hosted mode) */\n storeUri?: string;\n /** OAuth client ID for Google APIs */\n clientId: string;\n /** OAuth client secret (optional for public clients) */\n clientSecret?: string;\n /** OAuth scopes to request */\n scope: string;\n /** Logger instance */\n logger?: Logger;\n}\n\n/**\n * Configuration for loopback OAuth client\n * @public\n */\nexport interface LoopbackOAuthConfig {\n service: GoogleService;\n clientId: string;\n /** Optional for public clients */\n clientSecret?: string | undefined;\n scope: string;\n /** No browser interaction when true */\n headless: boolean;\n logger: Logger;\n tokenStore: Keyv<unknown>;\n /** Defaults to ephemeral loopback */\n redirectUri?: string;\n}\n\n// =============================================================================\n// Middleware Types\n// =============================================================================\n\n/**\n * Auth context injected into extra by middleware\n * @public\n */\nexport interface AuthContext {\n /**\n * OAuth2Client ready for googleapis\n * GUARANTEED to exist when handler runs\n */\n auth: OAuth2Client;\n\n /**\n * Account being used (for logging, debugging)\n */\n accountId: string;\n\n /**\n * User ID (multi-tenant only)\n */\n\n /**\n * Additional metadata (e.g., service account email)\n */\n metadata?: {\n serviceEmail?: string;\n [key: string]: unknown;\n };\n}\n\n/**\n * Enriched extra with guaranteed auth context and logger\n * Handlers receive this type - never plain RequestHandlerExtra\n * @public\n */\nexport interface EnrichedExtra extends RequestHandlerExtra<ServerRequest, ServerNotification> {\n /**\n * Auth context injected by middleware\n * GUARANTEED to exist (middleware catches auth failures)\n */\n authContext: AuthContext;\n\n /**\n * Logger injected by middleware\n * GUARANTEED to exist\n */\n logger: Logger;\n\n // Preserve backchannel support\n _meta?: {\n accountId?: string;\n [key: string]: unknown;\n };\n}\n\n// =============================================================================\n// DCR Internal Types\n// =============================================================================\n\n/**\n * Registered client with full metadata\n * Extends DcrClientInformation with internal timestamps\n * @internal\n */\nexport interface RegisteredClient extends DcrClientInformation {\n /** Creation timestamp (milliseconds since epoch) */\n created_at: number;\n}\n\n/**\n * Authorization code data structure\n * @public\n */\nexport interface AuthorizationCode {\n code: string;\n client_id: string;\n redirect_uri: string;\n scope: string;\n code_challenge?: string;\n code_challenge_method?: string;\n /** Google provider tokens obtained during authorization */\n providerTokens: ProviderTokens;\n created_at: number;\n expires_at: number;\n}\n\n/**\n * Access token data structure\n * @public\n */\nexport interface AccessToken {\n access_token: string;\n token_type: 'Bearer';\n expires_in: number;\n refresh_token?: string;\n scope: string;\n client_id: string;\n /** Google provider tokens */\n providerTokens: ProviderTokens;\n created_at: number;\n}\n\n// =============================================================================\n// Schema Types\n// =============================================================================\n\n/**\n * Authentication required response type\n * Re-exported from @mcp-z/oauth for consistency\n * @public\n */\nexport type { AuthRequired, AuthRequiredBranch } from './schemas/index.ts';\n"],"names":["AuthRequiredError"],"mappings":"AAAA;;;CAGC,GAED,8CAA8C;AAU9C,wBAAwB;AACxB,SAASA,iBAAiB,QAAQ,eAAe"}
|