@giantswarm-io/pro 1.7.15 → 1.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@giantswarm-io/pro",
3
- "version": "1.7.15",
3
+ "version": "1.8.1",
4
4
  "description": "Core library and MCP server for managing Giant Swarm's roadmap and customer project boards",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -6,7 +6,12 @@
6
6
  * proxying the actual authentication to GitHub.
7
7
  *
8
8
  * Flow:
9
- * 1. MCP client registers via /register → gets a local client_id
9
+ * 1. MCP client obtains a client_id, either by
10
+ * a. registering via /register (RFC 7591 dynamic client registration), or
11
+ * b. using the HTTPS URL of its Client ID Metadata Document (CIMD,
12
+ * SEP-991) directly as client_id — PRO fetches and validates the
13
+ * document on first use. The AS metadata advertises this with
14
+ * client_id_metadata_document_supported: true.
10
15
  * 2. MCP client initiates /authorize with PKCE
11
16
  * 3. PRO redirects to GitHub OAuth with our app's client_id
12
17
  * 4. GitHub redirects back to /github/callback
@@ -14,14 +19,27 @@
14
19
  * 6. MCP client exchanges local code for the GitHub token via /token
15
20
  * 7. MCP requests include the GitHub token as Bearer auth
16
21
  *
22
+ * State and restarts: everything here lives in process memory. A restart
23
+ * drops all dynamically registered client_ids (clients on path 1a get
24
+ * invalid_client and must register again), every in-flight authorization
25
+ * session (a login that is on GitHub when the pod restarts fails at
26
+ * /github/callback with "Invalid or expired authorization session" and has to
27
+ * be started over) and every not-yet-exchanged local authorization code.
28
+ * CIMD clients (path 1b) are unaffected: their client_id is re-resolved from
29
+ * the URL, which is why muster and Claude Code use it.
30
+ *
17
31
  * Environment variables:
18
32
  * GITHUB_OAUTH_CLIENT_ID - GitHub OAuth App client ID
19
33
  * GITHUB_OAUTH_CLIENT_SECRET - GitHub OAuth App client secret
20
- * OAUTH_TRUSTED_CLIENT_IDS - Comma-separated CIMD URLs of trusted clients
21
- * that are auto-registered on first use (e.g. muster)
34
+ * OAUTH_TRUSTED_CLIENT_IDS - Comma-separated CIMD URLs that bypass the
35
+ * outbound URL policy below (e.g. a muster on a
36
+ * cluster-internal hostname). Public HTTPS CIMD
37
+ * URLs need no entry here.
22
38
  */
23
39
 
24
40
  import { randomUUID } from 'crypto';
41
+ import net from 'node:net';
42
+ import { InvalidGrantError, UnsupportedGrantTypeError } from '@modelcontextprotocol/sdk/server/auth/errors.js';
25
43
  import { logger } from '../logger.js';
26
44
 
27
45
  // TTL for authorization sessions (10 minutes)
@@ -32,8 +50,47 @@ const TOKEN_CACHE_TTL_MS = 5 * 60 * 1000;
32
50
  const MAX_CLIENTS = 1000;
33
51
  // GitHub OAuth scopes required by PRO's tools
34
52
  const REQUIRED_GITHUB_SCOPES = ['repo', 'project', 'read:org'];
35
- // TTL for cached CIMD fetches (1 hour) — avoids re-fetching on every authorize
53
+ // TTL for resolved Client ID Metadata Documents (1 hour) — avoids re-fetching
54
+ // on every authorize/token call
36
55
  const CIMD_CACHE_TTL_MS = 60 * 60 * 1000;
56
+ // TTL for remembering a CIMD URL that failed to resolve, so a flood of bogus
57
+ // URL client_ids does not become a flood of outbound fetches
58
+ const CIMD_NEGATIVE_CACHE_TTL_MS = 5 * 60 * 1000;
59
+ // Maximum number of CIMD clients (positive and negative entries) kept in memory
60
+ const MAX_CIMD_CLIENTS = 1000;
61
+ // Outbound fetch limits for CIMD documents
62
+ const CIMD_FETCH_TIMEOUT_MS = 5 * 1000;
63
+ const CIMD_MAX_BYTES = 64 * 1024;
64
+
65
+ /**
66
+ * Whether a client_id has the shape of a Client ID Metadata Document URL that
67
+ * this server is willing to fetch.
68
+ *
69
+ * SEP-991 requires an HTTPS URL with a non-root path (the same shape the MCP
70
+ * SDK client enforces on its own clientMetadataUrl). On top of that, since the
71
+ * client_id is attacker-controlled and resolving it means an outbound request
72
+ * from inside the cluster, refuse everything that would turn the fetch into an
73
+ * SSRF probe: IP literals, loopback, single-label and cluster-internal
74
+ * hostnames, embedded credentials, fragments.
75
+ */
76
+ export function isCimdUrl(clientId) {
77
+ let url;
78
+ try {
79
+ url = new URL(clientId);
80
+ } catch {
81
+ return false;
82
+ }
83
+ if (url.protocol !== 'https:') return false;
84
+ if (url.pathname === '' || url.pathname === '/') return false;
85
+ if (url.username || url.password || url.hash) return false;
86
+
87
+ const host = url.hostname;
88
+ if (net.isIP(host.replace(/^\[|\]$/g, '')) !== 0) return false;
89
+ if (host === 'localhost' || host.endsWith('.localhost')) return false;
90
+ if (!host.includes('.')) return false;
91
+ if (/\.(local|localdomain|internal|svc|home\.arpa)$/.test(host)) return false;
92
+ return true;
93
+ }
37
94
 
38
95
  /**
39
96
  * Create the GitHub OAuth provider.
@@ -44,8 +101,9 @@ const CIMD_CACHE_TTL_MS = 60 * 60 * 1000;
44
101
  export function createGitHubOAuthProvider(config) {
45
102
  const { clientId, clientSecret } = config;
46
103
 
47
- // Trusted client IDs (CIMD URLs) that can skip /register — read at creation
48
- // time so tests can set the env var before calling createGitHubOAuthProvider.
104
+ // Trusted CIMD URLs that bypass the outbound URL policy in isCimdUrl — read
105
+ // at creation time so tests can set the env var before calling
106
+ // createGitHubOAuthProvider.
49
107
  const trustedClientIds = (process.env.OAUTH_TRUSTED_CLIENT_IDS || '')
50
108
  .split(',')
51
109
  .map(s => s.trim())
@@ -78,58 +136,128 @@ export function createGitHubOAuthProvider(config) {
78
136
  }, 60_000);
79
137
  sweepInterval.unref();
80
138
 
81
- // Cache for fetched CIMDs (URL → { metadata, expiresAt })
82
- const cimdCache = new Map();
139
+ // Resolved CIMD clients (URL client_id → { clientInfo | undefined, expiresAt }).
140
+ // Kept apart from `clients` so DCR churn can never evict them, and so a
141
+ // stale entry can keep serving while a refresh fails.
142
+ const cimdClients = new Map();
83
143
 
84
144
  /**
85
- * Fetch a Client ID Metadata Document from a trusted CIMD URL and
86
- * register the client in the local store. Returns the client info
87
- * or undefined if the fetch fails or the URL is not trusted.
145
+ * Validate a fetched Client ID Metadata Document and turn it into the
146
+ * client info shape the MCP SDK handlers expect. Returns undefined (after
147
+ * logging why) when the document is unusable.
88
148
  */
89
- async function fetchAndRegisterTrustedClient(clientId) {
90
- if (!trustedClientIds.includes(clientId)) {
149
+ function clientInfoFromCimd(clientId, doc, trusted) {
150
+ const reject = (reason) => {
151
+ logger.warn(`OAuth: Rejected CIMD ${clientId}: ${reason}`);
91
152
  return undefined;
153
+ };
154
+ if (!doc || typeof doc !== 'object' || Array.isArray(doc)) {
155
+ return reject('document is not a JSON object');
92
156
  }
93
-
94
- // Check CIMD cache
95
- const cached = cimdCache.get(clientId);
96
- if (cached && Date.now() < cached.expiresAt) {
97
- return clients.get(clientId);
157
+ // The document must claim the URL it was fetched from as its client_id.
158
+ // Trusted (allowlisted) documents may omit it, but must not contradict it.
159
+ if (doc.client_id !== clientId && !(trusted && doc.client_id === undefined)) {
160
+ return reject(`client_id ${JSON.stringify(doc.client_id)} does not match the document URL`);
98
161
  }
162
+ const redirectUris = doc.redirect_uris;
163
+ if (!Array.isArray(redirectUris) || redirectUris.length === 0 ||
164
+ !redirectUris.every(u => typeof u === 'string' && URL.canParse(u))) {
165
+ return reject('redirect_uris must be a non-empty array of URLs');
166
+ }
167
+ // A public document cannot hold a secret and we do not support
168
+ // private_key_jwt, so only public clients can identify via CIMD.
169
+ const authMethod = doc.token_endpoint_auth_method ?? 'none';
170
+ if (authMethod !== 'none') {
171
+ return reject(`unsupported token_endpoint_auth_method ${JSON.stringify(authMethod)}`);
172
+ }
173
+ const str = (v) => (typeof v === 'string' ? v : undefined);
174
+ return {
175
+ client_id: clientId,
176
+ client_id_issued_at: Math.floor(Date.now() / 1000),
177
+ client_name: str(doc.client_name),
178
+ client_uri: str(doc.client_uri),
179
+ redirect_uris: redirectUris,
180
+ grant_types: Array.isArray(doc.grant_types) ? doc.grant_types : ['authorization_code'],
181
+ response_types: Array.isArray(doc.response_types) ? doc.response_types : ['code'],
182
+ token_endpoint_auth_method: 'none',
183
+ scope: str(doc.scope)
184
+ };
185
+ }
99
186
 
187
+ /**
188
+ * Fetch a Client ID Metadata Document. Returns the parsed JSON or undefined.
189
+ */
190
+ async function fetchCimd(clientId) {
100
191
  try {
101
192
  const res = await fetch(clientId, {
102
- headers: { Accept: 'application/json', 'User-Agent': 'giantswarm-pro-mcp' }
193
+ headers: { Accept: 'application/json', 'User-Agent': 'giantswarm-pro-mcp' },
194
+ redirect: 'manual',
195
+ signal: AbortSignal.timeout(CIMD_FETCH_TIMEOUT_MS)
103
196
  });
104
197
  if (!res.ok) {
105
198
  logger.warn(`OAuth: Failed to fetch CIMD from ${clientId}: ${res.status}`);
106
199
  return undefined;
107
200
  }
108
- const metadata = await res.json();
109
-
110
- const now = Math.floor(Date.now() / 1000);
111
- const clientInfo = {
112
- client_id: clientId,
113
- client_id_issued_at: now,
114
- client_name: metadata.client_name,
115
- client_uri: metadata.client_uri,
116
- redirect_uris: metadata.redirect_uris || [],
117
- grant_types: metadata.grant_types || ['authorization_code'],
118
- response_types: metadata.response_types || ['code'],
119
- token_endpoint_auth_method: metadata.token_endpoint_auth_method || 'none',
120
- scope: metadata.scope
121
- };
122
-
123
- clients.set(clientId, clientInfo);
124
- cimdCache.set(clientId, { expiresAt: Date.now() + CIMD_CACHE_TTL_MS });
125
- logger.info(`OAuth: Auto-registered trusted client ${clientId} (${metadata.client_name || 'unknown'})`);
126
- return clientInfo;
201
+ const declared = Number(res.headers?.get?.('content-length'));
202
+ if (declared > CIMD_MAX_BYTES) {
203
+ logger.warn(`OAuth: Rejected CIMD ${clientId}: content-length ${declared} exceeds ${CIMD_MAX_BYTES} bytes`);
204
+ return undefined;
205
+ }
206
+ const text = await res.text();
207
+ if (text.length > CIMD_MAX_BYTES) {
208
+ logger.warn(`OAuth: Rejected CIMD ${clientId}: body exceeds ${CIMD_MAX_BYTES} bytes`);
209
+ return undefined;
210
+ }
211
+ return JSON.parse(text);
127
212
  } catch (err) {
128
213
  logger.warn(`OAuth: Error fetching CIMD from ${clientId}: ${err.message}`);
129
214
  return undefined;
130
215
  }
131
216
  }
132
217
 
218
+ /**
219
+ * Resolve a URL client_id (SEP-991) to client info by fetching and
220
+ * validating its Client ID Metadata Document. Results — including failures
221
+ * for untrusted URLs — are cached; a trusted client's last good document
222
+ * keeps being served while a refresh fails. Returns undefined for anything
223
+ * that is not an acceptable CIMD URL or whose document does not validate.
224
+ */
225
+ async function resolveCimdClient(clientId) {
226
+ const trusted = trustedClientIds.includes(clientId);
227
+ if (!trusted && !isCimdUrl(clientId)) {
228
+ return undefined;
229
+ }
230
+
231
+ const now = Date.now();
232
+ const cached = cimdClients.get(clientId);
233
+ if (cached && now < cached.expiresAt) {
234
+ return cached.clientInfo;
235
+ }
236
+
237
+ const doc = await fetchCimd(clientId);
238
+ let clientInfo = doc === undefined ? undefined : clientInfoFromCimd(clientId, doc, trusted);
239
+
240
+ if (clientInfo) {
241
+ logger.info(`OAuth: Resolved CIMD client ${clientId} (${clientInfo.client_name || 'unknown'})`);
242
+ } else if (cached?.clientInfo) {
243
+ // Refresh failed: keep the last good document a little longer rather
244
+ // than locking the client out over a transient upstream problem.
245
+ logger.warn(`OAuth: Keeping previously resolved CIMD client ${clientId} after failed refresh`);
246
+ clientInfo = cached.clientInfo;
247
+ } else if (trusted) {
248
+ // Never negative-cache a trusted client: the next attempt should retry.
249
+ return undefined;
250
+ }
251
+
252
+ if (!cimdClients.has(clientId) && cimdClients.size >= MAX_CIMD_CLIENTS) {
253
+ const oldestKey = cimdClients.keys().next().value;
254
+ cimdClients.delete(oldestKey);
255
+ }
256
+ const ttl = clientInfo && clientInfo !== cached?.clientInfo ? CIMD_CACHE_TTL_MS : CIMD_NEGATIVE_CACHE_TTL_MS;
257
+ cimdClients.set(clientId, { clientInfo, expiresAt: now + ttl });
258
+ return clientInfo;
259
+ }
260
+
133
261
  /**
134
262
  * Verify a GitHub access token by calling the GitHub API.
135
263
  * Validates that the token has all required scopes.
@@ -190,8 +318,8 @@ export function createGitHubOAuthProvider(config) {
190
318
  async getClient(clientId) {
191
319
  const existing = clients.get(clientId);
192
320
  if (existing) return existing;
193
- // Auto-register if this is a trusted CIMD URL
194
- return await fetchAndRegisterTrustedClient(clientId);
321
+ // URL client_ids resolve to their Client ID Metadata Document
322
+ return await resolveCimdClient(clientId);
195
323
  },
196
324
 
197
325
  registerClient(clientMetadata) {
@@ -249,13 +377,19 @@ export function createGitHubOAuthProvider(config) {
249
377
  res.redirect(githubUrl.toString());
250
378
  },
251
379
 
380
+ // Errors thrown from the token-grant methods below must be MCP SDK
381
+ // OAuthError subclasses: the SDK's /token handler turns those into the
382
+ // RFC 6749 §5.2 error response (400 + error code) and anything else into
383
+ // an opaque 500 server_error. A bad or expired code is invalid_grant, so a
384
+ // client can tell "start over" apart from "the server is broken".
385
+
252
386
  /**
253
387
  * Return the PKCE code challenge for a local authorization code.
254
388
  */
255
389
  async challengeForAuthorizationCode(_client, authorizationCode) {
256
390
  const entry = authCodes.get(authorizationCode);
257
391
  if (!entry) {
258
- throw new Error('Authorization code not found or expired');
392
+ throw new InvalidGrantError('Authorization code not found or expired');
259
393
  }
260
394
  return entry.codeChallenge;
261
395
  },
@@ -266,11 +400,11 @@ export function createGitHubOAuthProvider(config) {
266
400
  async exchangeAuthorizationCode(client, authorizationCode) {
267
401
  const entry = authCodes.get(authorizationCode);
268
402
  if (!entry) {
269
- throw new Error('Authorization code not found or expired');
403
+ throw new InvalidGrantError('Authorization code not found or expired');
270
404
  }
271
405
 
272
406
  if (entry.clientId !== client.client_id) {
273
- throw new Error('Authorization code was issued to a different client');
407
+ throw new InvalidGrantError('Authorization code was issued to a different client');
274
408
  }
275
409
 
276
410
  // Delete the code (single use)
@@ -295,7 +429,7 @@ export function createGitHubOAuthProvider(config) {
295
429
  * so we reject these requests.
296
430
  */
297
431
  async exchangeRefreshToken() {
298
- throw new Error('Refresh tokens are not supported. Re-authorize to get a new token.');
432
+ throw new UnsupportedGrantTypeError('Refresh tokens are not supported. Re-authorize to get a new token.');
299
433
  },
300
434
 
301
435
  /**
@@ -42,11 +42,12 @@ const sessions = {};
42
42
  /**
43
43
  * Start the MCP server with streamable HTTP transport
44
44
  * @param {Object} options
45
- * @param {number} options.port - Port to listen on (default: 8080)
45
+ * @param {number} options.port - Port to listen on (default: 8080; 0 picks a free port)
46
46
  * @param {string} options.endpoint - MCP endpoint path (default: /mcp)
47
+ * @returns {Promise<import('http').Server>} the listening server
47
48
  */
48
49
  export async function startHTTPServer(options = {}) {
49
- const port = options.port || parseInt(process.env.HTTP_PORT, 10) || DEFAULT_PORT;
50
+ const port = options.port ?? (parseInt(process.env.HTTP_PORT, 10) || DEFAULT_PORT);
50
51
  const endpoint = options.endpoint || DEFAULT_ENDPOINT;
51
52
 
52
53
  const app = express();
@@ -63,7 +64,8 @@ export async function startHTTPServer(options = {}) {
63
64
  let bearerAuthMiddleware = null;
64
65
 
65
66
  if (oauthClientId && oauthClientSecret) {
66
- const { mcpAuthRouter } = await import('@modelcontextprotocol/sdk/server/auth/router.js');
67
+ const { mcpAuthRouter, createOAuthMetadata } = await import('@modelcontextprotocol/sdk/server/auth/router.js');
68
+ const { metadataHandler } = await import('@modelcontextprotocol/sdk/server/auth/handlers/metadata.js');
67
69
  const { requireBearerAuth } = await import('@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js');
68
70
  const { createGitHubOAuthProvider } = await import('../auth/provider.js');
69
71
 
@@ -74,13 +76,30 @@ export async function startHTTPServer(options = {}) {
74
76
  clientSecret: oauthClientSecret
75
77
  });
76
78
 
77
- // Mount OAuth routes: /authorize, /token, /register, /.well-known/*
78
- app.use(mcpAuthRouter({
79
+ const authRouterOptions = {
79
80
  provider,
80
81
  issuerUrl,
81
82
  scopesSupported: ['repo', 'project', 'read:org'],
82
83
  resourceName: 'Giant Swarm PRO MCP Server'
83
- }));
84
+ };
85
+
86
+ // RFC 8414 authorization server metadata. mcpAuthRouter builds this same
87
+ // document internally but offers no way to extend it, so build it here,
88
+ // add the SEP-991 flag and mount the well-known route before the router:
89
+ // Express dispatches in registration order, so this copy wins over the
90
+ // router's own.
91
+ const oauthMetadata = {
92
+ ...createOAuthMetadata(authRouterOptions),
93
+ // Clients may use the HTTPS URL of their Client ID Metadata Document as
94
+ // client_id instead of registering (resolved in clientsStore.getClient).
95
+ // Muster and Claude Code pick this path only when it is advertised; it
96
+ // is what lets them survive a restart of this in-memory client store.
97
+ client_id_metadata_document_supported: true
98
+ };
99
+ app.use('/.well-known/oauth-authorization-server', metadataHandler(oauthMetadata));
100
+
101
+ // Mount OAuth routes: /authorize, /token, /register, /.well-known/*
102
+ app.use(mcpAuthRouter(authRouterOptions));
84
103
 
85
104
  // GitHub OAuth callback (not part of MCP spec — specific to our proxy)
86
105
  app.get('/github/callback', handleGitHubCallback);
@@ -207,8 +226,12 @@ export async function startHTTPServer(options = {}) {
207
226
  sweepInterval.unref();
208
227
 
209
228
  // Start listening
210
- const httpServer = app.listen(port, () => {
211
- logger.info(`MCP HTTP server listening on port ${port} (endpoint: ${endpoint})`);
229
+ const httpServer = await new Promise((resolve, reject) => {
230
+ const server = app.listen(port, () => {
231
+ logger.info(`MCP HTTP server listening on port ${server.address().port} (endpoint: ${endpoint})`);
232
+ resolve(server);
233
+ });
234
+ server.once('error', reject);
212
235
  });
213
236
 
214
237
  // Graceful shutdown
@@ -230,4 +253,6 @@ export async function startHTTPServer(options = {}) {
230
253
 
231
254
  process.on('SIGINT', shutdown);
232
255
  process.on('SIGTERM', shutdown);
256
+
257
+ return httpServer;
233
258
  }