@giantswarm-io/pro 1.8.1 → 1.9.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.
package/README.md CHANGED
@@ -76,9 +76,26 @@ Note: this skips the global binary, so `pro --self-update` won't be available.
76
76
 
77
77
  ## Configuration
78
78
 
79
+ ### HTTP transport authentication
80
+
81
+ With `--transport=streamable-http` the server picks one of three modes:
82
+
83
+ | Mode | Configuration | Who holds the GitHub credential |
84
+ | --- | --- | --- |
85
+ | Env token | `GITHUB_API_TOKEN` only | the server (one identity for every caller) |
86
+ | OAuth 2.1 | `GITHUB_OAUTH_CLIENT_ID` + `GITHUB_OAUTH_CLIENT_SECRET` (+ `OAUTH_ISSUER_URL`) | this server, acting as authorization server in front of GitHub; each caller signs in through it |
87
+ | Bearer-only | `OAUTH_BEARER_ONLY=true` (+ `OAUTH_ISSUER_URL`) | the caller: every `/mcp` request carries a GitHub token as bearer, verified via the GitHub API and used for that request. No `/authorize`, `/token`, `/register`; `/.well-known/oauth-protected-resource[/mcp]` names `https://github.com/login/oauth` as the authorization server. Made for an MCP aggregator such as muster that holds the person's GitHub grant itself. |
88
+
89
+ In the OAuth and bearer-only modes GitHub calls run as the caller, so board
90
+ changes are attributed to the person. Scoped tokens (classic OAuth, classic
91
+ PAT) must cover `repo`, `project` and `read:org`; GitHub App user-to-server
92
+ tokens and fine-grained PATs carry no scope list and are accepted as they
93
+ are, GitHub enforcing their permissions on each call.
94
+
79
95
  ### Environment Variables
80
96
 
81
- - `GITHUB_API_TOKEN` (required): GitHub PAT with `project:write` and `repo:write` scopes.
97
+ - `GITHUB_API_TOKEN` (required for stdio and the env-token HTTP mode): GitHub PAT with `project:write` and `repo:write` scopes.
98
+ - `OAUTH_BEARER_ONLY` (optional, HTTP transport): `true` selects the bearer-only mode described above.
82
99
  - `HTTP_PORT` (optional): Port for HTTP transport (default: 8080).
83
100
 
84
101
  ## Transport Modes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@giantswarm-io/pro",
3
- "version": "1.8.1",
3
+ "version": "1.9.0",
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": {
@@ -39,7 +39,7 @@
39
39
 
40
40
  import { randomUUID } from 'crypto';
41
41
  import net from 'node:net';
42
- import { InvalidGrantError, UnsupportedGrantTypeError } from '@modelcontextprotocol/sdk/server/auth/errors.js';
42
+ import { InvalidGrantError, UnsupportedGrantTypeError, InvalidTokenError, InsufficientScopeError } from '@modelcontextprotocol/sdk/server/auth/errors.js';
43
43
  import { logger } from '../logger.js';
44
44
 
45
45
  // TTL for authorization sessions (10 minutes)
@@ -50,6 +50,12 @@ const TOKEN_CACHE_TTL_MS = 5 * 60 * 1000;
50
50
  const MAX_CLIENTS = 1000;
51
51
  // GitHub OAuth scopes required by PRO's tools
52
52
  const REQUIRED_GITHUB_SCOPES = ['repo', 'project', 'read:org'];
53
+ // GitHub's OAuth authorization server, as the hosted GitHub MCP server names it
54
+ // in its protected resource metadata. Used when this server runs as a plain
55
+ // resource server (OAUTH_BEARER_ONLY) whose tokens come from GitHub directly.
56
+ export const GITHUB_AUTHORIZATION_SERVER = 'https://github.com/login/oauth';
57
+ // Upper bound on cached verified tokens; beyond it the oldest entry is dropped.
58
+ const TOKEN_CACHE_MAX = 10000;
53
59
  // TTL for resolved Client ID Metadata Documents (1 hour) — avoids re-fetching
54
60
  // on every authorize/token call
55
61
  const CIMD_CACHE_TTL_MS = 60 * 60 * 1000;
@@ -92,6 +98,83 @@ export function isCimdUrl(clientId) {
92
98
  return true;
93
99
  }
94
100
 
101
+ /**
102
+ * Create a verifier for GitHub access tokens presented as bearers.
103
+ *
104
+ * A token is valid when GitHub's /user endpoint accepts it. Classic OAuth and
105
+ * PAT tokens announce their scopes in `x-oauth-scopes`; those must cover the
106
+ * scopes the board tools need, so a token that cannot write is refused up
107
+ * front. GitHub App user-to-server tokens and fine-grained PATs carry no such
108
+ * header -- their permissions are enforced by GitHub per request -- and are
109
+ * accepted; a missing permission surfaces as a 403 from the call that needs
110
+ * it. Verified tokens are cached briefly; `sweep` drops expired entries.
111
+ *
112
+ * Used by the OAuth provider (tokens this server issued) and by the
113
+ * bearer-only mode (tokens a client such as muster obtained from GitHub).
114
+ *
115
+ * @returns {{ verifyAccessToken(token: string): Promise<object>, sweep(now?: number): void }}
116
+ */
117
+ export function createGitHubTokenVerifier() {
118
+ // token → { authInfo, expiresAt }
119
+ const tokenCache = new Map();
120
+
121
+ async function verifyAccessToken(token) {
122
+ const cached = tokenCache.get(token);
123
+ if (cached && Date.now() < cached.expiresAt) {
124
+ return cached.authInfo;
125
+ }
126
+
127
+ const res = await fetch('https://api.github.com/user', {
128
+ headers: {
129
+ Authorization: `Bearer ${token}`,
130
+ Accept: 'application/vnd.github+json',
131
+ 'User-Agent': 'giantswarm-pro-mcp'
132
+ }
133
+ });
134
+
135
+ if (!res.ok) {
136
+ // An OAuthError so the bearer middleware answers 401 with a proper
137
+ // WWW-Authenticate challenge instead of an opaque 500.
138
+ throw new InvalidTokenError(`GitHub token verification failed: ${res.status}`);
139
+ }
140
+
141
+ // Scoped tokens (classic OAuth, classic PAT) announce their scopes; a
142
+ // token without the header is permission-based and checked per call.
143
+ const scopeHeader = res.headers.get('x-oauth-scopes');
144
+ const grantedScopes = (scopeHeader || '').split(',').map(s => s.trim()).filter(Boolean);
145
+ if (scopeHeader !== null && scopeHeader !== undefined) {
146
+ const missingScopes = REQUIRED_GITHUB_SCOPES.filter(s => !grantedScopes.includes(s));
147
+ if (missingScopes.length > 0) {
148
+ throw new InsufficientScopeError(`GitHub token is missing required scopes: ${missingScopes.join(', ')}`);
149
+ }
150
+ }
151
+
152
+ const user = await res.json();
153
+
154
+ const authInfo = {
155
+ token,
156
+ clientId: user.login,
157
+ scopes: grantedScopes,
158
+ expiresAt: Math.floor(Date.now() / 1000) + 3600 // 1 hour
159
+ };
160
+
161
+ if (tokenCache.size >= TOKEN_CACHE_MAX) {
162
+ tokenCache.delete(tokenCache.keys().next().value);
163
+ }
164
+ tokenCache.set(token, { authInfo, expiresAt: Date.now() + TOKEN_CACHE_TTL_MS });
165
+
166
+ return authInfo;
167
+ }
168
+
169
+ function sweep(now = Date.now()) {
170
+ for (const [key, entry] of tokenCache) {
171
+ if (now > entry.expiresAt) tokenCache.delete(key);
172
+ }
173
+ }
174
+
175
+ return { verifyAccessToken, sweep };
176
+ }
177
+
95
178
  /**
96
179
  * Create the GitHub OAuth provider.
97
180
  *
@@ -118,8 +201,8 @@ export function createGitHubOAuthProvider(config) {
118
201
  // In-memory local auth codes (code → { githubToken, clientId, redirectUri, codeChallenge })
119
202
  const authCodes = new Map();
120
203
 
121
- // Token verification cache (token → { authInfo, expiresAt })
122
- const tokenCache = new Map();
204
+ // GitHub token verification, shared with the bearer-only mode.
205
+ const tokenVerifier = createGitHubTokenVerifier();
123
206
 
124
207
  // Periodic cleanup
125
208
  const sweepInterval = setInterval(() => {
@@ -130,9 +213,7 @@ export function createGitHubOAuthProvider(config) {
130
213
  for (const [key, code] of authCodes) {
131
214
  if (now > code.expiresAt) authCodes.delete(key);
132
215
  }
133
- for (const [key, entry] of tokenCache) {
134
- if (now > entry.expiresAt) tokenCache.delete(key);
135
- }
216
+ tokenVerifier.sweep(now);
136
217
  }, 60_000);
137
218
  sweepInterval.unref();
138
219
 
@@ -258,54 +339,9 @@ export function createGitHubOAuthProvider(config) {
258
339
  return clientInfo;
259
340
  }
260
341
 
261
- /**
262
- * Verify a GitHub access token by calling the GitHub API.
263
- * Validates that the token has all required scopes.
264
- * Results are cached briefly to avoid per-request API calls.
265
- */
342
+ /** Verify a GitHub access token, see createGitHubTokenVerifier. */
266
343
  async function verifyGitHubToken(token) {
267
- const cached = tokenCache.get(token);
268
- if (cached && Date.now() < cached.expiresAt) {
269
- return cached.authInfo;
270
- }
271
-
272
- const res = await fetch('https://api.github.com/user', {
273
- headers: {
274
- Authorization: `Bearer ${token}`,
275
- Accept: 'application/vnd.github+json',
276
- 'User-Agent': 'giantswarm-pro-mcp'
277
- }
278
- });
279
-
280
- if (!res.ok) {
281
- throw new Error(`GitHub token verification failed: ${res.status}`);
282
- }
283
-
284
- // Parse the actual scopes granted to this token
285
- const scopeHeader = res.headers.get('x-oauth-scopes') || '';
286
- const grantedScopes = scopeHeader.split(',').map(s => s.trim()).filter(Boolean);
287
-
288
- // Reject tokens that are missing required scopes
289
- const missingScopes = REQUIRED_GITHUB_SCOPES.filter(s => !grantedScopes.includes(s));
290
- if (missingScopes.length > 0) {
291
- throw new Error(`GitHub token is missing required scopes: ${missingScopes.join(', ')}`);
292
- }
293
-
294
- const user = await res.json();
295
-
296
- const authInfo = {
297
- token,
298
- clientId: user.login,
299
- scopes: grantedScopes,
300
- expiresAt: Math.floor(Date.now() / 1000) + 3600 // 1 hour
301
- };
302
-
303
- tokenCache.set(token, {
304
- authInfo,
305
- expiresAt: Date.now() + TOKEN_CACHE_TTL_MS
306
- });
307
-
308
- return authInfo;
344
+ return tokenVerifier.verifyAccessToken(token);
309
345
  }
310
346
 
311
347
  // -----------------------------------------------------------------------
@@ -10,14 +10,21 @@
10
10
  * - OAuth endpoints: /authorize, /token, /register, /.well-known/*
11
11
  * - GitHub callback: /github/callback
12
12
  *
13
- * When either GITHUB_OAUTH_CLIENT_ID or GITHUB_OAUTH_CLIENT_SECRET is NOT set,
14
- * runs without auth (env var token mode).
13
+ * When OAUTH_BEARER_ONLY=true (and no GitHub OAuth App is configured), the
14
+ * server is a resource server only: every MCP request must carry a GitHub
15
+ * token as bearer, which is verified against the GitHub API and used for that
16
+ * request's GitHub calls. The token is obtained elsewhere -- muster's GitHub
17
+ * connector holds the person's grant -- so no /authorize, /token or /register
18
+ * exist; RFC 9728 protected resource metadata names GitHub as the
19
+ * authorization server.
20
+ *
21
+ * When none of the above is set, runs without auth (env var token mode).
15
22
  *
16
23
  * Each client session gets its own transport and MCP server instance,
17
24
  * following the recommended pattern from the MCP SDK.
18
25
  *
19
26
  * Endpoints:
20
- * POST/GET/DELETE /mcp - MCP streamable HTTP endpoint (auth required when OAuth enabled)
27
+ * POST/GET/DELETE /mcp - MCP streamable HTTP endpoint (auth required when OAuth or bearer-only auth is enabled)
21
28
  * GET /healthz - Liveness probe (always 200)
22
29
  * GET /readyz - Readiness probe (200 when server is connected)
23
30
  */
@@ -108,6 +115,33 @@ export async function startHTTPServer(options = {}) {
108
115
  bearerAuthMiddleware = requireBearerAuth({ verifier: provider });
109
116
 
110
117
  logger.info('OAuth 2.1 enabled — MCP clients must authenticate via GitHub');
118
+ } else if (process.env.OAUTH_BEARER_ONLY === 'true') {
119
+ const { requireBearerAuth } = await import('@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js');
120
+ const { metadataHandler } = await import('@modelcontextprotocol/sdk/server/auth/handlers/metadata.js');
121
+ const { createGitHubTokenVerifier, GITHUB_AUTHORIZATION_SERVER } = await import('../auth/provider.js');
122
+
123
+ // The public URL doubles as the resource identifier's origin.
124
+ const publicUrl = new URL(process.env.OAUTH_ISSUER_URL || `http://localhost:${port}`);
125
+ const resourceUrl = new URL(endpoint, publicUrl);
126
+ const protectedResourceMetadata = {
127
+ resource: resourceUrl.href,
128
+ authorization_servers: [GITHUB_AUTHORIZATION_SERVER],
129
+ scopes_supported: ['repo', 'project', 'read:org'],
130
+ bearer_methods_supported: ['header'],
131
+ resource_name: 'Giant Swarm PRO MCP Server'
132
+ };
133
+ // RFC 9728: path-specific document first (what the WWW-Authenticate
134
+ // challenge points at), root document as the fallback clients probe.
135
+ const metadataPath = `/.well-known/oauth-protected-resource${endpoint}`;
136
+ app.use(metadataPath, metadataHandler(protectedResourceMetadata));
137
+ app.use('/.well-known/oauth-protected-resource', metadataHandler(protectedResourceMetadata));
138
+
139
+ bearerAuthMiddleware = requireBearerAuth({
140
+ verifier: createGitHubTokenVerifier(),
141
+ resourceMetadataUrl: new URL(metadataPath, publicUrl).href
142
+ });
143
+
144
+ logger.info('Bearer-only auth enabled — MCP clients present GitHub tokens obtained elsewhere; no authorization server is run');
111
145
  } else {
112
146
  logger.info('OAuth not configured — using GITHUB_API_TOKEN for all requests');
113
147
  }