@giantswarm-io/pro 1.3.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/LICENSE +201 -0
- package/README.md +317 -0
- package/bin/index.js +65 -0
- package/package.json +40 -0
- package/src/index.js +49 -0
- package/src/lib/api.js +87 -0
- package/src/lib/auth/provider.js +395 -0
- package/src/lib/fields.js +111 -0
- package/src/lib/items.js +426 -0
- package/src/lib/logger.js +40 -0
- package/src/lib/mcp/http.js +233 -0
- package/src/lib/mcp/resources.js +304 -0
- package/src/lib/mcp/server.js +156 -0
- package/src/lib/mcp/sub-issues.js +580 -0
- package/src/lib/mcp/tools.js +601 -0
- package/src/lib/project.js +406 -0
- package/src/lib/rest-api.js +141 -0
- package/src/lib/selfupdate.js +107 -0
- package/src/lib/sub-issues.js +100 -0
- package/src/lib/utils.js +23 -0
- package/src/lib/version.js +19 -0
package/src/lib/api.js
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* GitHub API Communication Module
|
|
3
|
+
*
|
|
4
|
+
* Provides an authenticated GraphQL client and pagination support
|
|
5
|
+
* for the GitHub Projects V2 API.
|
|
6
|
+
*
|
|
7
|
+
* Supports per-request tokens (for OAuth/HTTP transport) with fallback
|
|
8
|
+
* to the GITHUB_API_TOKEN environment variable (for stdio transport).
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { graphql } from '@octokit/graphql';
|
|
12
|
+
import { logger } from './logger.js';
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Resolve the GitHub token to use for a request.
|
|
16
|
+
* Uses the explicit token if provided, otherwise falls back to the env var.
|
|
17
|
+
* @param {string} [token] - Explicit token for this request
|
|
18
|
+
* @returns {string} - The resolved token
|
|
19
|
+
* @throws {Error} - If no token is available
|
|
20
|
+
*/
|
|
21
|
+
function resolveToken(token) {
|
|
22
|
+
const resolved = token || process.env.GITHUB_API_TOKEN;
|
|
23
|
+
if (!resolved) {
|
|
24
|
+
throw new Error(
|
|
25
|
+
'No GitHub token available. Set GITHUB_API_TOKEN or authenticate via OAuth.'
|
|
26
|
+
);
|
|
27
|
+
}
|
|
28
|
+
return resolved;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Create a GraphQL client authenticated with the given token.
|
|
33
|
+
* @param {string} token - GitHub API token
|
|
34
|
+
* @returns {Function} - Configured graphql client
|
|
35
|
+
*/
|
|
36
|
+
function createGraphQLClient(token) {
|
|
37
|
+
return graphql.defaults({
|
|
38
|
+
headers: {
|
|
39
|
+
authorization: `bearer ${token}`
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Make a GraphQL request to GitHub API with authentication.
|
|
46
|
+
* @param {string} query - GraphQL query
|
|
47
|
+
* @param {Object} variables - Query variables
|
|
48
|
+
* @param {string} [token] - Optional per-request token (falls back to GITHUB_API_TOKEN)
|
|
49
|
+
* @returns {Promise<Object>} - Query result
|
|
50
|
+
*/
|
|
51
|
+
export async function graphQLWithAuth(query, variables = {}, token) {
|
|
52
|
+
const client = createGraphQLClient(resolveToken(token));
|
|
53
|
+
return await client(query, variables);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Fetch paginated results.
|
|
58
|
+
* @param {string} query - GraphQL query
|
|
59
|
+
* @param {Object} variables - Query variables
|
|
60
|
+
* @param {Function} getNextPage - Function to extract page info from result
|
|
61
|
+
* @param {string} [token] - Optional per-request token (falls back to GITHUB_API_TOKEN)
|
|
62
|
+
* @returns {Promise<Array>} - All results
|
|
63
|
+
*/
|
|
64
|
+
export async function fetchPaginated(query, variables, getNextPage, token) {
|
|
65
|
+
const allItems = [];
|
|
66
|
+
let hasNextPage = true;
|
|
67
|
+
let after = null;
|
|
68
|
+
|
|
69
|
+
while (hasNextPage) {
|
|
70
|
+
const queryVars = { ...variables };
|
|
71
|
+
if (after) {
|
|
72
|
+
queryVars.after = after;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const result = await graphQLWithAuth(query, queryVars, token);
|
|
76
|
+
const pageInfo = getNextPage(result);
|
|
77
|
+
|
|
78
|
+
if (pageInfo.nodes && Array.isArray(pageInfo.nodes)) {
|
|
79
|
+
allItems.push(...pageInfo.nodes);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
hasNextPage = pageInfo.pageInfo && pageInfo.pageInfo.hasNextPage;
|
|
83
|
+
after = pageInfo.pageInfo && pageInfo.pageInfo.endCursor;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
return allItems;
|
|
87
|
+
}
|
|
@@ -0,0 +1,395 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* GitHub OAuth Provider for MCP
|
|
3
|
+
*
|
|
4
|
+
* Implements the MCP SDK's OAuthServerProvider interface to authenticate
|
|
5
|
+
* users via GitHub OAuth. PRO acts as the OAuth authorization server,
|
|
6
|
+
* proxying the actual authentication to GitHub.
|
|
7
|
+
*
|
|
8
|
+
* Flow:
|
|
9
|
+
* 1. MCP client registers via /register → gets a local client_id
|
|
10
|
+
* 2. MCP client initiates /authorize with PKCE
|
|
11
|
+
* 3. PRO redirects to GitHub OAuth with our app's client_id
|
|
12
|
+
* 4. GitHub redirects back to /github/callback
|
|
13
|
+
* 5. PRO exchanges GitHub code for a token, stores it, redirects client
|
|
14
|
+
* 6. MCP client exchanges local code for the GitHub token via /token
|
|
15
|
+
* 7. MCP requests include the GitHub token as Bearer auth
|
|
16
|
+
*
|
|
17
|
+
* Environment variables:
|
|
18
|
+
* GITHUB_OAUTH_CLIENT_ID - GitHub OAuth App client ID
|
|
19
|
+
* 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)
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import { randomUUID } from 'crypto';
|
|
25
|
+
import { logger } from '../logger.js';
|
|
26
|
+
|
|
27
|
+
// TTL for authorization sessions (10 minutes)
|
|
28
|
+
const AUTH_SESSION_TTL_MS = 10 * 60 * 1000;
|
|
29
|
+
// TTL for cached token verifications (5 minutes)
|
|
30
|
+
const TOKEN_CACHE_TTL_MS = 5 * 60 * 1000;
|
|
31
|
+
// Maximum number of registered MCP clients kept in memory
|
|
32
|
+
const MAX_CLIENTS = 1000;
|
|
33
|
+
// GitHub OAuth scopes required by PRO's tools
|
|
34
|
+
const REQUIRED_GITHUB_SCOPES = ['repo', 'project', 'read:org'];
|
|
35
|
+
// TTL for cached CIMD fetches (1 hour) — avoids re-fetching on every authorize
|
|
36
|
+
const CIMD_CACHE_TTL_MS = 60 * 60 * 1000;
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Create the GitHub OAuth provider.
|
|
40
|
+
*
|
|
41
|
+
* @param {{ clientId: string, clientSecret: string }} config
|
|
42
|
+
* @returns {import('@modelcontextprotocol/sdk/server/auth/provider.js').OAuthServerProvider}
|
|
43
|
+
*/
|
|
44
|
+
export function createGitHubOAuthProvider(config) {
|
|
45
|
+
const { clientId, clientSecret } = config;
|
|
46
|
+
|
|
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.
|
|
49
|
+
const trustedClientIds = (process.env.OAUTH_TRUSTED_CLIENT_IDS || '')
|
|
50
|
+
.split(',')
|
|
51
|
+
.map(s => s.trim())
|
|
52
|
+
.filter(Boolean);
|
|
53
|
+
|
|
54
|
+
// In-memory registered MCP clients (UUID client_id → client metadata)
|
|
55
|
+
const clients = new Map();
|
|
56
|
+
|
|
57
|
+
// In-memory authorization sessions (state → session data)
|
|
58
|
+
const authSessions = new Map();
|
|
59
|
+
|
|
60
|
+
// In-memory local auth codes (code → { githubToken, clientId, redirectUri, codeChallenge })
|
|
61
|
+
const authCodes = new Map();
|
|
62
|
+
|
|
63
|
+
// Token verification cache (token → { authInfo, expiresAt })
|
|
64
|
+
const tokenCache = new Map();
|
|
65
|
+
|
|
66
|
+
// Periodic cleanup
|
|
67
|
+
const sweepInterval = setInterval(() => {
|
|
68
|
+
const now = Date.now();
|
|
69
|
+
for (const [key, session] of authSessions) {
|
|
70
|
+
if (now > session.expiresAt) authSessions.delete(key);
|
|
71
|
+
}
|
|
72
|
+
for (const [key, code] of authCodes) {
|
|
73
|
+
if (now > code.expiresAt) authCodes.delete(key);
|
|
74
|
+
}
|
|
75
|
+
for (const [key, entry] of tokenCache) {
|
|
76
|
+
if (now > entry.expiresAt) tokenCache.delete(key);
|
|
77
|
+
}
|
|
78
|
+
}, 60_000);
|
|
79
|
+
sweepInterval.unref();
|
|
80
|
+
|
|
81
|
+
// Cache for fetched CIMDs (URL → { metadata, expiresAt })
|
|
82
|
+
const cimdCache = new Map();
|
|
83
|
+
|
|
84
|
+
/**
|
|
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.
|
|
88
|
+
*/
|
|
89
|
+
async function fetchAndRegisterTrustedClient(clientId) {
|
|
90
|
+
if (!trustedClientIds.includes(clientId)) {
|
|
91
|
+
return undefined;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Check CIMD cache
|
|
95
|
+
const cached = cimdCache.get(clientId);
|
|
96
|
+
if (cached && Date.now() < cached.expiresAt) {
|
|
97
|
+
return clients.get(clientId);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
try {
|
|
101
|
+
const res = await fetch(clientId, {
|
|
102
|
+
headers: { Accept: 'application/json', 'User-Agent': 'giantswarm-pro-mcp' }
|
|
103
|
+
});
|
|
104
|
+
if (!res.ok) {
|
|
105
|
+
logger.warn(`OAuth: Failed to fetch CIMD from ${clientId}: ${res.status}`);
|
|
106
|
+
return undefined;
|
|
107
|
+
}
|
|
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;
|
|
127
|
+
} catch (err) {
|
|
128
|
+
logger.warn(`OAuth: Error fetching CIMD from ${clientId}: ${err.message}`);
|
|
129
|
+
return undefined;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Verify a GitHub access token by calling the GitHub API.
|
|
135
|
+
* Validates that the token has all required scopes.
|
|
136
|
+
* Results are cached briefly to avoid per-request API calls.
|
|
137
|
+
*/
|
|
138
|
+
async function verifyGitHubToken(token) {
|
|
139
|
+
const cached = tokenCache.get(token);
|
|
140
|
+
if (cached && Date.now() < cached.expiresAt) {
|
|
141
|
+
return cached.authInfo;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const res = await fetch('https://api.github.com/user', {
|
|
145
|
+
headers: {
|
|
146
|
+
Authorization: `Bearer ${token}`,
|
|
147
|
+
Accept: 'application/vnd.github+json',
|
|
148
|
+
'User-Agent': 'giantswarm-pro-mcp'
|
|
149
|
+
}
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
if (!res.ok) {
|
|
153
|
+
throw new Error(`GitHub token verification failed: ${res.status}`);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// Parse the actual scopes granted to this token
|
|
157
|
+
const scopeHeader = res.headers.get('x-oauth-scopes') || '';
|
|
158
|
+
const grantedScopes = scopeHeader.split(',').map(s => s.trim()).filter(Boolean);
|
|
159
|
+
|
|
160
|
+
// Reject tokens that are missing required scopes
|
|
161
|
+
const missingScopes = REQUIRED_GITHUB_SCOPES.filter(s => !grantedScopes.includes(s));
|
|
162
|
+
if (missingScopes.length > 0) {
|
|
163
|
+
throw new Error(`GitHub token is missing required scopes: ${missingScopes.join(', ')}`);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const user = await res.json();
|
|
167
|
+
|
|
168
|
+
const authInfo = {
|
|
169
|
+
token,
|
|
170
|
+
clientId: user.login,
|
|
171
|
+
scopes: grantedScopes,
|
|
172
|
+
expiresAt: Math.floor(Date.now() / 1000) + 3600 // 1 hour
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
tokenCache.set(token, {
|
|
176
|
+
authInfo,
|
|
177
|
+
expiresAt: Date.now() + TOKEN_CACHE_TTL_MS
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
return authInfo;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// -----------------------------------------------------------------------
|
|
184
|
+
// OAuthServerProvider implementation
|
|
185
|
+
// -----------------------------------------------------------------------
|
|
186
|
+
|
|
187
|
+
const provider = {
|
|
188
|
+
get clientsStore() {
|
|
189
|
+
return {
|
|
190
|
+
async getClient(clientId) {
|
|
191
|
+
const existing = clients.get(clientId);
|
|
192
|
+
if (existing) return existing;
|
|
193
|
+
// Auto-register if this is a trusted CIMD URL
|
|
194
|
+
return await fetchAndRegisterTrustedClient(clientId);
|
|
195
|
+
},
|
|
196
|
+
|
|
197
|
+
registerClient(clientMetadata) {
|
|
198
|
+
// Evict the oldest entry when the cap is reached
|
|
199
|
+
if (clients.size >= MAX_CLIENTS) {
|
|
200
|
+
const oldestKey = clients.keys().next().value;
|
|
201
|
+
clients.delete(oldestKey);
|
|
202
|
+
logger.warn(`OAuth: Client store full (${MAX_CLIENTS}), evicted oldest client ${oldestKey}`);
|
|
203
|
+
}
|
|
204
|
+
const id = randomUUID();
|
|
205
|
+
const now = Math.floor(Date.now() / 1000);
|
|
206
|
+
const clientInfo = {
|
|
207
|
+
...clientMetadata,
|
|
208
|
+
client_id: id,
|
|
209
|
+
client_id_issued_at: now
|
|
210
|
+
};
|
|
211
|
+
clients.set(id, clientInfo);
|
|
212
|
+
logger.info(`OAuth: Registered MCP client ${id}`);
|
|
213
|
+
return clientInfo;
|
|
214
|
+
}
|
|
215
|
+
};
|
|
216
|
+
},
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Start the authorization flow: redirect user to GitHub.
|
|
220
|
+
*/
|
|
221
|
+
async authorize(client, params, res) {
|
|
222
|
+
// Defense-in-depth: the MCP SDK already validates redirect_uri, but
|
|
223
|
+
// re-check here since an open-redirect would be severe.
|
|
224
|
+
if (client.redirect_uris?.length && !client.redirect_uris.includes(params.redirectUri)) {
|
|
225
|
+
throw new Error('redirect_uri does not match registered URIs');
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
const state = randomUUID();
|
|
229
|
+
|
|
230
|
+
// Store session for when GitHub redirects back
|
|
231
|
+
authSessions.set(state, {
|
|
232
|
+
mcpClientId: client.client_id,
|
|
233
|
+
redirectUri: params.redirectUri,
|
|
234
|
+
codeChallenge: params.codeChallenge,
|
|
235
|
+
clientState: params.state,
|
|
236
|
+
expiresAt: Date.now() + AUTH_SESSION_TTL_MS
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
// Redirect to GitHub OAuth
|
|
240
|
+
const githubUrl = new URL('https://github.com/login/oauth/authorize');
|
|
241
|
+
githubUrl.searchParams.set('client_id', clientId);
|
|
242
|
+
githubUrl.searchParams.set('state', state);
|
|
243
|
+
githubUrl.searchParams.set('allow_signup', 'false');
|
|
244
|
+
|
|
245
|
+
// Always request the fixed set of GitHub scopes required by PRO's tools
|
|
246
|
+
const githubScopes = ['repo', 'project', 'read:org'];
|
|
247
|
+
githubUrl.searchParams.set('scope', githubScopes.join(' '));
|
|
248
|
+
|
|
249
|
+
res.redirect(githubUrl.toString());
|
|
250
|
+
},
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Return the PKCE code challenge for a local authorization code.
|
|
254
|
+
*/
|
|
255
|
+
async challengeForAuthorizationCode(_client, authorizationCode) {
|
|
256
|
+
const entry = authCodes.get(authorizationCode);
|
|
257
|
+
if (!entry) {
|
|
258
|
+
throw new Error('Authorization code not found or expired');
|
|
259
|
+
}
|
|
260
|
+
return entry.codeChallenge;
|
|
261
|
+
},
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Exchange a local authorization code for the stored GitHub token.
|
|
265
|
+
*/
|
|
266
|
+
async exchangeAuthorizationCode(client, authorizationCode) {
|
|
267
|
+
const entry = authCodes.get(authorizationCode);
|
|
268
|
+
if (!entry) {
|
|
269
|
+
throw new Error('Authorization code not found or expired');
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
if (entry.clientId !== client.client_id) {
|
|
273
|
+
throw new Error('Authorization code was issued to a different client');
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// Delete the code (single use)
|
|
277
|
+
authCodes.delete(authorizationCode);
|
|
278
|
+
|
|
279
|
+
const tokens = {
|
|
280
|
+
access_token: entry.githubToken,
|
|
281
|
+
token_type: 'Bearer'
|
|
282
|
+
};
|
|
283
|
+
// Pass through the actual scope GitHub granted rather than hardcoding
|
|
284
|
+
if (entry.githubScope) {
|
|
285
|
+
tokens.scope = entry.githubScope;
|
|
286
|
+
}
|
|
287
|
+
// Omit expires_in — classic GitHub OAuth tokens don't expire, and we
|
|
288
|
+
// don't support refresh tokens, so a hardcoded TTL would just force
|
|
289
|
+
// clients into an unnecessary re-authorize loop.
|
|
290
|
+
return tokens;
|
|
291
|
+
},
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* Refresh tokens — GitHub OAuth doesn't support refresh tokens,
|
|
295
|
+
* so we reject these requests.
|
|
296
|
+
*/
|
|
297
|
+
async exchangeRefreshToken() {
|
|
298
|
+
throw new Error('Refresh tokens are not supported. Re-authorize to get a new token.');
|
|
299
|
+
},
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Verify an access token (which is a GitHub token).
|
|
303
|
+
*/
|
|
304
|
+
async verifyAccessToken(token) {
|
|
305
|
+
return await verifyGitHubToken(token);
|
|
306
|
+
}
|
|
307
|
+
};
|
|
308
|
+
|
|
309
|
+
// -----------------------------------------------------------------------
|
|
310
|
+
// GitHub callback handler (mounted as an Express route)
|
|
311
|
+
// -----------------------------------------------------------------------
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* Handle GitHub's OAuth redirect.
|
|
315
|
+
* Exchange GitHub code for token, generate local auth code, redirect to MCP client.
|
|
316
|
+
*/
|
|
317
|
+
async function handleGitHubCallback(req, res) {
|
|
318
|
+
const { code, state } = req.query;
|
|
319
|
+
|
|
320
|
+
if (!code || !state) {
|
|
321
|
+
res.status(400).json({ error: 'Missing code or state parameter' });
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
const session = authSessions.get(state);
|
|
326
|
+
if (!session) {
|
|
327
|
+
res.status(400).json({ error: 'Invalid or expired authorization session' });
|
|
328
|
+
return;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
if (session.expiresAt <= Date.now()) {
|
|
332
|
+
authSessions.delete(state);
|
|
333
|
+
res.status(400).json({ error: 'Invalid or expired authorization session' });
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
// Clean up the session
|
|
337
|
+
authSessions.delete(state);
|
|
338
|
+
|
|
339
|
+
try {
|
|
340
|
+
// Exchange GitHub code for access token
|
|
341
|
+
const tokenRes = await fetch('https://github.com/login/oauth/access_token', {
|
|
342
|
+
method: 'POST',
|
|
343
|
+
headers: {
|
|
344
|
+
'Content-Type': 'application/json',
|
|
345
|
+
Accept: 'application/json'
|
|
346
|
+
},
|
|
347
|
+
body: JSON.stringify({
|
|
348
|
+
client_id: clientId,
|
|
349
|
+
client_secret: clientSecret,
|
|
350
|
+
code
|
|
351
|
+
})
|
|
352
|
+
});
|
|
353
|
+
|
|
354
|
+
const tokenData = await tokenRes.json();
|
|
355
|
+
|
|
356
|
+
if (tokenData.error) {
|
|
357
|
+
logger.error('GitHub OAuth token exchange failed', { error: tokenData.error });
|
|
358
|
+
res.status(400).json({ error: `GitHub OAuth error: ${tokenData.error_description || tokenData.error}` });
|
|
359
|
+
return;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
if (!tokenData.access_token) {
|
|
363
|
+
logger.error('GitHub OAuth: no access_token in response');
|
|
364
|
+
res.status(502).json({ error: 'GitHub did not return an access token' });
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// Generate a local authorization code for the MCP client
|
|
369
|
+
const localCode = randomUUID();
|
|
370
|
+
|
|
371
|
+
authCodes.set(localCode, {
|
|
372
|
+
githubToken: tokenData.access_token,
|
|
373
|
+
githubScope: tokenData.scope,
|
|
374
|
+
clientId: session.mcpClientId,
|
|
375
|
+
redirectUri: session.redirectUri,
|
|
376
|
+
codeChallenge: session.codeChallenge,
|
|
377
|
+
expiresAt: Date.now() + AUTH_SESSION_TTL_MS
|
|
378
|
+
});
|
|
379
|
+
|
|
380
|
+
// Redirect back to the MCP client's redirect_uri with our local code
|
|
381
|
+
const redirectUrl = new URL(session.redirectUri);
|
|
382
|
+
redirectUrl.searchParams.set('code', localCode);
|
|
383
|
+
if (session.clientState) {
|
|
384
|
+
redirectUrl.searchParams.set('state', session.clientState);
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
res.redirect(redirectUrl.toString());
|
|
388
|
+
} catch (err) {
|
|
389
|
+
logger.error('GitHub OAuth callback error', { error: err.message });
|
|
390
|
+
res.status(500).json({ error: 'Failed to complete GitHub authentication' });
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
return { provider, handleGitHubCallback };
|
|
395
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fields Management Module
|
|
3
|
+
*
|
|
4
|
+
* Provides functions to list, find, and match GitHub Project V2 fields
|
|
5
|
+
* on a given project board. All functions return data directly
|
|
6
|
+
* without console output.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { fetchPaginated } from './api.js';
|
|
10
|
+
import { LIST_FIELDS_QUERY } from './project.js';
|
|
11
|
+
import { normalizeFieldValue } from './utils.js';
|
|
12
|
+
import { logger } from './logger.js';
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* List all fields in a project board
|
|
16
|
+
* @param {string} boardId - The GitHub project node ID
|
|
17
|
+
* @param {string} [token] - Optional per-request GitHub token
|
|
18
|
+
* @returns {Promise<Array>} - Array of field objects
|
|
19
|
+
*/
|
|
20
|
+
export async function listFields(boardId, token) {
|
|
21
|
+
const first = 100;
|
|
22
|
+
try {
|
|
23
|
+
const allFields = await fetchPaginated(
|
|
24
|
+
LIST_FIELDS_QUERY,
|
|
25
|
+
{ projectId: boardId, first },
|
|
26
|
+
result => result.node.fields,
|
|
27
|
+
token
|
|
28
|
+
);
|
|
29
|
+
|
|
30
|
+
return allFields;
|
|
31
|
+
} catch (error) {
|
|
32
|
+
logger.error(`Error fetching fields: ${error.message}`);
|
|
33
|
+
throw error;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Updatable field __typename values.
|
|
39
|
+
* - ProjectV2SingleSelectField: single-select fields (Status, Kind, etc.)
|
|
40
|
+
* - ProjectV2IterationField: iteration fields (Quarter, Sprint, etc.)
|
|
41
|
+
* - ProjectV2Field with dataType DATE: date fields (Start Date, Target Date, etc.)
|
|
42
|
+
*/
|
|
43
|
+
const UPDATABLE_FIELD_TYPES = new Set([
|
|
44
|
+
'ProjectV2SingleSelectField',
|
|
45
|
+
'ProjectV2IterationField',
|
|
46
|
+
]);
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Find a field by name in a project board.
|
|
50
|
+
* Returns single-select, iteration, and date fields that can be updated.
|
|
51
|
+
* @param {string} fieldName - The name of the field to find (case insensitive)
|
|
52
|
+
* @param {string} boardId - The GitHub project node ID
|
|
53
|
+
* @param {string} [token] - Optional per-request GitHub token
|
|
54
|
+
* @returns {Promise<Object|null>} - The field object or null if not found
|
|
55
|
+
*/
|
|
56
|
+
export async function findFieldByName(fieldName, boardId, token) {
|
|
57
|
+
const allFields = await listFields(boardId, token);
|
|
58
|
+
|
|
59
|
+
const field = allFields.find(field => {
|
|
60
|
+
if (field.name.toLowerCase() !== fieldName.toLowerCase()) return false;
|
|
61
|
+
if (UPDATABLE_FIELD_TYPES.has(field.__typename)) return true;
|
|
62
|
+
// ProjectV2Field with dataType DATE
|
|
63
|
+
if (field.__typename === 'ProjectV2Field' && field.dataType === 'DATE') return true;
|
|
64
|
+
return false;
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
return field || null;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Find a matching option in a field's options
|
|
72
|
+
* @param {Array} options - Field options
|
|
73
|
+
* @param {string} optionName - The name to match
|
|
74
|
+
* @returns {Object|null} - Matching option or null
|
|
75
|
+
*/
|
|
76
|
+
export function findMatchingOption(options, optionName) {
|
|
77
|
+
if (!optionName) return null;
|
|
78
|
+
|
|
79
|
+
// Try direct match first
|
|
80
|
+
const exactMatch = options.find(option => option.name === optionName);
|
|
81
|
+
if (exactMatch) return exactMatch;
|
|
82
|
+
|
|
83
|
+
// Try case-insensitive match with normalization
|
|
84
|
+
const normalizedName = normalizeFieldValue(optionName);
|
|
85
|
+
return options.find(option => {
|
|
86
|
+
const normalizedOption = normalizeFieldValue(option.name);
|
|
87
|
+
return normalizedOption === normalizedName;
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Find a matching iteration in a field's iteration configuration
|
|
93
|
+
* @param {Object} field - An iteration field with configuration.iterations[]
|
|
94
|
+
* @param {string} value - The iteration title to match (e.g. "Q2 2026")
|
|
95
|
+
* @returns {Object|null} - Matching iteration {id, title, startDate, duration} or null
|
|
96
|
+
*/
|
|
97
|
+
export function findMatchingIteration(field, value) {
|
|
98
|
+
const iterations = field.configuration?.iterations;
|
|
99
|
+
if (!iterations?.length || !value) return null;
|
|
100
|
+
|
|
101
|
+
// Try direct match first
|
|
102
|
+
const exactMatch = iterations.find(iter => iter.title === value);
|
|
103
|
+
if (exactMatch) return exactMatch;
|
|
104
|
+
|
|
105
|
+
// Try case-insensitive match with normalization
|
|
106
|
+
const normalizedValue = normalizeFieldValue(value);
|
|
107
|
+
return iterations.find(iter => {
|
|
108
|
+
const normalizedTitle = normalizeFieldValue(iter.title);
|
|
109
|
+
return normalizedTitle === normalizedValue;
|
|
110
|
+
}) || null;
|
|
111
|
+
}
|