@mcp-z/oauth-microsoft 1.0.0 → 1.0.2

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.
Files changed (51) hide show
  1. package/README.md +8 -0
  2. package/dist/cjs/index.d.cts +2 -1
  3. package/dist/cjs/index.d.ts +2 -1
  4. package/dist/cjs/index.js +4 -0
  5. package/dist/cjs/index.js.map +1 -1
  6. package/dist/cjs/lib/dcr-router.js.map +1 -1
  7. package/dist/cjs/lib/dcr-utils.js.map +1 -1
  8. package/dist/cjs/lib/dcr-verify.js.map +1 -1
  9. package/dist/cjs/lib/fetch-with-timeout.js.map +1 -1
  10. package/dist/cjs/lib/loopback-router.d.cts +8 -0
  11. package/dist/cjs/lib/loopback-router.d.ts +8 -0
  12. package/dist/cjs/lib/loopback-router.js +219 -0
  13. package/dist/cjs/lib/loopback-router.js.map +1 -0
  14. package/dist/cjs/lib/token-verifier.js.map +1 -1
  15. package/dist/cjs/providers/dcr.js.map +1 -1
  16. package/dist/cjs/providers/device-code.js.map +1 -1
  17. package/dist/cjs/providers/loopback-oauth.d.cts +93 -18
  18. package/dist/cjs/providers/loopback-oauth.d.ts +93 -18
  19. package/dist/cjs/providers/loopback-oauth.js +877 -491
  20. package/dist/cjs/providers/loopback-oauth.js.map +1 -1
  21. package/dist/cjs/schemas/index.js +1 -1
  22. package/dist/cjs/schemas/index.js.map +1 -1
  23. package/dist/cjs/setup/config.d.cts +4 -1
  24. package/dist/cjs/setup/config.d.ts +4 -1
  25. package/dist/cjs/setup/config.js +7 -4
  26. package/dist/cjs/setup/config.js.map +1 -1
  27. package/dist/cjs/types.js.map +1 -1
  28. package/dist/esm/index.d.ts +2 -1
  29. package/dist/esm/index.js +1 -0
  30. package/dist/esm/index.js.map +1 -1
  31. package/dist/esm/lib/dcr-router.js.map +1 -1
  32. package/dist/esm/lib/dcr-utils.js.map +1 -1
  33. package/dist/esm/lib/dcr-verify.js.map +1 -1
  34. package/dist/esm/lib/fetch-with-timeout.js.map +1 -1
  35. package/dist/esm/lib/loopback-router.d.ts +8 -0
  36. package/dist/esm/lib/loopback-router.js +32 -0
  37. package/dist/esm/lib/loopback-router.js.map +1 -0
  38. package/dist/esm/lib/token-verifier.js.map +1 -1
  39. package/dist/esm/providers/dcr.js.map +1 -1
  40. package/dist/esm/providers/device-code.js +2 -2
  41. package/dist/esm/providers/device-code.js.map +1 -1
  42. package/dist/esm/providers/loopback-oauth.d.ts +93 -18
  43. package/dist/esm/providers/loopback-oauth.js +470 -289
  44. package/dist/esm/providers/loopback-oauth.js.map +1 -1
  45. package/dist/esm/schemas/index.js +1 -1
  46. package/dist/esm/schemas/index.js.map +1 -1
  47. package/dist/esm/setup/config.d.ts +4 -1
  48. package/dist/esm/setup/config.js +7 -4
  49. package/dist/esm/setup/config.js.map +1 -1
  50. package/dist/esm/types.js.map +1 -1
  51. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/Projects/ai/mcp-z/oauth/oauth-microsoft/src/providers/device-code.ts"],"sourcesContent":["/**\n * Device Code OAuth Implementation for Microsoft\n *\n * Implements OAuth 2.0 Device Authorization Grant (RFC 8628) for headless/limited-input devices.\n * Designed for scenarios where interactive browser flows are impractical (SSH sessions, CI/CD, etc.).\n *\n * Flow:\n * 1. Request device code from Microsoft endpoint\n * 2. Display user_code and verification_uri to user\n * 3. Poll token endpoint until user completes authentication\n * 4. Cache access token + refresh token to storage\n * 5. Refresh tokens when expired\n *\n * Similar to service accounts in usage pattern: single static identity, minimal account management.\n */\n\nimport { getToken, type OAuth2TokenStorageProvider, setToken } from '@mcp-z/oauth';\nimport type { Keyv } from 'keyv';\nimport open from 'open';\nimport { fetchWithTimeout } from '../lib/fetch-with-timeout.ts';\nimport type { AuthContext, CachedToken, EnrichedExtra, Logger, MicrosoftAuthProvider, MicrosoftService } from '../types.ts';\n\n/**\n * Device Code Flow Response\n * Response from Microsoft device authorization endpoint\n */\ninterface DeviceCodeResponse {\n device_code: string;\n user_code: string;\n verification_uri: string;\n verification_uri_complete?: string;\n expires_in: number;\n interval: number;\n message?: string;\n}\n\n/**\n * Token Response from Microsoft OAuth endpoint\n */\ninterface TokenResponse {\n access_token: string;\n refresh_token?: string;\n expires_in: number;\n scope?: string;\n token_type?: string;\n}\n\n/**\n * Device Code Provider Configuration\n */\nexport interface DeviceCodeConfig {\n /** Microsoft service type (e.g., 'outlook') */\n service: MicrosoftService;\n /** Azure AD client ID */\n clientId: string;\n /** Azure AD tenant ID */\n tenantId: string;\n /** OAuth scopes to request (space-separated string or array) */\n scope: string;\n /** Logger instance */\n logger: Logger;\n /** Token storage for caching */\n tokenStore: Keyv<unknown>;\n /** Headless mode - print device code instead of opening browser */\n headless: boolean;\n}\n\n/**\n * DeviceCodeProvider implements OAuth2TokenStorageProvider using Microsoft Device Code Flow\n *\n * This provider:\n * - Initiates device code flow with Microsoft endpoint\n * - Displays user_code and verification_uri for manual authentication\n * - Polls token endpoint until user completes auth\n * - Stores access tokens + refresh tokens in Keyv storage\n * - Refreshes tokens when expired\n * - Provides single static identity (minimal account management like service accounts)\n *\n * @example\n * ```typescript\n * const provider = new DeviceCodeProvider({\n * service: 'outlook',\n * clientId: 'your-client-id',\n * tenantId: 'common',\n * scope: 'https://graph.microsoft.com/Mail.Read',\n * logger: console,\n * tokenStore: new Keyv(),\n * headless: true,\n * });\n *\n * // Get authenticated Microsoft Graph client\n * const token = await provider.getAccessToken('default');\n * ```\n */\nexport class DeviceCodeProvider implements OAuth2TokenStorageProvider {\n private config: DeviceCodeConfig;\n\n constructor(config: DeviceCodeConfig) {\n this.config = config;\n }\n\n /**\n * Start device code flow and poll for token\n *\n * 1. POST to /devicecode endpoint to get device_code and user_code\n * 2. Display verification instructions to user\n * 3. Poll /token endpoint every interval seconds\n * 4. Handle authorization_pending, slow_down, expired_token errors\n * 5. Return token when user completes authentication\n */\n private async startDeviceCodeFlow(accountId: string): Promise<CachedToken> {\n const { clientId, tenantId, scope, logger, headless } = this.config;\n\n // Step 1: Request device code\n const deviceCodeEndpoint = `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/devicecode`;\n logger.debug('Requesting device code', { endpoint: deviceCodeEndpoint });\n\n const deviceCodeResponse = await fetchWithTimeout(deviceCodeEndpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n client_id: clientId,\n scope: scope,\n }),\n });\n\n if (!deviceCodeResponse.ok) {\n const errorText = await deviceCodeResponse.text();\n throw new Error(`Device code request failed (HTTP ${deviceCodeResponse.status}): ${errorText}`);\n }\n\n const deviceCodeData = (await deviceCodeResponse.json()) as DeviceCodeResponse;\n const { device_code, user_code, verification_uri, verification_uri_complete, expires_in, interval } = deviceCodeData;\n\n // Step 2: Display instructions to user\n logger.info('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');\n logger.info('Device code authentication required');\n logger.info('');\n logger.info(`Please visit: ${verification_uri_complete || verification_uri}`);\n logger.info(`And enter code: ${user_code}`);\n logger.info('');\n logger.info(`Code expires in ${expires_in} seconds`);\n logger.info('Waiting for authentication...');\n logger.info('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');\n\n // Optional: Open browser in non-headless mode\n if (!headless) {\n const urlToOpen = verification_uri_complete || verification_uri;\n try {\n await open(urlToOpen);\n logger.debug('Opened browser to verification URL', { url: urlToOpen });\n } catch (error) {\n logger.debug('Failed to open browser', { error: error instanceof Error ? error.message : String(error) });\n }\n }\n\n // Step 3: Poll token endpoint\n return await this.pollForToken(device_code, interval || 5, accountId);\n }\n\n /**\n * Poll Microsoft token endpoint until user completes authentication\n *\n * Handles Microsoft-specific error codes:\n * - authorization_pending: User hasn't completed auth yet, keep polling\n * - slow_down: Increase polling interval by 5 seconds\n * - authorization_declined: User denied authorization\n * - expired_token: Device code expired (typically after 15 minutes)\n */\n private async pollForToken(deviceCode: string, intervalSeconds: number, accountId: string): Promise<CachedToken> {\n const { clientId, tenantId, logger, service, tokenStore } = this.config;\n const tokenEndpoint = `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`;\n\n let currentInterval = intervalSeconds;\n const startTime = Date.now();\n\n while (true) {\n // Wait for polling interval\n await new Promise((resolve) => setTimeout(resolve, currentInterval * 1000));\n\n logger.debug('Polling for token', { elapsed: Math.floor((Date.now() - startTime) / 1000), interval: currentInterval });\n\n const response = await fetchWithTimeout(tokenEndpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: 'urn:ietf:params:oauth:grant-type:device_code',\n client_id: clientId,\n device_code: deviceCode,\n }),\n });\n\n const responseData = (await response.json()) as TokenResponse & { error?: string; error_description?: string };\n\n if (response.ok) {\n // Success! Convert to CachedToken and store\n const tokenData = responseData as TokenResponse;\n const token: CachedToken = {\n accessToken: tokenData.access_token,\n ...(tokenData.refresh_token && { refreshToken: tokenData.refresh_token }),\n expiresAt: Date.now() + (tokenData.expires_in - 60) * 1000, // 60s safety margin\n ...(tokenData.scope && { scope: tokenData.scope }),\n };\n\n // Cache token to storage\n await setToken(tokenStore, { accountId, service }, token);\n logger.info('Device code authentication successful', { accountId });\n\n return token;\n }\n\n // Handle error responses\n const error = responseData.error;\n const errorDescription = responseData.error_description || '';\n\n if (error === 'authorization_pending') {\n // User hasn't completed auth yet - continue polling\n logger.debug('Authorization pending, waiting for user...');\n continue;\n }\n\n if (error === 'slow_down') {\n // Microsoft wants us to slow down polling\n currentInterval += 5;\n logger.debug('Received slow_down, increasing interval', { newInterval: currentInterval });\n continue;\n }\n\n if (error === 'authorization_declined') {\n throw new Error('User declined authorization. Please restart the authentication flow.');\n }\n\n if (error === 'expired_token') {\n throw new Error('Device code expired. Please restart the authentication flow.');\n }\n\n // Unknown error\n throw new Error(`Device code flow failed: ${error} - ${errorDescription}`);\n }\n }\n\n /**\n * Refresh expired access token using refresh token\n *\n * @param refreshToken - Refresh token from previous authentication\n * @returns New cached token with fresh access token\n */\n private async refreshAccessToken(refreshToken: string): Promise<CachedToken> {\n const { clientId, tenantId, scope, logger } = this.config;\n const tokenEndpoint = `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`;\n\n logger.debug('Refreshing access token');\n\n const response = await fetchWithTimeout(tokenEndpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: 'refresh_token',\n client_id: clientId,\n refresh_token: refreshToken,\n scope: scope,\n }),\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Token refresh failed (HTTP ${response.status}): ${errorText}`);\n }\n\n const tokenData = (await response.json()) as TokenResponse;\n\n return {\n accessToken: tokenData.access_token,\n refreshToken: tokenData.refresh_token || refreshToken, // Some responses may not include new refresh token\n expiresAt: Date.now() + (tokenData.expires_in - 60) * 1000, // 60s safety margin\n scope: tokenData.scope || scope,\n };\n }\n\n /**\n * Check if token is still valid (not expired)\n */\n private isTokenValid(token: CachedToken): boolean {\n return token.expiresAt !== undefined && token.expiresAt > Date.now();\n }\n\n /**\n * Get access token for Microsoft Graph API\n *\n * Flow:\n * 1. Check token storage\n * 2. If valid token exists, return it\n * 3. If expired but has refresh token, try refresh\n * 4. Otherwise, start new device code flow\n *\n * @param accountId - Account identifier. Defaults to 'device-code' (fixed identifier for device code flow).\n * @returns Access token for API requests\n */\n async getAccessToken(accountId?: string): Promise<string> {\n const { logger, service, tokenStore } = this.config;\n const effectiveAccountId = accountId ?? 'device-code';\n\n logger.debug('Getting access token', { service, accountId: effectiveAccountId });\n\n // Check storage for cached token\n const storedToken = await getToken<CachedToken>(tokenStore, { accountId: effectiveAccountId, service });\n\n if (storedToken && this.isTokenValid(storedToken)) {\n logger.debug('Using stored access token', { accountId: effectiveAccountId });\n return storedToken.accessToken;\n }\n\n // If stored token expired but has refresh token, try refresh\n if (storedToken?.refreshToken) {\n try {\n logger.info('Refreshing expired access token', { accountId: effectiveAccountId });\n const refreshedToken = await this.refreshAccessToken(storedToken.refreshToken);\n await setToken(tokenStore, { accountId: effectiveAccountId, service }, refreshedToken);\n return refreshedToken.accessToken;\n } catch (error) {\n logger.info('Token refresh failed', {\n accountId: effectiveAccountId,\n error: error instanceof Error ? error.message : String(error),\n });\n // In headless mode, cannot start interactive device code flow\n if (this.config.headless) {\n throw new Error(`Token refresh failed in headless mode. Cannot start interactive device code flow. Error: ${error instanceof Error ? error.message : String(error)}`);\n }\n // Fall through to new device code flow (interactive mode only)\n }\n }\n\n // No valid token - check if we can start device code flow\n if (this.config.headless) {\n throw new Error('No valid token available in headless mode. Device code flow requires user interaction. ' + 'Please run authentication flow interactively first or provide valid tokens.');\n }\n\n // Interactive mode - start device code flow\n logger.info('Starting device code flow', { accountId: effectiveAccountId });\n const token = await this.startDeviceCodeFlow(effectiveAccountId);\n return token.accessToken;\n }\n\n /**\n * Get user email from Microsoft Graph /me endpoint (pure query)\n *\n * @param accountId - Account identifier\n * @returns User's email address (userPrincipalName or mail field)\n */\n async getUserEmail(accountId?: string): Promise<string> {\n const { logger } = this.config;\n // Device code is single-account mode\n const token = await this.getAccessToken(accountId);\n\n logger.debug('Fetching user email from Microsoft Graph');\n\n const response = await fetchWithTimeout('https://graph.microsoft.com/v1.0/me', {\n headers: { Authorization: `Bearer ${token}` },\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Failed to get user email (HTTP ${response.status}): ${errorText}`);\n }\n\n const userData = (await response.json()) as { userPrincipalName?: string; mail?: string };\n const email = userData.userPrincipalName || userData.mail;\n\n if (!email) {\n throw new Error('User email not found in Microsoft Graph response');\n }\n\n return email;\n }\n\n /**\n * Create auth provider for Microsoft Graph SDK integration\n *\n * Device code provider ALWAYS uses fixed accountId='device-code'\n * This is by design - device code is a single static identity pattern\n *\n * @param accountId - Account identifier (must be 'device-code' or undefined, otherwise throws error)\n * @returns Auth provider with getAccessToken method\n */\n toAuthProvider(accountId?: string): { getAccessToken: () => Promise<string> } {\n // Device code ONLY works with 'device-code' account ID\n if (accountId !== undefined && accountId !== 'device-code') {\n throw new Error(`DeviceCodeProvider only supports accountId='device-code', got '${accountId}'. Device code uses a single static identity pattern.`);\n }\n\n // ALWAYS use fixed 'device-code' account ID\n const getToken = () => this.getAccessToken('device-code');\n\n return {\n getAccessToken: getToken,\n };\n }\n\n /**\n * Create Microsoft Graph AuthenticationProvider for SDK usage\n *\n * @param accountId - Account identifier\n * @returns AuthenticationProvider that provides access tokens\n */\n private createAuthProvider(accountId?: string): MicrosoftAuthProvider {\n return {\n getAccessToken: async () => {\n return await this.getAccessToken(accountId);\n },\n };\n }\n\n /**\n * Create middleware wrapper for single-user authentication\n *\n * Middleware wraps tool, resource, and prompt handlers and injects authContext into extra parameter.\n * Handlers receive MicrosoftAuthProvider 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 middleware = provider.authMiddleware();\n * const tools = toolFactories.map(f => f()).map(middleware.withToolAuth);\n * const resources = resourceFactories.map(f => f()).map(middleware.withResourceAuth);\n * const prompts = promptFactories.map(f => f()).map(middleware.withPromptAuth);\n *\n * // Tool handler receives auth\n * async function handler({ id }: In, extra: EnrichedExtra) {\n * // extra.authContext.auth is MicrosoftAuthProvider (from middleware)\n * const graph = Client.initWithMiddleware({ authProvider: 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 (defensive: handle arg-less tool pattern)\n // If called with fewer args than expected, use first arg as both args and extra\n let extra: EnrichedExtra;\n if (allArgs.length <= extraPosition) {\n // Arg-less tool pattern: single argument is both args and extra\n extra = (allArgs[0] || {}) as EnrichedExtra;\n allArgs[0] = extra;\n allArgs[extraPosition] = extra;\n } else {\n extra = (allArgs[extraPosition] || {}) as EnrichedExtra;\n allArgs[extraPosition] = extra;\n }\n\n try {\n // Use fixed accountId for storage isolation (like service-account pattern)\n const accountId = 'device-code';\n\n // Create Microsoft Graph authentication provider\n const auth = this.createAuthProvider(accountId);\n\n // Inject authContext and logger into extra parameter\n (extra as { authContext?: AuthContext }).authContext = {\n auth, // MicrosoftAuthProvider for Graph SDK\n accountId, // Account identifier\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 // Wrap auth errors with helpful context\n throw new Error(`Device code authentication failed: ${error instanceof Error ? error.message : String(error)}`);\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":["getToken","setToken","open","fetchWithTimeout","DeviceCodeProvider","startDeviceCodeFlow","accountId","clientId","tenantId","scope","logger","headless","config","deviceCodeEndpoint","debug","endpoint","deviceCodeResponse","method","headers","body","URLSearchParams","client_id","ok","errorText","text","Error","status","deviceCodeData","json","device_code","user_code","verification_uri","verification_uri_complete","expires_in","interval","info","urlToOpen","url","error","message","String","pollForToken","deviceCode","intervalSeconds","service","tokenStore","tokenEndpoint","currentInterval","startTime","Date","now","Promise","resolve","setTimeout","elapsed","Math","floor","response","grant_type","responseData","tokenData","token","accessToken","access_token","refresh_token","refreshToken","expiresAt","errorDescription","error_description","newInterval","refreshAccessToken","isTokenValid","undefined","getAccessToken","effectiveAccountId","storedToken","refreshedToken","getUserEmail","Authorization","userData","email","userPrincipalName","mail","toAuthProvider","createAuthProvider","authMiddleware","wrapAtPosition","module","extraPosition","originalHandler","handler","wrappedHandler","allArgs","extra","length","auth","authContext","withToolAuth","withResourceAuth","withPromptAuth"],"mappings":"AAAA;;;;;;;;;;;;;;CAcC,GAED,SAASA,QAAQ,EAAmCC,QAAQ,QAAQ,eAAe;AAEnF,OAAOC,UAAU,OAAO;AACxB,SAASC,gBAAgB,QAAQ,+BAA+B;AAgDhE;;;;;;;;;;;;;;;;;;;;;;;;;;CA0BC,GACD,OAAO,MAAMC;IAOX;;;;;;;;GAQC,GACD,MAAcC,oBAAoBC,SAAiB,EAAwB;QACzE,MAAM,EAAEC,QAAQ,EAAEC,QAAQ,EAAEC,KAAK,EAAEC,MAAM,EAAEC,QAAQ,EAAE,GAAG,IAAI,CAACC,MAAM;QAEnE,8BAA8B;QAC9B,MAAMC,qBAAqB,CAAC,kCAAkC,EAAEL,SAAS,uBAAuB,CAAC;QACjGE,OAAOI,KAAK,CAAC,0BAA0B;YAAEC,UAAUF;QAAmB;QAEtE,MAAMG,qBAAqB,MAAMb,iBAAiBU,oBAAoB;YACpEI,QAAQ;YACRC,SAAS;gBAAE,gBAAgB;YAAoC;YAC/DC,MAAM,IAAIC,gBAAgB;gBACxBC,WAAWd;gBACXE,OAAOA;YACT;QACF;QAEA,IAAI,CAACO,mBAAmBM,EAAE,EAAE;YAC1B,MAAMC,YAAY,MAAMP,mBAAmBQ,IAAI;YAC/C,MAAM,IAAIC,MAAM,CAAC,iCAAiC,EAAET,mBAAmBU,MAAM,CAAC,GAAG,EAAEH,WAAW;QAChG;QAEA,MAAMI,iBAAkB,MAAMX,mBAAmBY,IAAI;QACrD,MAAM,EAAEC,WAAW,EAAEC,SAAS,EAAEC,gBAAgB,EAAEC,yBAAyB,EAAEC,UAAU,EAAEC,QAAQ,EAAE,GAAGP;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pC,IAAI,CAACA,MAAM,GAAGA;IAChB;AAwYF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/Projects/mcp-z/oauth-microsoft/src/providers/device-code.ts"],"sourcesContent":["/**\n * Device Code OAuth Implementation for Microsoft\n *\n * Implements OAuth 2.0 Device Authorization Grant (RFC 8628) for headless/limited-input devices.\n * Designed for scenarios where interactive browser flows are impractical (SSH sessions, CI/CD, etc.).\n *\n * Flow:\n * 1. Request device code from Microsoft endpoint\n * 2. Display user_code and verification_uri to user\n * 3. Poll token endpoint until user completes authentication\n * 4. Cache access token + refresh token to storage\n * 5. Refresh tokens when expired\n *\n * Similar to service accounts in usage pattern: single static identity, minimal account management.\n */\n\nimport { getToken, type OAuth2TokenStorageProvider, setToken } from '@mcp-z/oauth';\nimport type { Keyv } from 'keyv';\nimport open from 'open';\nimport { fetchWithTimeout } from '../lib/fetch-with-timeout.ts';\nimport type { AuthContext, CachedToken, EnrichedExtra, Logger, MicrosoftAuthProvider, MicrosoftService } from '../types.ts';\n\n/**\n * Device Code Flow Response\n * Response from Microsoft device authorization endpoint\n */\ninterface DeviceCodeResponse {\n device_code: string;\n user_code: string;\n verification_uri: string;\n verification_uri_complete?: string;\n expires_in: number;\n interval: number;\n message?: string;\n}\n\n/**\n * Token Response from Microsoft OAuth endpoint\n */\ninterface TokenResponse {\n access_token: string;\n refresh_token?: string;\n expires_in: number;\n scope?: string;\n token_type?: string;\n}\n\n/**\n * Device Code Provider Configuration\n */\nexport interface DeviceCodeConfig {\n /** Microsoft service type (e.g., 'outlook') */\n service: MicrosoftService;\n /** Azure AD client ID */\n clientId: string;\n /** Azure AD tenant ID */\n tenantId: string;\n /** OAuth scopes to request (space-separated string or array) */\n scope: string;\n /** Logger instance */\n logger: Logger;\n /** Token storage for caching */\n tokenStore: Keyv<unknown>;\n /** Headless mode - print device code instead of opening browser */\n headless: boolean;\n}\n\n/**\n * DeviceCodeProvider implements OAuth2TokenStorageProvider using Microsoft Device Code Flow\n *\n * This provider:\n * - Initiates device code flow with Microsoft endpoint\n * - Displays user_code and verification_uri for manual authentication\n * - Polls token endpoint until user completes auth\n * - Stores access tokens + refresh tokens in Keyv storage\n * - Refreshes tokens when expired\n * - Provides single static identity (minimal account management like service accounts)\n *\n * @example\n * ```typescript\n * const provider = new DeviceCodeProvider({\n * service: 'outlook',\n * clientId: 'your-client-id',\n * tenantId: 'common',\n * scope: 'https://graph.microsoft.com/Mail.Read',\n * logger: console,\n * tokenStore: new Keyv(),\n * headless: true,\n * });\n *\n * // Get authenticated Microsoft Graph client\n * const token = await provider.getAccessToken('default');\n * ```\n */\nexport class DeviceCodeProvider implements OAuth2TokenStorageProvider {\n private config: DeviceCodeConfig;\n\n constructor(config: DeviceCodeConfig) {\n this.config = config;\n }\n\n /**\n * Start device code flow and poll for token\n *\n * 1. POST to /devicecode endpoint to get device_code and user_code\n * 2. Display verification instructions to user\n * 3. Poll /token endpoint every interval seconds\n * 4. Handle authorization_pending, slow_down, expired_token errors\n * 5. Return token when user completes authentication\n */\n private async startDeviceCodeFlow(accountId: string): Promise<CachedToken> {\n const { clientId, tenantId, scope, logger, headless } = this.config;\n\n // Step 1: Request device code\n const deviceCodeEndpoint = `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/devicecode`;\n logger.debug('Requesting device code', { endpoint: deviceCodeEndpoint });\n\n const deviceCodeResponse = await fetchWithTimeout(deviceCodeEndpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n client_id: clientId,\n scope,\n }),\n });\n\n if (!deviceCodeResponse.ok) {\n const errorText = await deviceCodeResponse.text();\n throw new Error(`Device code request failed (HTTP ${deviceCodeResponse.status}): ${errorText}`);\n }\n\n const deviceCodeData = (await deviceCodeResponse.json()) as DeviceCodeResponse;\n const { device_code, user_code, verification_uri, verification_uri_complete, expires_in, interval } = deviceCodeData;\n\n // Step 2: Display instructions to user\n logger.info('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');\n logger.info('Device code authentication required');\n logger.info('');\n logger.info(`Please visit: ${verification_uri_complete || verification_uri}`);\n logger.info(`And enter code: ${user_code}`);\n logger.info('');\n logger.info(`Code expires in ${expires_in} seconds`);\n logger.info('Waiting for authentication...');\n logger.info('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');\n\n // Optional: Open browser in non-headless mode\n if (!headless) {\n const urlToOpen = verification_uri_complete || verification_uri;\n try {\n await open(urlToOpen);\n logger.debug('Opened browser to verification URL', { url: urlToOpen });\n } catch (error) {\n logger.debug('Failed to open browser', { error: error instanceof Error ? error.message : String(error) });\n }\n }\n\n // Step 3: Poll token endpoint\n return await this.pollForToken(device_code, interval || 5, accountId);\n }\n\n /**\n * Poll Microsoft token endpoint until user completes authentication\n *\n * Handles Microsoft-specific error codes:\n * - authorization_pending: User hasn't completed auth yet, keep polling\n * - slow_down: Increase polling interval by 5 seconds\n * - authorization_declined: User denied authorization\n * - expired_token: Device code expired (typically after 15 minutes)\n */\n private async pollForToken(deviceCode: string, intervalSeconds: number, accountId: string): Promise<CachedToken> {\n const { clientId, tenantId, logger, service, tokenStore } = this.config;\n const tokenEndpoint = `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`;\n\n let currentInterval = intervalSeconds;\n const startTime = Date.now();\n\n while (true) {\n // Wait for polling interval\n await new Promise((resolve) => setTimeout(resolve, currentInterval * 1000));\n\n logger.debug('Polling for token', { elapsed: Math.floor((Date.now() - startTime) / 1000), interval: currentInterval });\n\n const response = await fetchWithTimeout(tokenEndpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: 'urn:ietf:params:oauth:grant-type:device_code',\n client_id: clientId,\n device_code: deviceCode,\n }),\n });\n\n const responseData = (await response.json()) as TokenResponse & { error?: string; error_description?: string };\n\n if (response.ok) {\n // Success! Convert to CachedToken and store\n const tokenData = responseData as TokenResponse;\n const token: CachedToken = {\n accessToken: tokenData.access_token,\n ...(tokenData.refresh_token && { refreshToken: tokenData.refresh_token }),\n expiresAt: Date.now() + (tokenData.expires_in - 60) * 1000, // 60s safety margin\n ...(tokenData.scope && { scope: tokenData.scope }),\n };\n\n // Cache token to storage\n await setToken(tokenStore, { accountId, service }, token);\n logger.info('Device code authentication successful', { accountId });\n\n return token;\n }\n\n // Handle error responses\n const error = responseData.error;\n const errorDescription = responseData.error_description || '';\n\n if (error === 'authorization_pending') {\n // User hasn't completed auth yet - continue polling\n logger.debug('Authorization pending, waiting for user...');\n continue;\n }\n\n if (error === 'slow_down') {\n // Microsoft wants us to slow down polling\n currentInterval += 5;\n logger.debug('Received slow_down, increasing interval', { newInterval: currentInterval });\n continue;\n }\n\n if (error === 'authorization_declined') {\n throw new Error('User declined authorization. Please restart the authentication flow.');\n }\n\n if (error === 'expired_token') {\n throw new Error('Device code expired. Please restart the authentication flow.');\n }\n\n // Unknown error\n throw new Error(`Device code flow failed: ${error} - ${errorDescription}`);\n }\n }\n\n /**\n * Refresh expired access token using refresh token\n *\n * @param refreshToken - Refresh token from previous authentication\n * @returns New cached token with fresh access token\n */\n private async refreshAccessToken(refreshToken: string): Promise<CachedToken> {\n const { clientId, tenantId, scope, logger } = this.config;\n const tokenEndpoint = `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`;\n\n logger.debug('Refreshing access token');\n\n const response = await fetchWithTimeout(tokenEndpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: 'refresh_token',\n client_id: clientId,\n refresh_token: refreshToken,\n scope,\n }),\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Token refresh failed (HTTP ${response.status}): ${errorText}`);\n }\n\n const tokenData = (await response.json()) as TokenResponse;\n\n return {\n accessToken: tokenData.access_token,\n refreshToken: tokenData.refresh_token || refreshToken, // Some responses may not include new refresh token\n expiresAt: Date.now() + (tokenData.expires_in - 60) * 1000, // 60s safety margin\n scope: tokenData.scope || scope,\n };\n }\n\n /**\n * Check if token is still valid (not expired)\n */\n private isTokenValid(token: CachedToken): boolean {\n return token.expiresAt !== undefined && token.expiresAt > Date.now();\n }\n\n /**\n * Get access token for Microsoft Graph API\n *\n * Flow:\n * 1. Check token storage\n * 2. If valid token exists, return it\n * 3. If expired but has refresh token, try refresh\n * 4. Otherwise, start new device code flow\n *\n * @param accountId - Account identifier. Defaults to 'device-code' (fixed identifier for device code flow).\n * @returns Access token for API requests\n */\n async getAccessToken(accountId?: string): Promise<string> {\n const { logger, service, tokenStore } = this.config;\n const effectiveAccountId = accountId ?? 'device-code';\n\n logger.debug('Getting access token', { service, accountId: effectiveAccountId });\n\n // Check storage for cached token\n const storedToken = await getToken<CachedToken>(tokenStore, { accountId: effectiveAccountId, service });\n\n if (storedToken && this.isTokenValid(storedToken)) {\n logger.debug('Using stored access token', { accountId: effectiveAccountId });\n return storedToken.accessToken;\n }\n\n // If stored token expired but has refresh token, try refresh\n if (storedToken?.refreshToken) {\n try {\n logger.info('Refreshing expired access token', { accountId: effectiveAccountId });\n const refreshedToken = await this.refreshAccessToken(storedToken.refreshToken);\n await setToken(tokenStore, { accountId: effectiveAccountId, service }, refreshedToken);\n return refreshedToken.accessToken;\n } catch (error) {\n logger.info('Token refresh failed', {\n accountId: effectiveAccountId,\n error: error instanceof Error ? error.message : String(error),\n });\n // In headless mode, cannot start interactive device code flow\n if (this.config.headless) {\n throw new Error(`Token refresh failed in headless mode. Cannot start interactive device code flow. Error: ${error instanceof Error ? error.message : String(error)}`);\n }\n // Fall through to new device code flow (interactive mode only)\n }\n }\n\n // No valid token - check if we can start device code flow\n if (this.config.headless) {\n throw new Error('No valid token available in headless mode. Device code flow requires user interaction. ' + 'Please run authentication flow interactively first or provide valid tokens.');\n }\n\n // Interactive mode - start device code flow\n logger.info('Starting device code flow', { accountId: effectiveAccountId });\n const token = await this.startDeviceCodeFlow(effectiveAccountId);\n return token.accessToken;\n }\n\n /**\n * Get user email from Microsoft Graph /me endpoint (pure query)\n *\n * @param accountId - Account identifier\n * @returns User's email address (userPrincipalName or mail field)\n */\n async getUserEmail(accountId?: string): Promise<string> {\n const { logger } = this.config;\n // Device code is single-account mode\n const token = await this.getAccessToken(accountId);\n\n logger.debug('Fetching user email from Microsoft Graph');\n\n const response = await fetchWithTimeout('https://graph.microsoft.com/v1.0/me', {\n headers: { Authorization: `Bearer ${token}` },\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Failed to get user email (HTTP ${response.status}): ${errorText}`);\n }\n\n const userData = (await response.json()) as { userPrincipalName?: string; mail?: string };\n const email = userData.userPrincipalName || userData.mail;\n\n if (!email) {\n throw new Error('User email not found in Microsoft Graph response');\n }\n\n return email;\n }\n\n /**\n * Create auth provider for Microsoft Graph SDK integration\n *\n * Device code provider ALWAYS uses fixed accountId='device-code'\n * This is by design - device code is a single static identity pattern\n *\n * @param accountId - Account identifier (must be 'device-code' or undefined, otherwise throws error)\n * @returns Auth provider with getAccessToken method\n */\n toAuthProvider(accountId?: string): { getAccessToken: () => Promise<string> } {\n // Device code ONLY works with 'device-code' account ID\n if (accountId !== undefined && accountId !== 'device-code') {\n throw new Error(`DeviceCodeProvider only supports accountId='device-code', got '${accountId}'. Device code uses a single static identity pattern.`);\n }\n\n // ALWAYS use fixed 'device-code' account ID\n const getToken = () => this.getAccessToken('device-code');\n\n return {\n getAccessToken: getToken,\n };\n }\n\n /**\n * Create Microsoft Graph AuthenticationProvider for SDK usage\n *\n * @param accountId - Account identifier\n * @returns AuthenticationProvider that provides access tokens\n */\n private createAuthProvider(accountId?: string): MicrosoftAuthProvider {\n return {\n getAccessToken: async () => {\n return await this.getAccessToken(accountId);\n },\n };\n }\n\n /**\n * Create middleware wrapper for single-user authentication\n *\n * Middleware wraps tool, resource, and prompt handlers and injects authContext into extra parameter.\n * Handlers receive MicrosoftAuthProvider 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 middleware = provider.authMiddleware();\n * const tools = toolFactories.map(f => f()).map(middleware.withToolAuth);\n * const resources = resourceFactories.map(f => f()).map(middleware.withResourceAuth);\n * const prompts = promptFactories.map(f => f()).map(middleware.withPromptAuth);\n *\n * // Tool handler receives auth\n * async function handler({ id }: In, extra: EnrichedExtra) {\n * // extra.authContext.auth is MicrosoftAuthProvider (from middleware)\n * const graph = Client.initWithMiddleware({ authProvider: 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 (defensive: handle arg-less tool pattern)\n // If called with fewer args than expected, use first arg as both args and extra\n let extra: EnrichedExtra;\n if (allArgs.length <= extraPosition) {\n // Arg-less tool pattern: single argument is both args and extra\n extra = (allArgs[0] || {}) as EnrichedExtra;\n allArgs[0] = extra;\n allArgs[extraPosition] = extra;\n } else {\n extra = (allArgs[extraPosition] || {}) as EnrichedExtra;\n allArgs[extraPosition] = extra;\n }\n\n try {\n // Use fixed accountId for storage isolation (like service-account pattern)\n const accountId = 'device-code';\n\n // Create Microsoft Graph authentication provider\n const auth = this.createAuthProvider(accountId);\n\n // Inject authContext and logger into extra parameter\n (extra as { authContext?: AuthContext }).authContext = {\n auth, // MicrosoftAuthProvider for Graph SDK\n accountId, // Account identifier\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 // Wrap auth errors with helpful context\n throw new Error(`Device code authentication failed: ${error instanceof Error ? error.message : String(error)}`);\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":["getToken","setToken","open","fetchWithTimeout","DeviceCodeProvider","startDeviceCodeFlow","accountId","clientId","tenantId","scope","logger","headless","config","deviceCodeEndpoint","debug","endpoint","deviceCodeResponse","method","headers","body","URLSearchParams","client_id","ok","errorText","text","Error","status","deviceCodeData","json","device_code","user_code","verification_uri","verification_uri_complete","expires_in","interval","info","urlToOpen","url","error","message","String","pollForToken","deviceCode","intervalSeconds","service","tokenStore","tokenEndpoint","currentInterval","startTime","Date","now","Promise","resolve","setTimeout","elapsed","Math","floor","response","grant_type","responseData","tokenData","token","accessToken","access_token","refresh_token","refreshToken","expiresAt","errorDescription","error_description","newInterval","refreshAccessToken","isTokenValid","undefined","getAccessToken","effectiveAccountId","storedToken","refreshedToken","getUserEmail","Authorization","userData","email","userPrincipalName","mail","toAuthProvider","createAuthProvider","authMiddleware","wrapAtPosition","module","extraPosition","originalHandler","handler","wrappedHandler","allArgs","extra","length","auth","authContext","withToolAuth","withResourceAuth","withPromptAuth"],"mappings":"AAAA;;;;;;;;;;;;;;CAcC,GAED,SAASA,QAAQ,EAAmCC,QAAQ,QAAQ,eAAe;AAEnF,OAAOC,UAAU,OAAO;AACxB,SAASC,gBAAgB,QAAQ,+BAA+B;AAgDhE;;;;;;;;;;;;;;;;;;;;;;;;;;CA0BC,GACD,OAAO,MAAMC;IAOX;;;;;;;;GAQC,GACD,MAAcC,oBAAoBC,SAAiB,EAAwB;QACzE,MAAM,EAAEC,QAAQ,EAAEC,QAAQ,EAAEC,KAAK,EAAEC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Y;oBAElB,iDAAiD;oBACjD,MAAMyF,OAAO,IAAI,CAACX,kBAAkB,CAAC9E;oBAErC,qDAAqD;oBACpDuF,MAAwCG,WAAW,GAAG;wBACrDD;wBACAzF;oBACF;oBACCuF,MAA+BnF,MAAM,GAAG,IAAI,CAACE,MAAM,CAACF,MAAM;oBAE3D,sCAAsC;oBACtC,OAAO,MAAM+E,mBAAmBG;gBAClC,EAAE,OAAOtD,OAAO;oBACd,wCAAwC;oBACxC,MAAM,IAAIb,MAAM,CAAC,mCAAmC,EAAEa,iBAAiBb,QAAQa,MAAMC,OAAO,GAAGC,OAAOF,QAAQ;gBAChH;YACF;YAEA,OAAO;gBACL,GAAGiD,MAAM;gBACTG,SAASC;YACX;QACF;QAEA,OAAO;YACL,4EAA4E;YAC5E,wDAAwD;YACxDM,cAAc,CAAgEV,SAAcD,eAAeC,QAAQ;YACnHW,kBAAkB,CAAqFX,SAAcD,eAAeC,QAAQ;YAC5IY,gBAAgB,CAAgEZ,SAAcD,eAAeC,QAAQ;QACvH;IACF;IAzYA,YAAY3E,MAAwB,CAAE;QACpC,IAAI,CAACA,MAAM,GAAGA;IAChB;AAwYF"}
@@ -13,9 +13,19 @@
13
13
  * 5. Handle callback, exchange code for token
14
14
  * 6. Cache token to storage
15
15
  * 7. Close ephemeral server
16
+ *
17
+ * CHANGE (2026-01-03):
18
+ * - Non-headless mode now opens the auth URL AND blocks (polls) until tokens are available,
19
+ * for BOTH redirectUri (persistent) and ephemeral (loopback) modes.
20
+ * - Ephemeral flow no longer calls `open()` itself. Instead it:
21
+ * 1) starts the loopback callback server
22
+ * 2) throws AuthRequiredError(auth_url)
23
+ * - Middleware catches AuthRequiredError(auth_url):
24
+ * - if not headless: open(url) once + poll pending state until callback completes (or timeout)
25
+ * - then retries token acquisition and injects authContext in the SAME tool call.
16
26
  */
17
27
  import { type OAuth2TokenStorageProvider } from '@mcp-z/oauth';
18
- import { type LoopbackOAuthConfig } from '../types.js';
28
+ import { type CachedToken, type LoopbackOAuthConfig } from '../types.js';
19
29
  /**
20
30
  * Loopback OAuth Client (RFC 8252 Section 7.3)
21
31
  *
@@ -27,6 +37,7 @@ import { type LoopbackOAuthConfig } from '../types.js';
27
37
  */
28
38
  export declare class LoopbackOAuthProvider implements OAuth2TokenStorageProvider {
29
39
  private config;
40
+ private openedStates;
30
41
  constructor(config: LoopbackOAuthConfig);
31
42
  /**
32
43
  * Get access token from Keyv using compound key
@@ -44,14 +55,6 @@ export declare class LoopbackOAuthProvider implements OAuth2TokenStorageProvider
44
55
  toAuthProvider(accountId?: string): {
45
56
  getAccessToken: () => Promise<string>;
46
57
  };
47
- /**
48
- * Authenticate new account with OAuth flow
49
- * Triggers account selection, stores token, registers account
50
- *
51
- * @returns Email address of newly authenticated account
52
- * @throws Error in headless mode (cannot open browser for OAuth)
53
- */
54
- authenticateNewAccount(): Promise<string>;
55
58
  /**
56
59
  * Get user email from Microsoft Graph API (pure query)
57
60
  * Used to query email for existing authenticated account
@@ -60,14 +63,6 @@ export declare class LoopbackOAuthProvider implements OAuth2TokenStorageProvider
60
63
  * @returns User's email address
61
64
  */
62
65
  getUserEmail(accountId?: string): Promise<string>;
63
- /**
64
- * Check for existing accounts in token storage (incremental OAuth detection)
65
- *
66
- * Uses key-utils helper for forward compatibility with key format changes.
67
- *
68
- * @returns Array of account IDs that have tokens for this service
69
- */
70
- private getExistingAccounts;
71
66
  private isTokenValid;
72
67
  /**
73
68
  * Fetch user email from Microsoft Graph using access token
@@ -77,9 +72,89 @@ export declare class LoopbackOAuthProvider implements OAuth2TokenStorageProvider
77
72
  * @returns User's email address (mail field or userPrincipalName fallback)
78
73
  */
79
74
  private fetchUserEmailFromToken;
80
- private performEphemeralOAuthFlow;
75
+ /**
76
+ * Build Microsoft OAuth authorization URL with the "most parameters" baseline.
77
+ * This is shared by BOTH persistent (redirectUri) and ephemeral (loopback) modes.
78
+ */
79
+ private buildAuthUrl;
80
+ /**
81
+ * Create a cached token + email from an authorization code.
82
+ * This is the shared callback handler for BOTH persistent and ephemeral modes.
83
+ */
84
+ private handleAuthorizationCode;
85
+ /**
86
+ * Store token + account metadata. Shared by BOTH persistent and ephemeral modes.
87
+ */
88
+ private persistAuthResult;
89
+ /**
90
+ * Pending auth (PKCE verifier) key format.
91
+ */
92
+ private pendingKey;
93
+ /**
94
+ * Store PKCE verifier for callback (5 minute TTL).
95
+ * Shared by BOTH persistent and ephemeral modes.
96
+ */
97
+ private createPendingAuth;
98
+ /**
99
+ * Load and validate pending auth state (5 minute TTL).
100
+ * Shared by BOTH persistent and ephemeral modes.
101
+ */
102
+ private readAndValidatePendingAuth;
103
+ /**
104
+ * Mark pending auth as completed (used by middleware polling).
105
+ */
106
+ private markPendingComplete;
107
+ /**
108
+ * Clean up pending auth state.
109
+ */
110
+ private deletePendingAuth;
111
+ /**
112
+ * Wait until pending auth is marked completed (or timeout).
113
+ * Used by middleware after opening auth URL in non-headless mode.
114
+ */
115
+ private waitForOAuthCompletion;
116
+ /**
117
+ * Process an OAuth callback using shared state validation + token exchange + persistence.
118
+ * Used by BOTH:
119
+ * - ephemeral loopback server callback handler
120
+ * - persistent redirectUri callback handler
121
+ *
122
+ * IMPORTANT CHANGE:
123
+ * - We do NOT delete pending state here anymore.
124
+ * - We mark it completed so middleware can poll and then clean it up.
125
+ */
126
+ private processOAuthCallback;
127
+ /**
128
+ * Loopback OAuth server helper (RFC 8252 Section 7.3)
129
+ *
130
+ * Implements ephemeral local server with OS-assigned port (RFC 8252 Section 8.3).
131
+ * Shared callback handling uses:
132
+ * - the same authUrl builder as redirectUri mode
133
+ * - the same pending PKCE verifier storage as redirectUri mode
134
+ * - the same callback processor as redirectUri mode
135
+ */
136
+ private createOAuthCallbackServer;
137
+ /**
138
+ * Starts the ephemeral loopback server and returns an AuthRequiredError(auth_url).
139
+ * Middleware will open+poll and then retry in the same call.
140
+ */
141
+ private startEphemeralOAuthFlow;
81
142
  private exchangeCodeForToken;
82
143
  private refreshAccessToken;
144
+ /**
145
+ * Handle OAuth callback from persistent endpoint.
146
+ * Used by HTTP servers with configured redirectUri.
147
+ *
148
+ * @param params - OAuth callback parameters
149
+ * @returns Email and cached token
150
+ */
151
+ handleOAuthCallback(params: {
152
+ code: string;
153
+ state?: string;
154
+ }): Promise<{
155
+ email: string;
156
+ token: CachedToken;
157
+ }>;
83
158
  /**
84
159
  * Create auth middleware for single-user context (single active account per service)
85
160
  *