copilot-agents-mcp 0.0.0-stage → 0.0.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 +21 -0
- package/README.md +248 -2
- package/dist/auth.js +584 -0
- package/dist/cli.js +328 -0
- package/dist/errors.js +197 -0
- package/dist/github.js +321 -0
- package/dist/http.js +77 -0
- package/dist/keyring.js +39 -0
- package/dist/notify.js +129 -0
- package/dist/selection.js +115 -0
- package/dist/server.js +389 -0
- package/dist/state.js +324 -0
- package/dist/swe-models.js +226 -0
- package/dist/watch.js +180 -0
- package/fixtures/openapi/create-task.request.json +45 -0
- package/fixtures/openapi/create-task.response.json +234 -0
- package/fixtures/openapi/get-task.response.json +413 -0
- package/package.json +49 -4
package/dist/auth.js
ADDED
|
@@ -0,0 +1,584 @@
|
|
|
1
|
+
import { userInfo } from "node:os";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { API_VERSION, appNotInstalledMessage, AuthError, KeyringError, NO_SESSION_MESSAGE, redact, redactTokenShapes } from "./errors.js";
|
|
4
|
+
import { withDirectoryLock } from "./state.js";
|
|
5
|
+
export const KEYRING_SERVICE = "copilot-agents-mcp:github.com";
|
|
6
|
+
export const DEFAULT_GITHUB_APP_CLIENT_ID = "Iv23liNbsc3GH7vmP8OT";
|
|
7
|
+
export const ACCESS_TOKEN_REFRESH_MARGIN_MS = 5 * 60 * 1000;
|
|
8
|
+
const DEVICE_CODE_URL = "https://github.com/login/device/code";
|
|
9
|
+
const ACCESS_TOKEN_URL = "https://github.com/login/oauth/access_token";
|
|
10
|
+
const DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
|
|
11
|
+
const MARGIN_MINUTES = ACCESS_TOKEN_REFRESH_MARGIN_MS / 60_000;
|
|
12
|
+
const RELOGIN_MESSAGE = "The GitHub session expired or is no longer valid. Run `npx copilot-agents-mcp login`.";
|
|
13
|
+
const REFRESH_NOT_SAVED = "The refresh token stored in the keyring is no longer valid. The new session remains in memory, and saving it will be retried. If this process exits before the save succeeds, run `npx copilot-agents-mcp login`.";
|
|
14
|
+
const WRITE_ATTEMPTS = 3;
|
|
15
|
+
const WRITE_RETRY_DELAY_MS = 50;
|
|
16
|
+
const OAUTH_TIMEOUT_MS = 30_000;
|
|
17
|
+
const APP_LOOKUP_TIMEOUT_MS = 10_000;
|
|
18
|
+
class BadRefreshToken extends Error {
|
|
19
|
+
constructor() {
|
|
20
|
+
super("bad_refresh_token");
|
|
21
|
+
this.name = "BadRefreshToken";
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
export function systemAccount() {
|
|
25
|
+
try {
|
|
26
|
+
const name = userInfo().username.trim();
|
|
27
|
+
return name || "user";
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
return "user";
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
export function githubAppClientId(env) {
|
|
34
|
+
const override = env.COPILOT_AGENTS_GITHUB_APP_CLIENT_ID;
|
|
35
|
+
if (typeof override === "string" && override.trim())
|
|
36
|
+
return override.trim();
|
|
37
|
+
return DEFAULT_GITHUB_APP_CLIENT_ID;
|
|
38
|
+
}
|
|
39
|
+
export function personalAccessToken(env) {
|
|
40
|
+
const value = env.GITHUB_PERSONAL_ACCESS_TOKEN;
|
|
41
|
+
if (typeof value !== "string")
|
|
42
|
+
return null;
|
|
43
|
+
const trimmed = value.trim();
|
|
44
|
+
return trimmed ? trimmed : null;
|
|
45
|
+
}
|
|
46
|
+
export function readActiveToken(env, readApp) {
|
|
47
|
+
return personalAccessToken(env) ?? readApp();
|
|
48
|
+
}
|
|
49
|
+
export function ignoredTokenWarning(env) {
|
|
50
|
+
if (personalAccessToken(env))
|
|
51
|
+
return null;
|
|
52
|
+
const names = ["GH_TOKEN", "GITHUB_TOKEN"].filter((name) => {
|
|
53
|
+
const value = env[name];
|
|
54
|
+
return typeof value === "string" && value.trim() !== "";
|
|
55
|
+
});
|
|
56
|
+
if (names.length === 0)
|
|
57
|
+
return null;
|
|
58
|
+
const verb = names.length === 1 ? "is ignored" : "are ignored";
|
|
59
|
+
return `${names.join(" and ")} ${verb}. Set GITHUB_PERSONAL_ACCESS_TOKEN or run \`npx copilot-agents-mcp login\`.`;
|
|
60
|
+
}
|
|
61
|
+
export function authLockPath(statePath) {
|
|
62
|
+
return join(dirname(statePath), "auth.lock");
|
|
63
|
+
}
|
|
64
|
+
export function createMemoryStore() {
|
|
65
|
+
let value = null;
|
|
66
|
+
return {
|
|
67
|
+
read: () => value,
|
|
68
|
+
write: (next) => {
|
|
69
|
+
value = next;
|
|
70
|
+
},
|
|
71
|
+
delete: () => {
|
|
72
|
+
value = null;
|
|
73
|
+
},
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
export function createAppSession(options) {
|
|
77
|
+
let memory = null;
|
|
78
|
+
let pendingSave = false;
|
|
79
|
+
let storeUnread = false;
|
|
80
|
+
let inflight = null;
|
|
81
|
+
let warnedStore = false;
|
|
82
|
+
let warnedSave = false;
|
|
83
|
+
const sleep = options.sleep ?? ((ms) => new Promise((resolve) => {
|
|
84
|
+
setTimeout(resolve, ms);
|
|
85
|
+
}));
|
|
86
|
+
function warnStore(message) {
|
|
87
|
+
if (warnedStore)
|
|
88
|
+
return;
|
|
89
|
+
warnedStore = true;
|
|
90
|
+
options.warn(redactTokenShapes(message));
|
|
91
|
+
}
|
|
92
|
+
function warnSave() {
|
|
93
|
+
if (warnedSave)
|
|
94
|
+
return;
|
|
95
|
+
warnedSave = true;
|
|
96
|
+
options.warn(redactTokenShapes(REFRESH_NOT_SAVED));
|
|
97
|
+
}
|
|
98
|
+
function tryWrite(credential) {
|
|
99
|
+
try {
|
|
100
|
+
options.store.write(serialize(credential));
|
|
101
|
+
return true;
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
return false;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
async function persist(credential) {
|
|
108
|
+
memory = credential;
|
|
109
|
+
pendingSave = true;
|
|
110
|
+
for (let attempt = 0; attempt < WRITE_ATTEMPTS; attempt += 1) {
|
|
111
|
+
if (attempt > 0)
|
|
112
|
+
await sleep(WRITE_RETRY_DELAY_MS);
|
|
113
|
+
if (tryWrite(credential)) {
|
|
114
|
+
pendingSave = false;
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
warnSave();
|
|
119
|
+
}
|
|
120
|
+
function read() {
|
|
121
|
+
if (pendingSave) {
|
|
122
|
+
if (memory && tryWrite(memory))
|
|
123
|
+
pendingSave = false;
|
|
124
|
+
return memory;
|
|
125
|
+
}
|
|
126
|
+
if (storeUnread)
|
|
127
|
+
return memory;
|
|
128
|
+
try {
|
|
129
|
+
const raw = options.store.read();
|
|
130
|
+
if (raw === null) {
|
|
131
|
+
memory = null;
|
|
132
|
+
return null;
|
|
133
|
+
}
|
|
134
|
+
const parsed = parseStored(raw);
|
|
135
|
+
if (!parsed) {
|
|
136
|
+
warnStore("The keyring session cannot be read. Run `npx copilot-agents-mcp login`.");
|
|
137
|
+
memory = null;
|
|
138
|
+
return null;
|
|
139
|
+
}
|
|
140
|
+
memory = parsed;
|
|
141
|
+
return parsed;
|
|
142
|
+
}
|
|
143
|
+
catch (error) {
|
|
144
|
+
if (!(error instanceof KeyringError))
|
|
145
|
+
throw error;
|
|
146
|
+
warnStore(`No keyring is available (${error.message}). The token remains only in this process's memory and is not written to disk.`);
|
|
147
|
+
return memory;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
function clear() {
|
|
151
|
+
memory = null;
|
|
152
|
+
pendingSave = false;
|
|
153
|
+
try {
|
|
154
|
+
options.store.delete();
|
|
155
|
+
}
|
|
156
|
+
catch (error) {
|
|
157
|
+
if (!(error instanceof KeyringError))
|
|
158
|
+
throw error;
|
|
159
|
+
storeUnread = true;
|
|
160
|
+
warnStore(`Could not delete the keyring session (${error.message}). The token has not been written to disk.`);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
function begin(rejected) {
|
|
164
|
+
if (inflight)
|
|
165
|
+
return inflight;
|
|
166
|
+
inflight = (async () => {
|
|
167
|
+
try {
|
|
168
|
+
return await withDirectoryLock(options.lockPath, () => refreshLocked(rejected), {
|
|
169
|
+
timeoutMs: 60_000,
|
|
170
|
+
busyMessage: "Could not refresh the session: the refresh lock is in use.",
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
finally {
|
|
174
|
+
inflight = null;
|
|
175
|
+
}
|
|
176
|
+
})();
|
|
177
|
+
return inflight;
|
|
178
|
+
}
|
|
179
|
+
async function refreshLocked(rejected) {
|
|
180
|
+
const latest = read();
|
|
181
|
+
if (latest && reusable(latest, rejected, options.now()))
|
|
182
|
+
return latest;
|
|
183
|
+
if (!latest)
|
|
184
|
+
throw new AuthError(NO_SESSION_MESSAGE);
|
|
185
|
+
if (latest.refresh_expires_at !== null && latest.refresh_expires_at <= options.now()) {
|
|
186
|
+
clear();
|
|
187
|
+
throw new AuthError(RELOGIN_MESSAGE);
|
|
188
|
+
}
|
|
189
|
+
try {
|
|
190
|
+
const grant = await requestRefresh(options.clientId, latest.refresh_token, options.fetchImpl);
|
|
191
|
+
const next = toStored(grant, options.now());
|
|
192
|
+
await persist(next);
|
|
193
|
+
return next;
|
|
194
|
+
}
|
|
195
|
+
catch (error) {
|
|
196
|
+
if (error instanceof BadRefreshToken) {
|
|
197
|
+
clear();
|
|
198
|
+
throw new AuthError(RELOGIN_MESSAGE);
|
|
199
|
+
}
|
|
200
|
+
throw error;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
return {
|
|
204
|
+
peek() {
|
|
205
|
+
return read()?.access_token ?? null;
|
|
206
|
+
},
|
|
207
|
+
stored() {
|
|
208
|
+
const credential = read();
|
|
209
|
+
return credential ? { ...credential } : null;
|
|
210
|
+
},
|
|
211
|
+
async current() {
|
|
212
|
+
if (inflight)
|
|
213
|
+
return (await inflight).access_token;
|
|
214
|
+
const credential = read();
|
|
215
|
+
if (!credential)
|
|
216
|
+
throw new AuthError(NO_SESSION_MESSAGE);
|
|
217
|
+
if (!expiring(credential, options.now()))
|
|
218
|
+
return credential.access_token;
|
|
219
|
+
return (await begin()).access_token;
|
|
220
|
+
},
|
|
221
|
+
async refresh(rejected) {
|
|
222
|
+
if (inflight) {
|
|
223
|
+
const next = await inflight;
|
|
224
|
+
if (next.access_token !== rejected)
|
|
225
|
+
return next.access_token;
|
|
226
|
+
}
|
|
227
|
+
const credential = read();
|
|
228
|
+
if (credential && credential.access_token !== rejected && !expiring(credential, options.now())) {
|
|
229
|
+
return credential.access_token;
|
|
230
|
+
}
|
|
231
|
+
return (await begin(rejected)).access_token;
|
|
232
|
+
},
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
export async function loginWithDeviceFlow(options) {
|
|
236
|
+
const device = await requestDeviceCode(options.clientId, options.fetchImpl);
|
|
237
|
+
const minutes = Math.max(1, Math.round(device.expiresIn / 60));
|
|
238
|
+
options.stdout(`Open ${device.verificationUri}`);
|
|
239
|
+
options.stdout(`Enter code ${device.userCode}.`);
|
|
240
|
+
options.stdout(`The code expires in ${minutes} minutes. Do not enter a code that you did not request.`);
|
|
241
|
+
const grant = await pollDevice(device, options);
|
|
242
|
+
const credential = toStored(grant, options.now());
|
|
243
|
+
const encoded = serialize(credential);
|
|
244
|
+
if (!options.persistent) {
|
|
245
|
+
options.store.write(encoded);
|
|
246
|
+
options.stderr("No keyring is available. The token remains only in this process's memory, is not written to disk, and is lost when the process exits.");
|
|
247
|
+
await warnIfAppNotInstalled(credential.access_token, options);
|
|
248
|
+
return { where: "memory", credential };
|
|
249
|
+
}
|
|
250
|
+
try {
|
|
251
|
+
options.store.write(encoded);
|
|
252
|
+
}
|
|
253
|
+
catch (error) {
|
|
254
|
+
if (!(error instanceof KeyringError))
|
|
255
|
+
throw error;
|
|
256
|
+
options.stderr(redactTokenShapes(`No keyring is available (${error.message}). The token remains only in this process's memory, is not written to disk, and is lost when the process exits.`));
|
|
257
|
+
await warnIfAppNotInstalled(credential.access_token, options);
|
|
258
|
+
return { where: "memory", credential };
|
|
259
|
+
}
|
|
260
|
+
options.stdout("Session saved in the system keyring.");
|
|
261
|
+
await warnIfAppNotInstalled(credential.access_token, options);
|
|
262
|
+
return { where: "keyring", credential };
|
|
263
|
+
}
|
|
264
|
+
export function logoutLocal(store) {
|
|
265
|
+
let existing;
|
|
266
|
+
try {
|
|
267
|
+
existing = store.read();
|
|
268
|
+
}
|
|
269
|
+
catch (error) {
|
|
270
|
+
if (error instanceof KeyringError)
|
|
271
|
+
return "unavailable";
|
|
272
|
+
throw error;
|
|
273
|
+
}
|
|
274
|
+
try {
|
|
275
|
+
store.delete();
|
|
276
|
+
}
|
|
277
|
+
catch (error) {
|
|
278
|
+
if (error instanceof KeyringError)
|
|
279
|
+
return "unavailable";
|
|
280
|
+
throw error;
|
|
281
|
+
}
|
|
282
|
+
return existing ? "removed" : "absent";
|
|
283
|
+
}
|
|
284
|
+
export function logoutMessage(result) {
|
|
285
|
+
const head = result === "removed"
|
|
286
|
+
? "The keyring session was deleted."
|
|
287
|
+
: result === "absent"
|
|
288
|
+
? "No keyring session was found."
|
|
289
|
+
: "The keyring could not be used. The token has not been written to disk.";
|
|
290
|
+
return [
|
|
291
|
+
head,
|
|
292
|
+
"To revoke access: GitHub → Settings → Applications → Authorized GitHub Apps.",
|
|
293
|
+
"To remove the app from a repository or organization, uninstall it.",
|
|
294
|
+
].join("\n");
|
|
295
|
+
}
|
|
296
|
+
export function statusReport(input) {
|
|
297
|
+
if (personalAccessToken(input.env)) {
|
|
298
|
+
const lines = ["Active credential: PAT (GITHUB_PERSONAL_ACCESS_TOKEN environment variable)."];
|
|
299
|
+
if (input.stored)
|
|
300
|
+
lines.push("A GitHub App session is stored, but it is not used while that variable is set.");
|
|
301
|
+
return lines.join("\n");
|
|
302
|
+
}
|
|
303
|
+
if (!input.stored)
|
|
304
|
+
return NO_SESSION_MESSAGE;
|
|
305
|
+
const where = input.keyring === "memory"
|
|
306
|
+
? "only in this process's memory"
|
|
307
|
+
: `in the system keyring (account "${input.account}")`;
|
|
308
|
+
const clientId = githubAppClientId(input.env);
|
|
309
|
+
const source = clientIdFromEnv(input.env)
|
|
310
|
+
? "COPILOT_AGENTS_GITHUB_APP_CLIENT_ID environment variable"
|
|
311
|
+
: "default value";
|
|
312
|
+
const appName = input.appName?.trim() || "unknown";
|
|
313
|
+
const lines = [
|
|
314
|
+
`Active credential: GitHub App, ${where}.`,
|
|
315
|
+
input.appNotInstalled ? appNotInstalledMessage() : `App: ${appName}.`,
|
|
316
|
+
`Client ID: ${clientId} (${source}).`,
|
|
317
|
+
`The access token expires at ${new Date(input.stored.expires_at).toISOString()}. It refreshes ${MARGIN_MINUTES} minutes before expiry and also when GitHub returns 401.`,
|
|
318
|
+
];
|
|
319
|
+
if (input.stored.refresh_expires_at !== null) {
|
|
320
|
+
lines.push(`The refresh token expires at ${new Date(input.stored.refresh_expires_at).toISOString()}.`);
|
|
321
|
+
}
|
|
322
|
+
else {
|
|
323
|
+
lines.push("The refresh token has no expiry time.");
|
|
324
|
+
}
|
|
325
|
+
if (input.keyring === "memory")
|
|
326
|
+
lines.push("No keyring is available. The token is not on disk and is lost when the process exits.");
|
|
327
|
+
return lines.join("\n");
|
|
328
|
+
}
|
|
329
|
+
export async function readGitHubAppName(accessToken, fetchImpl) {
|
|
330
|
+
return (await readGitHubApp(accessToken, fetchImpl)).name;
|
|
331
|
+
}
|
|
332
|
+
export async function readGitHubApp(accessToken, fetchImpl) {
|
|
333
|
+
try {
|
|
334
|
+
const body = await readGitHubJson(fetchImpl, "https://api.github.com/user/installations", accessToken);
|
|
335
|
+
if (!body)
|
|
336
|
+
return { name: null, empty: false };
|
|
337
|
+
if (body.total_count === 0)
|
|
338
|
+
return { name: null, empty: true };
|
|
339
|
+
const slug = installedAppSlug(body);
|
|
340
|
+
if (!slug)
|
|
341
|
+
return { name: null, empty: false };
|
|
342
|
+
const app = await readGitHubJson(fetchImpl, `https://api.github.com/apps/${encodeURIComponent(slug)}`);
|
|
343
|
+
const name = app && typeof app.name === "string" ? app.name.trim() : "";
|
|
344
|
+
return { name: name || null, empty: false };
|
|
345
|
+
}
|
|
346
|
+
catch {
|
|
347
|
+
return { name: null, empty: false };
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
async function warnIfAppNotInstalled(accessToken, options) {
|
|
351
|
+
const app = await readGitHubApp(accessToken, options.fetchImpl);
|
|
352
|
+
if (app.empty)
|
|
353
|
+
options.stdout(appNotInstalledMessage());
|
|
354
|
+
}
|
|
355
|
+
function clientIdFromEnv(env) {
|
|
356
|
+
const override = env.COPILOT_AGENTS_GITHUB_APP_CLIENT_ID;
|
|
357
|
+
return typeof override === "string" && override.trim() !== "";
|
|
358
|
+
}
|
|
359
|
+
function installedAppSlug(body) {
|
|
360
|
+
const installations = body.installations;
|
|
361
|
+
if (!Array.isArray(installations))
|
|
362
|
+
return null;
|
|
363
|
+
for (const item of installations) {
|
|
364
|
+
if (!item || typeof item !== "object")
|
|
365
|
+
continue;
|
|
366
|
+
const slug = "app_slug" in item ? item.app_slug : undefined;
|
|
367
|
+
if (typeof slug === "string" && slug.trim())
|
|
368
|
+
return slug.trim();
|
|
369
|
+
}
|
|
370
|
+
return null;
|
|
371
|
+
}
|
|
372
|
+
async function readGitHubJson(fetchImpl, url, token) {
|
|
373
|
+
const headers = {
|
|
374
|
+
accept: "application/vnd.github+json",
|
|
375
|
+
"user-agent": "copilot-agents-mcp",
|
|
376
|
+
"x-github-api-version": API_VERSION,
|
|
377
|
+
};
|
|
378
|
+
if (token)
|
|
379
|
+
headers.authorization = `Bearer ${token}`;
|
|
380
|
+
const response = await fetchImpl(url, {
|
|
381
|
+
method: "GET",
|
|
382
|
+
headers,
|
|
383
|
+
redirect: "error",
|
|
384
|
+
signal: AbortSignal.timeout(APP_LOOKUP_TIMEOUT_MS),
|
|
385
|
+
});
|
|
386
|
+
if (!response.ok)
|
|
387
|
+
return null;
|
|
388
|
+
const parsed = await response.json();
|
|
389
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
390
|
+
return null;
|
|
391
|
+
return parsed;
|
|
392
|
+
}
|
|
393
|
+
async function requestDeviceCode(clientId, fetchImpl) {
|
|
394
|
+
const body = await postOAuth(DEVICE_CODE_URL, {
|
|
395
|
+
client_id: clientId,
|
|
396
|
+
scope: "offline_access",
|
|
397
|
+
}, fetchImpl, []);
|
|
398
|
+
if (typeof body.error === "string")
|
|
399
|
+
throw new AuthError(safeOAuthMessage("GitHub rejected the device flow", body, []));
|
|
400
|
+
if (typeof body.device_code !== "string" || typeof body.user_code !== "string") {
|
|
401
|
+
throw new AuthError("GitHub did not return a verification code.");
|
|
402
|
+
}
|
|
403
|
+
const expiresIn = typeof body.expires_in === "number" && body.expires_in > 0 ? body.expires_in : 900;
|
|
404
|
+
const interval = typeof body.interval === "number" && body.interval >= 1 ? body.interval : 5;
|
|
405
|
+
const verificationUri = typeof body.verification_uri === "string" && body.verification_uri
|
|
406
|
+
? body.verification_uri
|
|
407
|
+
: "https://github.com/login/device";
|
|
408
|
+
return { deviceCode: body.device_code, userCode: body.user_code, verificationUri, expiresIn, interval };
|
|
409
|
+
}
|
|
410
|
+
async function pollDevice(device, options) {
|
|
411
|
+
const deadline = options.now() + device.expiresIn * 1000;
|
|
412
|
+
let interval = device.interval;
|
|
413
|
+
while (options.now() < deadline) {
|
|
414
|
+
const remaining = deadline - options.now();
|
|
415
|
+
await options.sleep(Math.min(interval * 1000, remaining));
|
|
416
|
+
if (options.now() >= deadline)
|
|
417
|
+
break;
|
|
418
|
+
const body = await postOAuth(ACCESS_TOKEN_URL, {
|
|
419
|
+
client_id: options.clientId,
|
|
420
|
+
device_code: device.deviceCode,
|
|
421
|
+
grant_type: DEVICE_GRANT,
|
|
422
|
+
}, options.fetchImpl, [device.deviceCode]);
|
|
423
|
+
if (typeof body.error !== "string")
|
|
424
|
+
return readGrant(body);
|
|
425
|
+
if (body.error === "authorization_pending")
|
|
426
|
+
continue;
|
|
427
|
+
if (body.error === "slow_down") {
|
|
428
|
+
const announced = typeof body.interval === "number" ? body.interval : interval + 5;
|
|
429
|
+
interval = announced > interval ? announced : interval + 5;
|
|
430
|
+
continue;
|
|
431
|
+
}
|
|
432
|
+
throw new AuthError(deviceFailure(body, device.deviceCode));
|
|
433
|
+
}
|
|
434
|
+
throw new AuthError("The code expired. Run `npx copilot-agents-mcp login` again.");
|
|
435
|
+
}
|
|
436
|
+
function deviceFailure(body, deviceCode) {
|
|
437
|
+
const code = typeof body.error === "string" ? body.error : "";
|
|
438
|
+
if (code === "access_denied")
|
|
439
|
+
return "You denied the authorization.";
|
|
440
|
+
if (code === "expired_token" || code === "token_expired") {
|
|
441
|
+
return "The code expired. Run `npx copilot-agents-mcp login` again.";
|
|
442
|
+
}
|
|
443
|
+
if (code === "device_flow_disabled")
|
|
444
|
+
return "The GitHub App does not have device flow enabled.";
|
|
445
|
+
return safeOAuthMessage("GitHub rejected the device flow", body, [deviceCode]);
|
|
446
|
+
}
|
|
447
|
+
async function requestRefresh(clientId, refreshToken, fetchImpl) {
|
|
448
|
+
const body = await postOAuth(ACCESS_TOKEN_URL, {
|
|
449
|
+
client_id: clientId,
|
|
450
|
+
grant_type: "refresh_token",
|
|
451
|
+
refresh_token: refreshToken,
|
|
452
|
+
}, fetchImpl, [refreshToken]);
|
|
453
|
+
if (body.error === "bad_refresh_token")
|
|
454
|
+
throw new BadRefreshToken();
|
|
455
|
+
if (typeof body.error === "string")
|
|
456
|
+
throw new AuthError(safeOAuthMessage("GitHub rejected the refresh", body, [refreshToken]));
|
|
457
|
+
return readGrant(body);
|
|
458
|
+
}
|
|
459
|
+
async function postOAuth(url, body, fetchImpl, secrets) {
|
|
460
|
+
let response;
|
|
461
|
+
try {
|
|
462
|
+
response = await fetchImpl(url, {
|
|
463
|
+
method: "POST",
|
|
464
|
+
headers: {
|
|
465
|
+
accept: "application/json",
|
|
466
|
+
"content-type": "application/json",
|
|
467
|
+
"user-agent": "copilot-agents-mcp",
|
|
468
|
+
},
|
|
469
|
+
body: JSON.stringify(body),
|
|
470
|
+
redirect: "error",
|
|
471
|
+
signal: AbortSignal.timeout(OAUTH_TIMEOUT_MS),
|
|
472
|
+
});
|
|
473
|
+
}
|
|
474
|
+
catch (error) {
|
|
475
|
+
if (isTimeout(error))
|
|
476
|
+
throw new AuthError(`GitHub did not respond in time (${OAUTH_TIMEOUT_MS / 1000} s).`);
|
|
477
|
+
const message = error instanceof Error ? error.message : "network error";
|
|
478
|
+
throw new AuthError(redactSecrets(`Could not call GitHub: ${message}`, secrets));
|
|
479
|
+
}
|
|
480
|
+
const text = await response.text();
|
|
481
|
+
let parsed = null;
|
|
482
|
+
if (text) {
|
|
483
|
+
try {
|
|
484
|
+
parsed = JSON.parse(text);
|
|
485
|
+
}
|
|
486
|
+
catch {
|
|
487
|
+
parsed = null;
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
491
|
+
throw new AuthError(`GitHub returned HTTP ${response.status} and a non-JSON body.`);
|
|
492
|
+
}
|
|
493
|
+
const record = parsed;
|
|
494
|
+
if (typeof record.error === "string" || response.ok)
|
|
495
|
+
return record;
|
|
496
|
+
throw new AuthError(`GitHub returned HTTP ${response.status}.`);
|
|
497
|
+
}
|
|
498
|
+
function readGrant(body) {
|
|
499
|
+
if (typeof body.access_token !== "string" || !body.access_token)
|
|
500
|
+
throw new AuthError("GitHub did not return an access token.");
|
|
501
|
+
if (typeof body.refresh_token !== "string" || !body.refresh_token) {
|
|
502
|
+
throw new AuthError("GitHub did not return a refresh token. The app must issue expiring user tokens.");
|
|
503
|
+
}
|
|
504
|
+
if (typeof body.expires_in !== "number" || !Number.isFinite(body.expires_in) || body.expires_in <= 0) {
|
|
505
|
+
throw new AuthError("GitHub did not return the access token expiry.");
|
|
506
|
+
}
|
|
507
|
+
const refreshExpiresIn = typeof body.refresh_token_expires_in === "number" && Number.isFinite(body.refresh_token_expires_in)
|
|
508
|
+
? body.refresh_token_expires_in
|
|
509
|
+
: null;
|
|
510
|
+
return {
|
|
511
|
+
accessToken: body.access_token,
|
|
512
|
+
refreshToken: body.refresh_token,
|
|
513
|
+
expiresIn: body.expires_in,
|
|
514
|
+
refreshExpiresIn,
|
|
515
|
+
};
|
|
516
|
+
}
|
|
517
|
+
function toStored(grant, now) {
|
|
518
|
+
return {
|
|
519
|
+
access_token: grant.accessToken,
|
|
520
|
+
refresh_token: grant.refreshToken,
|
|
521
|
+
expires_at: now + grant.expiresIn * 1000,
|
|
522
|
+
refresh_expires_at: grant.refreshExpiresIn === null ? null : now + grant.refreshExpiresIn * 1000,
|
|
523
|
+
};
|
|
524
|
+
}
|
|
525
|
+
function serialize(credential) {
|
|
526
|
+
return JSON.stringify({
|
|
527
|
+
access_token: credential.access_token,
|
|
528
|
+
refresh_token: credential.refresh_token,
|
|
529
|
+
expires_at: credential.expires_at,
|
|
530
|
+
refresh_expires_at: credential.refresh_expires_at,
|
|
531
|
+
});
|
|
532
|
+
}
|
|
533
|
+
function parseStored(raw) {
|
|
534
|
+
let parsed;
|
|
535
|
+
try {
|
|
536
|
+
parsed = JSON.parse(raw);
|
|
537
|
+
}
|
|
538
|
+
catch {
|
|
539
|
+
return null;
|
|
540
|
+
}
|
|
541
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
542
|
+
return null;
|
|
543
|
+
const record = parsed;
|
|
544
|
+
if (typeof record.access_token !== "string" || !record.access_token)
|
|
545
|
+
return null;
|
|
546
|
+
if (typeof record.refresh_token !== "string" || !record.refresh_token)
|
|
547
|
+
return null;
|
|
548
|
+
if (typeof record.expires_at !== "number" || !Number.isFinite(record.expires_at))
|
|
549
|
+
return null;
|
|
550
|
+
if (record.refresh_expires_at !== null && (typeof record.refresh_expires_at !== "number" || !Number.isFinite(record.refresh_expires_at))) {
|
|
551
|
+
return null;
|
|
552
|
+
}
|
|
553
|
+
return {
|
|
554
|
+
access_token: record.access_token,
|
|
555
|
+
refresh_token: record.refresh_token,
|
|
556
|
+
expires_at: record.expires_at,
|
|
557
|
+
refresh_expires_at: record.refresh_expires_at,
|
|
558
|
+
};
|
|
559
|
+
}
|
|
560
|
+
function expiring(credential, now) {
|
|
561
|
+
return credential.expires_at - now <= ACCESS_TOKEN_REFRESH_MARGIN_MS;
|
|
562
|
+
}
|
|
563
|
+
function reusable(credential, rejected, now) {
|
|
564
|
+
if (expiring(credential, now))
|
|
565
|
+
return false;
|
|
566
|
+
if (rejected !== undefined && credential.access_token === rejected)
|
|
567
|
+
return false;
|
|
568
|
+
return true;
|
|
569
|
+
}
|
|
570
|
+
function safeOAuthMessage(prefix, body, secrets) {
|
|
571
|
+
const code = typeof body.error === "string" ? body.error : "";
|
|
572
|
+
const description = typeof body.error_description === "string" ? body.error_description : "";
|
|
573
|
+
const detail = [code, description].filter(Boolean).join(": ");
|
|
574
|
+
return redactSecrets(detail ? `${prefix}: ${detail}` : prefix, secrets);
|
|
575
|
+
}
|
|
576
|
+
function isTimeout(error) {
|
|
577
|
+
return error instanceof Error && error.name === "TimeoutError";
|
|
578
|
+
}
|
|
579
|
+
function redactSecrets(text, secrets) {
|
|
580
|
+
let out = text;
|
|
581
|
+
for (const secret of secrets)
|
|
582
|
+
out = redact(out, secret);
|
|
583
|
+
return redactTokenShapes(out);
|
|
584
|
+
}
|