@mcp-z/oauth-google 1.0.0

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 (89) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +93 -0
  3. package/dist/cjs/index.d.cts +16 -0
  4. package/dist/cjs/index.d.ts +16 -0
  5. package/dist/cjs/index.js +112 -0
  6. package/dist/cjs/index.js.map +1 -0
  7. package/dist/cjs/lib/dcr-router.d.cts +44 -0
  8. package/dist/cjs/lib/dcr-router.d.ts +44 -0
  9. package/dist/cjs/lib/dcr-router.js +1189 -0
  10. package/dist/cjs/lib/dcr-router.js.map +1 -0
  11. package/dist/cjs/lib/dcr-utils.d.cts +160 -0
  12. package/dist/cjs/lib/dcr-utils.d.ts +160 -0
  13. package/dist/cjs/lib/dcr-utils.js +860 -0
  14. package/dist/cjs/lib/dcr-utils.js.map +1 -0
  15. package/dist/cjs/lib/dcr-verify.d.cts +53 -0
  16. package/dist/cjs/lib/dcr-verify.d.ts +53 -0
  17. package/dist/cjs/lib/dcr-verify.js +193 -0
  18. package/dist/cjs/lib/dcr-verify.js.map +1 -0
  19. package/dist/cjs/lib/fetch-with-timeout.d.cts +14 -0
  20. package/dist/cjs/lib/fetch-with-timeout.d.ts +14 -0
  21. package/dist/cjs/lib/fetch-with-timeout.js +257 -0
  22. package/dist/cjs/lib/fetch-with-timeout.js.map +1 -0
  23. package/dist/cjs/lib/token-verifier.d.cts +44 -0
  24. package/dist/cjs/lib/token-verifier.d.ts +44 -0
  25. package/dist/cjs/lib/token-verifier.js +253 -0
  26. package/dist/cjs/lib/token-verifier.js.map +1 -0
  27. package/dist/cjs/package.json +1 -0
  28. package/dist/cjs/providers/dcr.d.cts +107 -0
  29. package/dist/cjs/providers/dcr.d.ts +107 -0
  30. package/dist/cjs/providers/dcr.js +584 -0
  31. package/dist/cjs/providers/dcr.js.map +1 -0
  32. package/dist/cjs/providers/loopback-oauth.d.cts +119 -0
  33. package/dist/cjs/providers/loopback-oauth.d.ts +119 -0
  34. package/dist/cjs/providers/loopback-oauth.js +1334 -0
  35. package/dist/cjs/providers/loopback-oauth.js.map +1 -0
  36. package/dist/cjs/providers/service-account.d.cts +131 -0
  37. package/dist/cjs/providers/service-account.d.ts +131 -0
  38. package/dist/cjs/providers/service-account.js +800 -0
  39. package/dist/cjs/providers/service-account.js.map +1 -0
  40. package/dist/cjs/schemas/index.d.cts +20 -0
  41. package/dist/cjs/schemas/index.d.ts +20 -0
  42. package/dist/cjs/schemas/index.js +37 -0
  43. package/dist/cjs/schemas/index.js.map +1 -0
  44. package/dist/cjs/setup/config.d.cts +112 -0
  45. package/dist/cjs/setup/config.d.ts +112 -0
  46. package/dist/cjs/setup/config.js +236 -0
  47. package/dist/cjs/setup/config.js.map +1 -0
  48. package/dist/cjs/types.d.cts +173 -0
  49. package/dist/cjs/types.d.ts +173 -0
  50. package/dist/cjs/types.js +16 -0
  51. package/dist/cjs/types.js.map +1 -0
  52. package/dist/esm/index.d.ts +16 -0
  53. package/dist/esm/index.js +16 -0
  54. package/dist/esm/index.js.map +1 -0
  55. package/dist/esm/lib/dcr-router.d.ts +44 -0
  56. package/dist/esm/lib/dcr-router.js +515 -0
  57. package/dist/esm/lib/dcr-router.js.map +1 -0
  58. package/dist/esm/lib/dcr-utils.d.ts +160 -0
  59. package/dist/esm/lib/dcr-utils.js +270 -0
  60. package/dist/esm/lib/dcr-utils.js.map +1 -0
  61. package/dist/esm/lib/dcr-verify.d.ts +53 -0
  62. package/dist/esm/lib/dcr-verify.js +53 -0
  63. package/dist/esm/lib/dcr-verify.js.map +1 -0
  64. package/dist/esm/lib/fetch-with-timeout.d.ts +14 -0
  65. package/dist/esm/lib/fetch-with-timeout.js +30 -0
  66. package/dist/esm/lib/fetch-with-timeout.js.map +1 -0
  67. package/dist/esm/lib/token-verifier.d.ts +44 -0
  68. package/dist/esm/lib/token-verifier.js +53 -0
  69. package/dist/esm/lib/token-verifier.js.map +1 -0
  70. package/dist/esm/package.json +1 -0
  71. package/dist/esm/providers/dcr.d.ts +107 -0
  72. package/dist/esm/providers/dcr.js +242 -0
  73. package/dist/esm/providers/dcr.js.map +1 -0
  74. package/dist/esm/providers/loopback-oauth.d.ts +119 -0
  75. package/dist/esm/providers/loopback-oauth.js +639 -0
  76. package/dist/esm/providers/loopback-oauth.js.map +1 -0
  77. package/dist/esm/providers/service-account.d.ts +131 -0
  78. package/dist/esm/providers/service-account.js +353 -0
  79. package/dist/esm/providers/service-account.js.map +1 -0
  80. package/dist/esm/schemas/index.d.ts +20 -0
  81. package/dist/esm/schemas/index.js +18 -0
  82. package/dist/esm/schemas/index.js.map +1 -0
  83. package/dist/esm/setup/config.d.ts +112 -0
  84. package/dist/esm/setup/config.js +258 -0
  85. package/dist/esm/setup/config.js.map +1 -0
  86. package/dist/esm/types.d.ts +173 -0
  87. package/dist/esm/types.js +6 -0
  88. package/dist/esm/types.js.map +1 -0
  89. package/package.json +89 -0
@@ -0,0 +1,20 @@
1
+ import { z } from 'zod';
2
+ export declare const AuthRequiredBranchSchema: z.ZodObject<{
3
+ type: z.ZodLiteral<"auth_required">;
4
+ provider: z.ZodString;
5
+ message: z.ZodString;
6
+ url: z.ZodOptional<z.ZodString>;
7
+ }, z.core.$strip>;
8
+ export type AuthRequiredBranch = z.infer<typeof AuthRequiredBranchSchema>;
9
+ export declare const AuthRequiredSchema: z.ZodObject<{
10
+ type: z.ZodLiteral<"auth_required">;
11
+ provider: z.ZodString;
12
+ message: z.ZodString;
13
+ url: z.ZodString;
14
+ flow: z.ZodOptional<z.ZodString>;
15
+ instructions: z.ZodString;
16
+ user_code: z.ZodOptional<z.ZodString>;
17
+ expires_in: z.ZodOptional<z.ZodNumber>;
18
+ accountId: z.ZodOptional<z.ZodString>;
19
+ }, z.core.$strip>;
20
+ export type AuthRequired = z.infer<typeof AuthRequiredSchema>;
@@ -0,0 +1,18 @@
1
+ import { z } from 'zod';
2
+ export const AuthRequiredBranchSchema = z.object({
3
+ type: z.literal('auth_required'),
4
+ provider: z.string(),
5
+ message: z.string(),
6
+ url: z.string().optional()
7
+ });
8
+ export const AuthRequiredSchema = z.object({
9
+ type: z.literal('auth_required'),
10
+ provider: z.string().describe('OAuth provider name (e.g., "google")'),
11
+ message: z.string().describe('Human-readable message explaining why auth is needed'),
12
+ url: z.string().url().describe('Authentication URL to open in browser'),
13
+ flow: z.string().optional().describe('Authentication flow type (e.g., "auth_url", "device_code")'),
14
+ instructions: z.string().describe('Clear instructions for the user'),
15
+ user_code: z.string().optional().describe('Code user must enter at verification URL (device flows only)'),
16
+ expires_in: z.number().optional().describe('Seconds until code expires (device flows only)'),
17
+ accountId: z.string().optional().describe('Account identifier (email) that requires authentication')
18
+ }).describe('Authentication required with clear actionable instructions for user');
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/Users/kevin/Dev/Projects/ai/mcp-z/oauth/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"}
@@ -0,0 +1,112 @@
1
+ /**
2
+ * Google OAuth configuration parsing from CLI arguments and environment variables.
3
+ *
4
+ * This module provides utilities to parse Google OAuth configuration from
5
+ * CLI arguments and environment variables, following the same pattern as @mcp-z/server's
6
+ * parseConfig().
7
+ */
8
+ import type { DcrConfig, OAuthConfig } from '../types.js';
9
+ export type { DcrConfig, OAuthConfig };
10
+ /**
11
+ * Transport type for MCP servers
12
+ */
13
+ type TransportType = 'stdio' | 'http';
14
+ /**
15
+ * Parse Google OAuth configuration from CLI arguments and environment variables.
16
+ *
17
+ * CLI Arguments:
18
+ * - --auth: Auth mode ('loopback-oauth' | 'service-account' | 'dcr')
19
+ * - Default: 'loopback-oauth' (if flag is omitted)
20
+ * - --headless: Disable browser opening for OAuth flow (default: false, true in test env)
21
+ * - --redirect-uri: Override OAuth redirect URI (default: ephemeral loopback)
22
+ * - --service-account-key-file: Service account key file path (required for service-account mode)
23
+ *
24
+ * Required environment variables:
25
+ * - GOOGLE_CLIENT_ID: OAuth 2.0 client ID from Google Cloud Console
26
+ *
27
+ * Optional environment variables:
28
+ * - GOOGLE_CLIENT_SECRET: OAuth 2.0 client secret (optional for public clients)
29
+ * - AUTH_MODE: Auth mode (same format as --auth flag)
30
+ * - HEADLESS: Headless mode flag ('true' to enable)
31
+ * - REDIRECT_URI: OAuth redirect URI (overridden by --redirect-uri CLI flag)
32
+ * - GOOGLE_SERVICE_ACCOUNT_KEY_FILE: Service account key file (for service-account mode)
33
+ *
34
+ * @param args - CLI arguments array (typically process.argv)
35
+ * @param env - Environment variables object (typically process.env)
36
+ * @param transport - Optional transport type. If 'stdio' and auth mode is 'dcr', throws an error.
37
+ * @returns Parsed Google OAuth configuration
38
+ * @throws Error if required environment variables are missing, values are invalid, or DCR is used with stdio transport
39
+ *
40
+ * @example Default mode (no flags)
41
+ * ```typescript
42
+ * const config = parseConfig(process.argv, process.env);
43
+ * // { auth: 'loopback-oauth' }
44
+ * ```
45
+ *
46
+ * @example Override auth mode
47
+ * ```typescript
48
+ * parseConfig(['--auth=loopback-oauth'], process.env);
49
+ * parseConfig(['--auth=service-account'], process.env);
50
+ * parseConfig(['--auth=dcr'], process.env);
51
+ * ```
52
+ *
53
+ * @example With transport validation
54
+ * ```typescript
55
+ * parseConfig(['--auth=dcr'], process.env, 'http'); // OK
56
+ * parseConfig(['--auth=dcr'], process.env, 'stdio'); // Throws error
57
+ * ```
58
+ *
59
+ * Valid auth modes:
60
+ * - loopback-oauth (default)
61
+ * - service-account
62
+ * - dcr (HTTP transport only)
63
+ */
64
+ export declare function parseConfig(args: string[], env: Record<string, string | undefined>, transport?: TransportType): OAuthConfig;
65
+ /**
66
+ * Build production configuration from process globals.
67
+ * Entry point for production server.
68
+ */
69
+ export declare function createConfig(): OAuthConfig;
70
+ /**
71
+ * Parse DCR configuration from CLI arguments and environment variables.
72
+ *
73
+ * CLI Arguments:
74
+ * - --dcr-mode: DCR mode ('self-hosted' | 'external')
75
+ * - Default: 'self-hosted' (if flag is omitted)
76
+ * - --dcr-verify-url: External verification endpoint URL (required for external mode)
77
+ * - --dcr-store-uri: DCR client storage URI (required for self-hosted mode)
78
+ *
79
+ * Required environment variables:
80
+ * - GOOGLE_CLIENT_ID: OAuth 2.0 client ID from Google Cloud Console
81
+ *
82
+ * Optional environment variables:
83
+ * - GOOGLE_CLIENT_SECRET: OAuth 2.0 client secret (optional for public clients)
84
+ * - DCR_MODE: DCR mode (same format as --dcr-mode flag)
85
+ * - DCR_VERIFY_URL: External verification URL (same as --dcr-verify-url flag)
86
+ * - DCR_STORE_URI: DCR storage URI (same as --dcr-store-uri flag)
87
+ *
88
+ * @param args - CLI arguments array (typically process.argv)
89
+ * @param env - Environment variables object (typically process.env)
90
+ * @param scope - OAuth scopes to request (space-separated)
91
+ * @returns Parsed DCR configuration
92
+ * @throws Error if required environment variables are missing or validation fails
93
+ *
94
+ * @example Self-hosted mode
95
+ * ```typescript
96
+ * const config = parseDcrConfig(
97
+ * ['--dcr-mode=self-hosted', '--dcr-store-uri=file:///path/to/store.json'],
98
+ * process.env,
99
+ * 'https://www.googleapis.com/auth/drive.readonly'
100
+ * );
101
+ * ```
102
+ *
103
+ * @example External mode
104
+ * ```typescript
105
+ * const config = parseDcrConfig(
106
+ * ['--dcr-mode=external', '--dcr-verify-url=https://auth0.example.com/verify'],
107
+ * process.env,
108
+ * 'https://www.googleapis.com/auth/drive.readonly'
109
+ * );
110
+ * ```
111
+ */
112
+ export declare function parseDcrConfig(args: string[], env: Record<string, string | undefined>, scope: string): DcrConfig;
@@ -0,0 +1,258 @@
1
+ /**
2
+ * Google OAuth configuration parsing from CLI arguments and environment variables.
3
+ *
4
+ * This module provides utilities to parse Google OAuth configuration from
5
+ * CLI arguments and environment variables, following the same pattern as @mcp-z/server's
6
+ * parseConfig().
7
+ */ import { resolve } from 'path';
8
+ import { parseArgs } from 'util';
9
+ /**
10
+ * Parse auth mode string into auth mode.
11
+ *
12
+ * @param value - Auth mode string ('loopback-oauth', 'service-account', or 'dcr')
13
+ * @returns Parsed auth mode
14
+ * @throws Error if value is invalid
15
+ *
16
+ * @example Valid formats
17
+ * ```typescript
18
+ * parseAuthMode('loopback-oauth') // { auth: 'loopback-oauth' }
19
+ * parseAuthMode('service-account') // { auth: 'service-account' }
20
+ * parseAuthMode('dcr') // { auth: 'dcr' }
21
+ * ```
22
+ */ function parseAuthMode(value) {
23
+ if (value !== 'loopback-oauth' && value !== 'service-account' && value !== 'dcr') {
24
+ throw new Error(`Invalid --auth value: "${value}". Valid values: loopback-oauth, service-account, dcr`);
25
+ }
26
+ return {
27
+ auth: value
28
+ };
29
+ }
30
+ /**
31
+ * Parse Google OAuth configuration from CLI arguments and environment variables.
32
+ *
33
+ * CLI Arguments:
34
+ * - --auth: Auth mode ('loopback-oauth' | 'service-account' | 'dcr')
35
+ * - Default: 'loopback-oauth' (if flag is omitted)
36
+ * - --headless: Disable browser opening for OAuth flow (default: false, true in test env)
37
+ * - --redirect-uri: Override OAuth redirect URI (default: ephemeral loopback)
38
+ * - --service-account-key-file: Service account key file path (required for service-account mode)
39
+ *
40
+ * Required environment variables:
41
+ * - GOOGLE_CLIENT_ID: OAuth 2.0 client ID from Google Cloud Console
42
+ *
43
+ * Optional environment variables:
44
+ * - GOOGLE_CLIENT_SECRET: OAuth 2.0 client secret (optional for public clients)
45
+ * - AUTH_MODE: Auth mode (same format as --auth flag)
46
+ * - HEADLESS: Headless mode flag ('true' to enable)
47
+ * - REDIRECT_URI: OAuth redirect URI (overridden by --redirect-uri CLI flag)
48
+ * - GOOGLE_SERVICE_ACCOUNT_KEY_FILE: Service account key file (for service-account mode)
49
+ *
50
+ * @param args - CLI arguments array (typically process.argv)
51
+ * @param env - Environment variables object (typically process.env)
52
+ * @param transport - Optional transport type. If 'stdio' and auth mode is 'dcr', throws an error.
53
+ * @returns Parsed Google OAuth configuration
54
+ * @throws Error if required environment variables are missing, values are invalid, or DCR is used with stdio transport
55
+ *
56
+ * @example Default mode (no flags)
57
+ * ```typescript
58
+ * const config = parseConfig(process.argv, process.env);
59
+ * // { auth: 'loopback-oauth' }
60
+ * ```
61
+ *
62
+ * @example Override auth mode
63
+ * ```typescript
64
+ * parseConfig(['--auth=loopback-oauth'], process.env);
65
+ * parseConfig(['--auth=service-account'], process.env);
66
+ * parseConfig(['--auth=dcr'], process.env);
67
+ * ```
68
+ *
69
+ * @example With transport validation
70
+ * ```typescript
71
+ * parseConfig(['--auth=dcr'], process.env, 'http'); // OK
72
+ * parseConfig(['--auth=dcr'], process.env, 'stdio'); // Throws error
73
+ * ```
74
+ *
75
+ * Valid auth modes:
76
+ * - loopback-oauth (default)
77
+ * - service-account
78
+ * - dcr (HTTP transport only)
79
+ */ export function parseConfig(args, env, transport) {
80
+ var _ref;
81
+ function requiredEnv(key) {
82
+ const value = env[key];
83
+ if (!value) {
84
+ throw new Error(`Environment variable ${key} is required for Google OAuth`);
85
+ }
86
+ return value;
87
+ }
88
+ // Parse CLI arguments
89
+ const { values } = parseArgs({
90
+ args,
91
+ options: {
92
+ auth: {
93
+ type: 'string'
94
+ },
95
+ headless: {
96
+ type: 'boolean'
97
+ },
98
+ 'redirect-uri': {
99
+ type: 'string'
100
+ },
101
+ 'service-account-key-file': {
102
+ type: 'string'
103
+ }
104
+ },
105
+ strict: false,
106
+ allowPositionals: true
107
+ });
108
+ const authArg = typeof values.auth === 'string' ? values.auth : undefined;
109
+ const envAuthMode = env.AUTH_MODE;
110
+ const mode = authArg || envAuthMode;
111
+ let auth;
112
+ if (mode) {
113
+ const parsed = parseAuthMode(mode);
114
+ auth = parsed.auth;
115
+ } else {
116
+ // DEFAULT: No flags provided, use loopback-oauth
117
+ auth = 'loopback-oauth';
118
+ }
119
+ // Validate: DCR only works with HTTP transport
120
+ if (auth === 'dcr' && transport === 'stdio') {
121
+ throw new Error('DCR authentication mode requires HTTP transport. DCR is not supported with stdio transport.');
122
+ }
123
+ const cliHeadless = typeof values.headless === 'boolean' ? values.headless : undefined;
124
+ const envHeadless = env.HEADLESS === 'true' ? true : env.HEADLESS === 'false' ? false : undefined;
125
+ const headless = (_ref = cliHeadless !== null && cliHeadless !== void 0 ? cliHeadless : envHeadless) !== null && _ref !== void 0 ? _ref : false;
126
+ const cliRedirectUri = typeof values['redirect-uri'] === 'string' ? values['redirect-uri'] : undefined;
127
+ const envRedirectUri = env.REDIRECT_URI;
128
+ const redirectUri = cliRedirectUri !== null && cliRedirectUri !== void 0 ? cliRedirectUri : envRedirectUri;
129
+ const clientId = requiredEnv('GOOGLE_CLIENT_ID');
130
+ const clientSecret = env.GOOGLE_CLIENT_SECRET;
131
+ let serviceAccountKeyFile;
132
+ if (auth === 'service-account') {
133
+ const cliKeyFile = typeof values['service-account-key-file'] === 'string' ? values['service-account-key-file'] : undefined;
134
+ serviceAccountKeyFile = cliKeyFile !== null && cliKeyFile !== void 0 ? cliKeyFile : env.GOOGLE_SERVICE_ACCOUNT_KEY_FILE;
135
+ if (!serviceAccountKeyFile) {
136
+ 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');
137
+ }
138
+ // Resolve relative paths now since cwd can change during execution
139
+ serviceAccountKeyFile = resolve(serviceAccountKeyFile);
140
+ }
141
+ return {
142
+ clientId,
143
+ ...clientSecret && {
144
+ clientSecret
145
+ },
146
+ auth,
147
+ headless,
148
+ ...redirectUri && {
149
+ redirectUri
150
+ },
151
+ ...serviceAccountKeyFile && {
152
+ serviceAccountKeyFile
153
+ }
154
+ };
155
+ }
156
+ /**
157
+ * Build production configuration from process globals.
158
+ * Entry point for production server.
159
+ */ export function createConfig() {
160
+ return parseConfig(process.argv, process.env);
161
+ }
162
+ /**
163
+ * Parse DCR configuration from CLI arguments and environment variables.
164
+ *
165
+ * CLI Arguments:
166
+ * - --dcr-mode: DCR mode ('self-hosted' | 'external')
167
+ * - Default: 'self-hosted' (if flag is omitted)
168
+ * - --dcr-verify-url: External verification endpoint URL (required for external mode)
169
+ * - --dcr-store-uri: DCR client storage URI (required for self-hosted mode)
170
+ *
171
+ * Required environment variables:
172
+ * - GOOGLE_CLIENT_ID: OAuth 2.0 client ID from Google Cloud Console
173
+ *
174
+ * Optional environment variables:
175
+ * - GOOGLE_CLIENT_SECRET: OAuth 2.0 client secret (optional for public clients)
176
+ * - DCR_MODE: DCR mode (same format as --dcr-mode flag)
177
+ * - DCR_VERIFY_URL: External verification URL (same as --dcr-verify-url flag)
178
+ * - DCR_STORE_URI: DCR storage URI (same as --dcr-store-uri flag)
179
+ *
180
+ * @param args - CLI arguments array (typically process.argv)
181
+ * @param env - Environment variables object (typically process.env)
182
+ * @param scope - OAuth scopes to request (space-separated)
183
+ * @returns Parsed DCR configuration
184
+ * @throws Error if required environment variables are missing or validation fails
185
+ *
186
+ * @example Self-hosted mode
187
+ * ```typescript
188
+ * const config = parseDcrConfig(
189
+ * ['--dcr-mode=self-hosted', '--dcr-store-uri=file:///path/to/store.json'],
190
+ * process.env,
191
+ * 'https://www.googleapis.com/auth/drive.readonly'
192
+ * );
193
+ * ```
194
+ *
195
+ * @example External mode
196
+ * ```typescript
197
+ * const config = parseDcrConfig(
198
+ * ['--dcr-mode=external', '--dcr-verify-url=https://auth0.example.com/verify'],
199
+ * process.env,
200
+ * 'https://www.googleapis.com/auth/drive.readonly'
201
+ * );
202
+ * ```
203
+ */ export function parseDcrConfig(args, env, scope) {
204
+ function requiredEnv(key) {
205
+ const value = env[key];
206
+ if (!value) {
207
+ throw new Error(`Environment variable ${key} is required for DCR configuration`);
208
+ }
209
+ return value;
210
+ }
211
+ const { values } = parseArgs({
212
+ args,
213
+ options: {
214
+ 'dcr-mode': {
215
+ type: 'string'
216
+ },
217
+ 'dcr-verify-url': {
218
+ type: 'string'
219
+ },
220
+ 'dcr-store-uri': {
221
+ type: 'string'
222
+ }
223
+ },
224
+ strict: false,
225
+ allowPositionals: true
226
+ });
227
+ const cliMode = typeof values['dcr-mode'] === 'string' ? values['dcr-mode'] : undefined;
228
+ const envMode = env.DCR_MODE;
229
+ const mode = cliMode || envMode || 'self-hosted';
230
+ if (mode !== 'self-hosted' && mode !== 'external') {
231
+ throw new Error(`Invalid --dcr-mode value: "${mode}". Valid values: self-hosted, external`);
232
+ }
233
+ const cliVerifyUrl = typeof values['dcr-verify-url'] === 'string' ? values['dcr-verify-url'] : undefined;
234
+ const envVerifyUrl = env.DCR_VERIFY_URL;
235
+ const verifyUrl = cliVerifyUrl || envVerifyUrl;
236
+ const cliStoreUri = typeof values['dcr-store-uri'] === 'string' ? values['dcr-store-uri'] : undefined;
237
+ const envStoreUri = env.DCR_STORE_URI;
238
+ const storeUri = cliStoreUri || envStoreUri;
239
+ if (mode === 'external' && !verifyUrl) {
240
+ throw new Error('DCR external mode requires --dcr-verify-url or DCR_VERIFY_URL environment variable');
241
+ }
242
+ const clientId = requiredEnv('GOOGLE_CLIENT_ID');
243
+ const clientSecret = env.GOOGLE_CLIENT_SECRET;
244
+ return {
245
+ mode,
246
+ ...verifyUrl && {
247
+ verifyUrl
248
+ },
249
+ ...storeUri && {
250
+ storeUri
251
+ },
252
+ clientId,
253
+ ...clientSecret && {
254
+ clientSecret
255
+ },
256
+ scope
257
+ };
258
+ }
@@ -0,0 +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":"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"}
@@ -0,0 +1,173 @@
1
+ /**
2
+ * Standalone types for Google OAuth
3
+ * No dependencies on other @mcp-z packages except @mcp-z/oauth
4
+ */
5
+ import type { AuthFlowDescriptor, CachedToken, DcrClientInformation, DcrClientMetadata, Logger, OAuth2TokenStorageProvider, ProviderTokens, ToolHandler, ToolModule, UserAuthProvider } from '@mcp-z/oauth';
6
+ import type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js';
7
+ import type { ServerNotification, ServerRequest } from '@modelcontextprotocol/sdk/types.js';
8
+ import type { OAuth2Client } from 'google-auth-library';
9
+ import type { Keyv } from 'keyv';
10
+ export type { Logger, CachedToken, ToolModule, ProviderTokens, DcrClientMetadata, DcrClientInformation };
11
+ export { AuthRequiredError } from '@mcp-z/oauth';
12
+ export type { ToolHandler, AuthFlowDescriptor, OAuth2TokenStorageProvider, UserAuthProvider, RequestHandlerExtra, ServerRequest, ServerNotification };
13
+ /**
14
+ * Google service types that support OAuth
15
+ * OAuth clients support all Google services provided by googleapis
16
+ * @public
17
+ */
18
+ export type GoogleService = string;
19
+ /**
20
+ * OAuth client configuration for upstream provider
21
+ * @public
22
+ */
23
+ export interface OAuthClientConfig {
24
+ /** OAuth client ID for upstream provider */
25
+ clientId: string;
26
+ /** OAuth client secret (optional for some flows) */
27
+ clientSecret?: string;
28
+ }
29
+ /**
30
+ * Google OAuth configuration interface.
31
+ * @public
32
+ */
33
+ export interface OAuthConfig {
34
+ clientId: string;
35
+ /** Optional for public clients */
36
+ clientSecret?: string;
37
+ auth: 'loopback-oauth' | 'service-account' | 'dcr';
38
+ /** No browser interaction when true */
39
+ headless: boolean;
40
+ /** Defaults to ephemeral loopback */
41
+ redirectUri?: string;
42
+ /** Required when auth === 'service-account' */
43
+ serviceAccountKeyFile?: string;
44
+ }
45
+ /**
46
+ * DCR configuration for dynamic client registration
47
+ * @public
48
+ */
49
+ export interface DcrConfig {
50
+ /** DCR mode: self-hosted (runs own OAuth server) or external (uses Auth0/Stitch) */
51
+ mode: 'self-hosted' | 'external';
52
+ /** External verification endpoint URL (required for external mode) */
53
+ verifyUrl?: string;
54
+ /** DCR client storage URI (required for self-hosted mode) */
55
+ storeUri?: string;
56
+ /** OAuth client ID for Google APIs */
57
+ clientId: string;
58
+ /** OAuth client secret (optional for public clients) */
59
+ clientSecret?: string;
60
+ /** OAuth scopes to request */
61
+ scope: string;
62
+ /** Logger instance */
63
+ logger?: Logger;
64
+ }
65
+ /**
66
+ * Configuration for loopback OAuth client
67
+ * @public
68
+ */
69
+ export interface LoopbackOAuthConfig {
70
+ service: GoogleService;
71
+ clientId: string;
72
+ /** Optional for public clients */
73
+ clientSecret?: string | undefined;
74
+ scope: string;
75
+ /** No browser interaction when true */
76
+ headless: boolean;
77
+ logger: Logger;
78
+ tokenStore: Keyv<unknown>;
79
+ /** Defaults to ephemeral loopback */
80
+ redirectUri?: string;
81
+ }
82
+ /**
83
+ * Auth context injected into extra by middleware
84
+ * @public
85
+ */
86
+ export interface AuthContext {
87
+ /**
88
+ * OAuth2Client ready for googleapis
89
+ * GUARANTEED to exist when handler runs
90
+ */
91
+ auth: OAuth2Client;
92
+ /**
93
+ * Account being used (for logging, debugging)
94
+ */
95
+ accountId: string;
96
+ /**
97
+ * User ID (multi-tenant only)
98
+ */
99
+ /**
100
+ * Additional metadata (e.g., service account email)
101
+ */
102
+ metadata?: {
103
+ serviceEmail?: string;
104
+ [key: string]: unknown;
105
+ };
106
+ }
107
+ /**
108
+ * Enriched extra with guaranteed auth context and logger
109
+ * Handlers receive this type - never plain RequestHandlerExtra
110
+ * @public
111
+ */
112
+ export interface EnrichedExtra extends RequestHandlerExtra<ServerRequest, ServerNotification> {
113
+ /**
114
+ * Auth context injected by middleware
115
+ * GUARANTEED to exist (middleware catches auth failures)
116
+ */
117
+ authContext: AuthContext;
118
+ /**
119
+ * Logger injected by middleware
120
+ * GUARANTEED to exist
121
+ */
122
+ logger: Logger;
123
+ _meta?: {
124
+ accountId?: string;
125
+ [key: string]: unknown;
126
+ };
127
+ }
128
+ /**
129
+ * Registered client with full metadata
130
+ * Extends DcrClientInformation with internal timestamps
131
+ * @internal
132
+ */
133
+ export interface RegisteredClient extends DcrClientInformation {
134
+ /** Creation timestamp (milliseconds since epoch) */
135
+ created_at: number;
136
+ }
137
+ /**
138
+ * Authorization code data structure
139
+ * @public
140
+ */
141
+ export interface AuthorizationCode {
142
+ code: string;
143
+ client_id: string;
144
+ redirect_uri: string;
145
+ scope: string;
146
+ code_challenge?: string;
147
+ code_challenge_method?: string;
148
+ /** Google provider tokens obtained during authorization */
149
+ providerTokens: ProviderTokens;
150
+ created_at: number;
151
+ expires_at: number;
152
+ }
153
+ /**
154
+ * Access token data structure
155
+ * @public
156
+ */
157
+ export interface AccessToken {
158
+ access_token: string;
159
+ token_type: 'Bearer';
160
+ expires_in: number;
161
+ refresh_token?: string;
162
+ scope: string;
163
+ client_id: string;
164
+ /** Google provider tokens */
165
+ providerTokens: ProviderTokens;
166
+ created_at: number;
167
+ }
168
+ /**
169
+ * Authentication required response type
170
+ * Re-exported from @mcp-z/oauth for consistency
171
+ * @public
172
+ */
173
+ export type { AuthRequired, AuthRequiredBranch } from './schemas/index.js';
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Standalone types for Google OAuth
3
+ * No dependencies on other @mcp-z packages except @mcp-z/oauth
4
+ */ // Shared types from base @mcp-z/oauth package
5
+ // Re-export error class
6
+ export { AuthRequiredError } from '@mcp-z/oauth';
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/Users/kevin/Dev/Projects/ai/mcp-z/oauth/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"}