@topline-build/harness-mcp 0.9.2 → 0.9.3
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/CHANGELOG.md +16 -1
- package/README.md +7 -5
- package/dist/index.d.ts +4 -1
- package/dist/index.js +479 -30
- package/docs/generated/build-mcp-manifest.json +288 -5
- package/docs/generated/build-mcp-reference.md +275 -4
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
2
|
import { createHash, randomBytes } from "node:crypto";
|
|
3
|
-
import { existsSync } from "node:fs";
|
|
3
|
+
import { existsSync, readFileSync, rmSync } from "node:fs";
|
|
4
4
|
import { cp, mkdir, mkdtemp, readdir, readFile, realpath, lstat, writeFile, rm, rename } from "node:fs/promises";
|
|
5
5
|
import { createServer } from "node:http";
|
|
6
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
6
7
|
import os from "node:os";
|
|
7
8
|
import path from "node:path";
|
|
8
9
|
import { gzipSync } from "node:zlib";
|
|
@@ -17,7 +18,7 @@ const MCP_SURFACES = ["build", "topline", "harness"];
|
|
|
17
18
|
export const DEFAULT_MCP_PROTOCOL_VERSION = "2025-11-25";
|
|
18
19
|
const DEFAULT_TIMEOUT_MS = 120_000;
|
|
19
20
|
export const BUILD_MCP_SERVER_NAME = "topline-build-stdio";
|
|
20
|
-
export const HARNESS_MCP_VERSION = "0.9.
|
|
21
|
+
export const HARNESS_MCP_VERSION = "0.9.3";
|
|
21
22
|
export const DEFAULT_OAUTH_SCOPES = Object.freeze(["harness:artifact:read", "harness:artifact:write", "harness:artifact:deploy", "harness:artifact:delete"]);
|
|
22
23
|
/** The Topline server's scopes: Build and Workspace. Consent shows what the seat allows. */
|
|
23
24
|
export const TOPLINE_OAUTH_SCOPES = Object.freeze([
|
|
@@ -135,17 +136,34 @@ export async function signInAtStartup(opts, onSignedIn, log = (message) => proce
|
|
|
135
136
|
return false;
|
|
136
137
|
try {
|
|
137
138
|
const stored = await readStoredOAuthCredentials(opts);
|
|
138
|
-
if (stored?.
|
|
139
|
+
if (stored?.accessToken && Date.parse(stored.accessTokenExpiresAt ?? "") > Date.now())
|
|
139
140
|
return false;
|
|
141
|
+
if (stored?.refreshToken) {
|
|
142
|
+
// An expired access token: refresh it now, so a saved sign-in Topline
|
|
143
|
+
// has since refused opens the browser here instead of failing a tool call.
|
|
144
|
+
try {
|
|
145
|
+
if (await getBearerTokenWithoutSignIn(opts))
|
|
146
|
+
return false;
|
|
147
|
+
}
|
|
148
|
+
catch (err) {
|
|
149
|
+
if (!isSignInRejected(err))
|
|
150
|
+
return false;
|
|
151
|
+
log("Your saved Topline sign-in has expired.");
|
|
152
|
+
}
|
|
153
|
+
}
|
|
140
154
|
// Hosts often start one server per window or session; only one of them opens the browser.
|
|
141
|
-
if (!(await
|
|
155
|
+
if (!(await takeSignInLock(opts.authFile))) {
|
|
156
|
+
// Another window is signing in: list tools again here once it lands.
|
|
157
|
+
watchForSignIn(opts, onSignedIn, stored);
|
|
142
158
|
return false;
|
|
159
|
+
}
|
|
143
160
|
try {
|
|
144
161
|
log(`Opening your browser to sign in to Topline at ${platformBaseUrl(opts)}. Choose Allow to load the Topline tools.`);
|
|
145
162
|
await interactiveSignIn({
|
|
146
163
|
...opts,
|
|
147
164
|
quietOpenFailure: true,
|
|
148
165
|
openUrl: async (url) => {
|
|
166
|
+
await shareSignInUrl(opts.authFile, url);
|
|
149
167
|
// Printed every time: with no browser (SSH, a container) this is the only way to finish.
|
|
150
168
|
log(`If it does not open, visit this address:\n${url}`);
|
|
151
169
|
await (opts.openUrl ? opts.openUrl(url) : openBrowser({ ...opts, openUrl: undefined, quietOpenFailure: true }, url));
|
|
@@ -153,7 +171,7 @@ export async function signInAtStartup(opts, onSignedIn, log = (message) => proce
|
|
|
153
171
|
});
|
|
154
172
|
}
|
|
155
173
|
finally {
|
|
156
|
-
await
|
|
174
|
+
await releaseSignInLock(opts.authFile);
|
|
157
175
|
}
|
|
158
176
|
await onSignedIn().catch(() => undefined);
|
|
159
177
|
return true;
|
|
@@ -163,27 +181,178 @@ export async function signInAtStartup(opts, onSignedIn, log = (message) => proce
|
|
|
163
181
|
return false;
|
|
164
182
|
}
|
|
165
183
|
}
|
|
166
|
-
|
|
184
|
+
// How long a browser sign-in waits for Allow (the callback server's timeout).
|
|
185
|
+
const SIGN_IN_WINDOW_MS = 5 * 60 * 1000;
|
|
186
|
+
const SIGN_IN_WATCH_INTERVAL_MS = 500;
|
|
187
|
+
function signInLockFile(authFile) {
|
|
167
188
|
return `${path.resolve(authFile)}.signin-lock`;
|
|
168
189
|
}
|
|
169
|
-
/**
|
|
170
|
-
|
|
171
|
-
|
|
190
|
+
/**
|
|
191
|
+
* True when this process may run the browser sign-in for this auth file.
|
|
192
|
+
* Hosts start one server per window or session, and every one of them can be
|
|
193
|
+
* refused at once; the lock keeps that to one browser tab. A lock younger than
|
|
194
|
+
* the sign-in window means another process is running it.
|
|
195
|
+
*/
|
|
196
|
+
async function takeSignInLock(authFile) {
|
|
197
|
+
const lock = signInLockFile(authFile);
|
|
172
198
|
await mkdir(path.dirname(lock), { recursive: true });
|
|
173
199
|
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
174
200
|
try {
|
|
175
|
-
await writeFile(lock, `${process.pid}\n`, { flag: "wx", mode: 0o600 });
|
|
201
|
+
await writeFile(lock, `${JSON.stringify({ pid: process.pid })}\n`, { flag: "wx", mode: 0o600 });
|
|
202
|
+
heldSignInLocks.add(lock);
|
|
203
|
+
releaseSignInLocksOnExit();
|
|
176
204
|
return true;
|
|
177
205
|
}
|
|
178
206
|
catch {
|
|
207
|
+
const owner = await readSignInLock(lock);
|
|
208
|
+
// An owner that died (crash, closed window) cannot finish its sign-in; its lock is stale at once.
|
|
209
|
+
const ownerGone = owner?.pid !== undefined && owner.pid !== process.pid && !processAlive(owner.pid);
|
|
179
210
|
const age = Date.now() - ((await lstat(lock).catch(() => null))?.mtimeMs ?? 0);
|
|
180
|
-
if (age <
|
|
211
|
+
if (!ownerGone && age < SIGN_IN_WINDOW_MS + 60 * 1000)
|
|
181
212
|
return false;
|
|
182
213
|
await rm(lock, { force: true }).catch(() => undefined);
|
|
183
214
|
}
|
|
184
215
|
}
|
|
185
216
|
return false;
|
|
186
217
|
}
|
|
218
|
+
/** The lock's owner and shared address. 0.9.2 wrote a bare pid. */
|
|
219
|
+
async function readSignInLock(lock) {
|
|
220
|
+
let text;
|
|
221
|
+
try {
|
|
222
|
+
text = await readFile(lock, "utf8");
|
|
223
|
+
}
|
|
224
|
+
catch {
|
|
225
|
+
return null;
|
|
226
|
+
}
|
|
227
|
+
return parseSignInLock(text);
|
|
228
|
+
}
|
|
229
|
+
function parseSignInLock(text) {
|
|
230
|
+
try {
|
|
231
|
+
const parsed = JSON.parse(text);
|
|
232
|
+
if (isRecord(parsed)) {
|
|
233
|
+
return {
|
|
234
|
+
...(Number.isInteger(parsed.pid) && parsed.pid > 0 ? { pid: parsed.pid } : {}),
|
|
235
|
+
...(typeof parsed.signInUrl === "string" ? { signInUrl: parsed.signInUrl } : {})
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
if (Number.isInteger(parsed) && parsed > 0)
|
|
239
|
+
return { pid: parsed };
|
|
240
|
+
}
|
|
241
|
+
catch {
|
|
242
|
+
// Not JSON.
|
|
243
|
+
}
|
|
244
|
+
return {};
|
|
245
|
+
}
|
|
246
|
+
/** False only when the process is known to be gone; EPERM means it exists under another user. */
|
|
247
|
+
function processAlive(pid) {
|
|
248
|
+
try {
|
|
249
|
+
process.kill(pid, 0);
|
|
250
|
+
return true;
|
|
251
|
+
}
|
|
252
|
+
catch (err) {
|
|
253
|
+
return err.code !== "ESRCH";
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
// Locks this process took, removed on exit so a closed window does not block the others.
|
|
257
|
+
const heldSignInLocks = new Set();
|
|
258
|
+
let releasesOnExit = false;
|
|
259
|
+
function releaseSignInLocksOnExit() {
|
|
260
|
+
if (releasesOnExit)
|
|
261
|
+
return;
|
|
262
|
+
releasesOnExit = true;
|
|
263
|
+
process.once("exit", () => {
|
|
264
|
+
for (const lock of heldSignInLocks) {
|
|
265
|
+
try {
|
|
266
|
+
if (parseSignInLock(readFileSync(lock, "utf8")).pid === process.pid)
|
|
267
|
+
rmSync(lock, { force: true });
|
|
268
|
+
}
|
|
269
|
+
catch {
|
|
270
|
+
// Already gone.
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
async function ownsSignInLock(lock) {
|
|
276
|
+
return (await readSignInLock(lock))?.pid === process.pid;
|
|
277
|
+
}
|
|
278
|
+
async function releaseSignInLock(authFile) {
|
|
279
|
+
const lock = signInLockFile(authFile);
|
|
280
|
+
heldSignInLocks.delete(lock);
|
|
281
|
+
if (await ownsSignInLock(lock))
|
|
282
|
+
await rm(lock, { force: true }).catch(() => undefined);
|
|
283
|
+
}
|
|
284
|
+
/** Put the authorize address in the lock, so other processes can hand the person the same tab. */
|
|
285
|
+
async function shareSignInUrl(authFile, signInUrl) {
|
|
286
|
+
const lock = signInLockFile(authFile);
|
|
287
|
+
if (!(await ownsSignInLock(lock)))
|
|
288
|
+
return;
|
|
289
|
+
await writeFile(lock, `${JSON.stringify({ pid: process.pid, signInUrl })}\n`, { mode: 0o600 }).catch(() => undefined);
|
|
290
|
+
}
|
|
291
|
+
/** The address another process's sign-in is waiting on, only when its owner is alive and it is a plain authorize address for this account. */
|
|
292
|
+
async function sharedSignInUrl(opts) {
|
|
293
|
+
const owner = await readSignInLock(signInLockFile(opts.authFile));
|
|
294
|
+
if (!owner?.signInUrl || owner.pid === undefined || !processAlive(owner.pid))
|
|
295
|
+
return null;
|
|
296
|
+
return shareableSignInUrl(opts, owner.signInUrl);
|
|
297
|
+
}
|
|
298
|
+
// What an authorize address may carry. Anything else, a verifier above all, is never shown.
|
|
299
|
+
const SHAREABLE_SIGN_IN_PARAMS = new Set(["response_type", "client_id", "redirect_uri", "scope", "resource", "code_challenge", "code_challenge_method", "state"]);
|
|
300
|
+
function shareableSignInUrl(opts, raw) {
|
|
301
|
+
let url;
|
|
302
|
+
try {
|
|
303
|
+
url = new URL(raw);
|
|
304
|
+
}
|
|
305
|
+
catch {
|
|
306
|
+
return null;
|
|
307
|
+
}
|
|
308
|
+
if (url.username || url.password || url.hash || `${url.origin}${url.pathname}` !== `${platformBaseUrl(opts)}/oauth/authorize`)
|
|
309
|
+
return null;
|
|
310
|
+
const keys = [...url.searchParams.keys()];
|
|
311
|
+
if (new Set(keys).size !== keys.length || keys.some((key) => !SHAREABLE_SIGN_IN_PARAMS.has(key)))
|
|
312
|
+
return null;
|
|
313
|
+
const param = (key) => url.searchParams.get(key) ?? "";
|
|
314
|
+
if (param("response_type") !== "code" || param("code_challenge_method") !== "S256")
|
|
315
|
+
return null;
|
|
316
|
+
if (!param("client_id") || !param("code_challenge") || !param("state"))
|
|
317
|
+
return null;
|
|
318
|
+
if (!/^http:\/\/127\.0\.0\.1:\d{1,5}\/callback$/.test(param("redirect_uri")))
|
|
319
|
+
return null;
|
|
320
|
+
return url.toString();
|
|
321
|
+
}
|
|
322
|
+
// Auth files this process is already watching for another process's sign-in.
|
|
323
|
+
const signInWatches = new Set();
|
|
324
|
+
function credentialsTag(stored) {
|
|
325
|
+
return stored ? JSON.stringify([stored.accessToken ?? null, stored.refreshToken ?? null]) : null;
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* Another process runs the browser sign-in; poll the auth file (bounded by
|
|
329
|
+
* the sign-in window, never keeping the process alive) and list tools again
|
|
330
|
+
* once, when its new sign-in lands.
|
|
331
|
+
*/
|
|
332
|
+
function watchForSignIn(opts, onSignedIn, baseline) {
|
|
333
|
+
const key = path.resolve(opts.authFile);
|
|
334
|
+
if (signInWatches.has(key))
|
|
335
|
+
return;
|
|
336
|
+
signInWatches.add(key);
|
|
337
|
+
const tag = credentialsTag(baseline);
|
|
338
|
+
const deadline = Date.now() + SIGN_IN_WINDOW_MS;
|
|
339
|
+
let checking = false;
|
|
340
|
+
const stop = () => { clearInterval(timer); signInWatches.delete(key); };
|
|
341
|
+
const timer = setInterval(() => {
|
|
342
|
+
if (checking)
|
|
343
|
+
return;
|
|
344
|
+
if (Date.now() > deadline)
|
|
345
|
+
return stop();
|
|
346
|
+
checking = true;
|
|
347
|
+
void readStoredOAuthCredentials(opts).catch(() => null).then(async (current) => {
|
|
348
|
+
if (!current || credentialsTag(current) === tag)
|
|
349
|
+
return;
|
|
350
|
+
stop();
|
|
351
|
+
await onSignedIn().catch(() => undefined);
|
|
352
|
+
}).finally(() => { checking = false; });
|
|
353
|
+
}, SIGN_IN_WATCH_INTERVAL_MS);
|
|
354
|
+
timer.unref?.();
|
|
355
|
+
}
|
|
187
356
|
// One browser sign-in per auth file at a time: the startup sign-in and a tool
|
|
188
357
|
// call that needs a token share it instead of opening two approvals.
|
|
189
358
|
const inFlightSignIns = new Map();
|
|
@@ -205,6 +374,196 @@ async function interactiveSignIn(opts) {
|
|
|
205
374
|
inFlightSignIns.delete(key);
|
|
206
375
|
}
|
|
207
376
|
}
|
|
377
|
+
// The address of the browser sign-in open for each auth file, so a tool call
|
|
378
|
+
// that joins it can still hand the person the link.
|
|
379
|
+
const signInUrls = new Map();
|
|
380
|
+
// When each auth file last finished a browser sign-in. A refusal right after
|
|
381
|
+
// one means Topline refuses the new sign-in too, so another browser tab would
|
|
382
|
+
// not help.
|
|
383
|
+
const lastSignIns = new Map();
|
|
384
|
+
const SIGN_IN_COOLDOWN_MS = 5 * 60 * 1000;
|
|
385
|
+
const signInUsage = new AsyncLocalStorage();
|
|
386
|
+
/** The auth file holds a different sign-in than the one the refused call used. */
|
|
387
|
+
function signInRenewedSince(usage, current) {
|
|
388
|
+
if (!current)
|
|
389
|
+
return false;
|
|
390
|
+
if (usage.bearer)
|
|
391
|
+
return current.accessToken !== usage.bearer && (Boolean(current.accessToken) || current.refreshToken !== usage.before?.refreshToken);
|
|
392
|
+
return usage.before !== null && credentialsTag(current) !== credentialsTag(usage.before);
|
|
393
|
+
}
|
|
394
|
+
/**
|
|
395
|
+
* Topline refused this computer's saved sign-in (expired or revoked), so the
|
|
396
|
+
* person would otherwise have to clear it by hand. First rule out the cases
|
|
397
|
+
* where an Allow page would not help: another window (or a refresh) already
|
|
398
|
+
* renewed the sign-in, or one refresh of the saved sign-in works (a 401 for
|
|
399
|
+
* another reason, such as a gateway glitch); both return `sign_in_renewed`
|
|
400
|
+
* so the assistant calls again. Otherwise start the browser
|
|
401
|
+
* sign-in, without waiting for Allow, and return `sign_in_required` with the
|
|
402
|
+
* address so the assistant can ask the person to choose Allow and then call
|
|
403
|
+
* the tool again. The refused call is never replayed, and the saved sign-in is
|
|
404
|
+
* only replaced once the new one succeeds. A manual token, which only its
|
|
405
|
+
* owner can replace, keeps `authorization_required`.
|
|
406
|
+
*/
|
|
407
|
+
async function withSignInRecovery(opts, result, usage, onSignedIn) {
|
|
408
|
+
const error = isRecord(result.structuredContent) && isRecord(result.structuredContent.error) ? result.structuredContent.error : null;
|
|
409
|
+
if (error?.code !== "authorization_required" || opts.token || !servesBuild(opts))
|
|
410
|
+
return result;
|
|
411
|
+
let current = await readStoredOAuthCredentials(opts).catch(() => null);
|
|
412
|
+
if (signInRenewedSince(usage, current))
|
|
413
|
+
return signInErrorResult("sign_in_renewed", "The Topline sign-in was renewed (by another window or a refresh) while this call was on its way, so it was refused with the old one. Nothing was replayed.");
|
|
414
|
+
// Topline refused a token obtained moments ago: refreshing or signing in
|
|
415
|
+
// again would not help, and retrying would loop.
|
|
416
|
+
if (usage.bearer && current?.accessToken === usage.bearer && tokenIsFresh(current.obtainedAt))
|
|
417
|
+
return notASignInProblem(result);
|
|
418
|
+
const key = path.resolve(opts.authFile);
|
|
419
|
+
if (Date.now() - (lastSignIns.get(key) ?? 0) < SIGN_IN_COOLDOWN_MS)
|
|
420
|
+
return result;
|
|
421
|
+
if (current?.refreshToken && current.clientId) {
|
|
422
|
+
try {
|
|
423
|
+
await refreshStoredOAuthToken(opts, current);
|
|
424
|
+
// The saved sign-in still works once refreshed: no Allow page, just call again.
|
|
425
|
+
return signInErrorResult("sign_in_renewed", "Your Topline sign-in was renewed — try again.");
|
|
426
|
+
}
|
|
427
|
+
catch (err) {
|
|
428
|
+
// A temporary refresh failure says nothing about the sign-in; do not send the person to Allow.
|
|
429
|
+
if (!isSignInRejected(err))
|
|
430
|
+
return result;
|
|
431
|
+
}
|
|
432
|
+
current = await readStoredOAuthCredentials(opts).catch(() => null);
|
|
433
|
+
}
|
|
434
|
+
const started = await startBrowserSignIn(opts, onSignedIn, current);
|
|
435
|
+
// The sign-in could not even start (Topline unreachable): keep the original guidance.
|
|
436
|
+
if (started.kind === "failed")
|
|
437
|
+
return result;
|
|
438
|
+
if (started.kind === "renewed")
|
|
439
|
+
return signInErrorResult("sign_in_renewed", "Another Topline window finished a new sign-in just now. Nothing was replayed.");
|
|
440
|
+
return signInErrorResult("sign_in_required", started.kind === "elsewhere"
|
|
441
|
+
? "Topline no longer accepts this computer's saved sign-in (it expired or was revoked), and a sign-in is already waiting in your browser: another Topline window started it."
|
|
442
|
+
: "Topline no longer accepts this computer's saved sign-in (it expired or was revoked), so a new browser sign-in has started.", started.signInUrl, error.recovery);
|
|
443
|
+
}
|
|
444
|
+
const FRESH_TOKEN_MS = 2 * 60 * 1000;
|
|
445
|
+
/** Obtained within the last 2 minutes. A time in the future (clock stepped back, bad value) is not fresh. */
|
|
446
|
+
function tokenIsFresh(obtainedAt) {
|
|
447
|
+
const age = Date.now() - Date.parse(obtainedAt ?? "");
|
|
448
|
+
return Number.isFinite(age) && age >= 0 && age < FRESH_TOKEN_MS;
|
|
449
|
+
}
|
|
450
|
+
function notASignInProblem(result) {
|
|
451
|
+
const content = result.structuredContent;
|
|
452
|
+
const structuredContent = { ...content, error: { ...content.error, retryable: false, recoveryAction: "Topline refused this request even with a fresh sign-in, so it isn't a sign-in problem. Don't retry; report the error." } };
|
|
453
|
+
return { ...result, content: [{ type: "text", text: JSON.stringify(structuredContent, null, 2) }], structuredContent };
|
|
454
|
+
}
|
|
455
|
+
function signInErrorResult(code, message, signInUrl, recovery) {
|
|
456
|
+
const structuredContent = {
|
|
457
|
+
ok: false,
|
|
458
|
+
error: {
|
|
459
|
+
code,
|
|
460
|
+
message,
|
|
461
|
+
...BUILD_MCP_RECOVERY_ERRORS[code],
|
|
462
|
+
...(signInUrl ? { signInUrl } : {}),
|
|
463
|
+
...(recovery !== undefined ? { recovery } : {})
|
|
464
|
+
}
|
|
465
|
+
};
|
|
466
|
+
return {
|
|
467
|
+
content: [
|
|
468
|
+
{ type: "text", text: JSON.stringify(structuredContent, null, 2) },
|
|
469
|
+
...(signInUrl ? [{ type: "resource_link", uri: signInUrl, name: "Sign in to Topline" }] : [])
|
|
470
|
+
],
|
|
471
|
+
structuredContent,
|
|
472
|
+
isError: true
|
|
473
|
+
};
|
|
474
|
+
}
|
|
475
|
+
// Serializes the decision to start a sign-in within this process, so two
|
|
476
|
+
// refused calls at once join one sign-in instead of racing for the lock.
|
|
477
|
+
const signInStarts = new Map();
|
|
478
|
+
/**
|
|
479
|
+
* Start (or join) the browser sign-in for this auth file without waiting for
|
|
480
|
+
* Allow. Only the process holding the cross-process sign-in lock opens a tab;
|
|
481
|
+
* the others watch the auth file and list tools again once it changes. With
|
|
482
|
+
* `expected`, the sign-in the caller saw, a newer one found after taking the
|
|
483
|
+
* lock is used instead of opening a tab.
|
|
484
|
+
*/
|
|
485
|
+
async function startBrowserSignIn(opts, onSignedIn, expected) {
|
|
486
|
+
const key = path.resolve(opts.authFile);
|
|
487
|
+
const known = signInUrls.get(key);
|
|
488
|
+
if (known)
|
|
489
|
+
return { kind: "started", signInUrl: known };
|
|
490
|
+
while (signInStarts.has(key))
|
|
491
|
+
await signInStarts.get(key);
|
|
492
|
+
let decided;
|
|
493
|
+
signInStarts.set(key, new Promise((resolve) => { decided = resolve; }));
|
|
494
|
+
let opened = () => undefined;
|
|
495
|
+
const address = new Promise((resolve) => { opened = resolve; });
|
|
496
|
+
let failed = false;
|
|
497
|
+
try {
|
|
498
|
+
const runsOwnSignIn = !inFlightSignIns.has(key);
|
|
499
|
+
if (runsOwnSignIn) {
|
|
500
|
+
if (!(await takeSignInLock(opts.authFile).catch(() => false))) {
|
|
501
|
+
watchForSignIn(opts, onSignedIn, expected !== undefined ? expected : await readStoredOAuthCredentials(opts).catch(() => null));
|
|
502
|
+
return { kind: "elsewhere", signInUrl: await sharedSignInUrl(opts) };
|
|
503
|
+
}
|
|
504
|
+
if (expected !== undefined && credentialsTag(await readStoredOAuthCredentials(opts).catch(() => null)) !== credentialsTag(expected)) {
|
|
505
|
+
await releaseSignInLock(opts.authFile);
|
|
506
|
+
return { kind: "renewed" };
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
const pending = interactiveSignIn({
|
|
510
|
+
...opts,
|
|
511
|
+
quietOpenFailure: true,
|
|
512
|
+
openUrl: async (url) => {
|
|
513
|
+
await shareSignInUrl(opts.authFile, url);
|
|
514
|
+
opened(url);
|
|
515
|
+
await (opts.openUrl ? opts.openUrl(url) : openBrowser({ ...opts, openUrl: undefined, quietOpenFailure: true }, url));
|
|
516
|
+
}
|
|
517
|
+
});
|
|
518
|
+
pending.then(() => { lastSignIns.set(key, Date.now()); return onSignedIn(); }, () => { failed = true; })
|
|
519
|
+
.catch(() => undefined)
|
|
520
|
+
.finally(() => {
|
|
521
|
+
opened(null);
|
|
522
|
+
// This process took the lock for its sign-in; a joined sign-in's owner releases its own.
|
|
523
|
+
if (runsOwnSignIn)
|
|
524
|
+
void releaseSignInLock(opts.authFile);
|
|
525
|
+
});
|
|
526
|
+
}
|
|
527
|
+
finally {
|
|
528
|
+
signInStarts.delete(key);
|
|
529
|
+
decided();
|
|
530
|
+
}
|
|
531
|
+
const timer = setTimeout(() => opened(null), opts.timeoutMs);
|
|
532
|
+
timer.unref?.();
|
|
533
|
+
// Joining a sign-in that has not published its address yet never calls
|
|
534
|
+
// this openUrl, so watch for the address it publishes instead.
|
|
535
|
+
const poll = setInterval(() => { const url = signInUrls.get(key); if (url)
|
|
536
|
+
opened(url); }, 100);
|
|
537
|
+
poll.unref?.();
|
|
538
|
+
const signInUrl = (await address) ?? signInUrls.get(key) ?? null;
|
|
539
|
+
clearTimeout(timer);
|
|
540
|
+
clearInterval(poll);
|
|
541
|
+
if (!signInUrl && failed)
|
|
542
|
+
return { kind: "failed" };
|
|
543
|
+
return { kind: "started", signInUrl };
|
|
544
|
+
}
|
|
545
|
+
/** `platform_sign_in`: a fresh browser sign-in the person or assistant asks for, signed in or not. */
|
|
546
|
+
async function signInTool(opts, onSignedIn) {
|
|
547
|
+
if (opts.token)
|
|
548
|
+
return structuredToolError("manual_token_sign_in_unavailable");
|
|
549
|
+
if (!servesBuild(opts))
|
|
550
|
+
return structuredToolError("sign_in_unavailable_on_harness_surface");
|
|
551
|
+
const started = await startBrowserSignIn(opts, onSignedIn);
|
|
552
|
+
if (started.kind === "failed" || started.kind === "renewed")
|
|
553
|
+
return structuredToolError("sign_in_unavailable: Topline did not answer the sign-in request. Try again shortly.");
|
|
554
|
+
const signInUrl = started.signInUrl;
|
|
555
|
+
const result = toolResult({
|
|
556
|
+
ok: true,
|
|
557
|
+
status: "sign_in_started",
|
|
558
|
+
message: started.kind === "elsewhere"
|
|
559
|
+
? "A Topline sign-in another Topline window started is already waiting in the person's browser. Ask them to sign in there and choose Allow; the Topline tools reload after that. The saved sign-in is only replaced once they allow it."
|
|
560
|
+
: "A Topline sign-in page opened in the person's browser. Ask them to sign in and choose Allow; the Topline tools reload after that. The saved sign-in is only replaced once they allow it.",
|
|
561
|
+
...(signInUrl ? { signInUrl } : {})
|
|
562
|
+
});
|
|
563
|
+
if (signInUrl)
|
|
564
|
+
result.content.push({ type: "resource_link", uri: signInUrl, name: "Sign in to Topline" });
|
|
565
|
+
return result;
|
|
566
|
+
}
|
|
208
567
|
/**
|
|
209
568
|
* `topline-mcp login`: sign in once during setup so the assistant's next chat
|
|
210
569
|
* starts already connected. Opens the browser, saves the refresh token to the
|
|
@@ -282,6 +641,8 @@ export function createHarnessMcpStdioServer(opts, toolAllowlist) {
|
|
|
282
641
|
let hostedSessionSchemas = new Map();
|
|
283
642
|
// Only the newest listing writes shared state, so a slow older one cannot overwrite it.
|
|
284
643
|
let listingGeneration = 0;
|
|
644
|
+
// The tool list only changes when signing in (from signed out, which is
|
|
645
|
+
// null) or when the scopes change, so a token refresh is not a new grant.
|
|
285
646
|
const grantTag = (stored) => stored?.accessToken && Date.parse(stored.accessTokenExpiresAt ?? "") > Date.now()
|
|
286
647
|
? JSON.stringify([stored.clientId, stored.resource, [...stored.scopes].sort()]) : null;
|
|
287
648
|
// Identifies one sign-in regardless of access-token expiry: each browser
|
|
@@ -395,6 +756,8 @@ export function createHarnessMcpStdioServer(opts, toolAllowlist) {
|
|
|
395
756
|
}
|
|
396
757
|
const reportsProgress = req.params.name === "platform_deploy_artifact_app" || req.params.name === "platform_wait_artifact_deploy";
|
|
397
758
|
let refusedHidden = false;
|
|
759
|
+
// The sign-in this call starts from, and the bearer it sends.
|
|
760
|
+
const usage = { before: servesBuild(opts) && !opts.token ? await readStoredOAuthCredentials(opts).catch(() => null) : null };
|
|
398
761
|
try {
|
|
399
762
|
// A changed sign-in (for example a reconnect with new scopes) may offer
|
|
400
763
|
// the tool again; Topline still checks, so the call goes through.
|
|
@@ -406,20 +769,21 @@ export function createHarnessMcpStdioServer(opts, toolAllowlist) {
|
|
|
406
769
|
if (!forwardsHostedTool(req.params.name))
|
|
407
770
|
throw new McpError(ErrorCode.InvalidParams, `Unknown tool: ${req.params.name}`);
|
|
408
771
|
// Workspace and other hosted tools: Topline checks scopes and seat.
|
|
409
|
-
return await forwardHostedTool(opts, req.params.name, req.params.arguments ?? {});
|
|
772
|
+
return await signInUsage.run(usage, () => forwardHostedTool(opts, req.params.name, req.params.arguments ?? {}));
|
|
410
773
|
}
|
|
411
|
-
const result = await callHarnessTool(opts, req.params.name, req.params.arguments ?? {}, {
|
|
774
|
+
const result = await signInUsage.run(usage, () => callHarnessTool(opts, req.params.name, req.params.arguments ?? {}, {
|
|
412
775
|
...(reportsProgress ? { onProgress: (progress, message) => sendProgress(extra, progress, 1, message) } : {}),
|
|
413
|
-
inputSchema: hostedSessionSchemas.get(req.params.name)
|
|
414
|
-
|
|
415
|
-
|
|
776
|
+
inputSchema: hostedSessionSchemas.get(req.params.name),
|
|
777
|
+
onSignedIn: () => mcp.sendToolListChanged()
|
|
778
|
+
}));
|
|
779
|
+
return await withSignInRecovery(opts, result, usage, () => mcp.sendToolListChanged());
|
|
416
780
|
}
|
|
417
781
|
catch (err) {
|
|
418
782
|
if (err instanceof McpError)
|
|
419
783
|
throw err;
|
|
420
784
|
if (reportsProgress)
|
|
421
785
|
await sendProgress(extra, 1, 1, "Failed artifact deployment");
|
|
422
|
-
return structuredToolError(redactSecrets(err instanceof Error ? err.message : String(err), opts));
|
|
786
|
+
return await withSignInRecovery(opts, structuredToolError(redactSecrets(err instanceof Error ? err.message : String(err), opts)), usage, () => mcp.sendToolListChanged());
|
|
423
787
|
}
|
|
424
788
|
finally {
|
|
425
789
|
let listChanged = false;
|
|
@@ -455,6 +819,9 @@ export async function callHarnessTool(opts, name, args, hooks) {
|
|
|
455
819
|
return toolError(`Invalid arguments for ${name}: ${inputError}`);
|
|
456
820
|
let result;
|
|
457
821
|
switch (name) {
|
|
822
|
+
case "platform_sign_in":
|
|
823
|
+
result = await signInTool(opts, hooks?.onSignedIn ?? (async () => undefined));
|
|
824
|
+
break;
|
|
458
825
|
case "platform_connection_check":
|
|
459
826
|
case "platform_get_design_system_state":
|
|
460
827
|
case "platform_edit_design_system":
|
|
@@ -463,11 +830,21 @@ export async function callHarnessTool(opts, name, args, hooks) {
|
|
|
463
830
|
case "platform_list_artifact_drafts":
|
|
464
831
|
case "platform_deploy_operation":
|
|
465
832
|
case "platform_validate_artifact":
|
|
466
|
-
case "platform_run_artifact_smoke":
|
|
467
833
|
case "platform_plan_artifact_draft_delete":
|
|
468
834
|
case "platform_delete_artifact_draft":
|
|
469
835
|
result = toolResult(await callHostedBuildTool(opts, name, input));
|
|
470
836
|
break;
|
|
837
|
+
case "platform_run_artifact_smoke":
|
|
838
|
+
// A dev sandbox smoke returns its screenshot as image content, so pass the whole hosted result through.
|
|
839
|
+
if (input.target === "sandbox") {
|
|
840
|
+
if (!servesBuild(opts))
|
|
841
|
+
throw new Error(`${name}_requires_build_surface`);
|
|
842
|
+
result = await forwardHostedTool(opts, name, input);
|
|
843
|
+
}
|
|
844
|
+
else {
|
|
845
|
+
result = toolResult(await callHostedBuildTool(opts, name, input));
|
|
846
|
+
}
|
|
847
|
+
break;
|
|
471
848
|
case "platform_checkout_design_system":
|
|
472
849
|
result = toolResult(await checkoutDesignSystem(opts, input));
|
|
473
850
|
break;
|
|
@@ -490,7 +867,8 @@ export async function callHarnessTool(opts, name, args, hooks) {
|
|
|
490
867
|
result = toolResult(await getArtifactStatus(opts, stringArg(input, "artifactId"), numberArg(input, "limit")));
|
|
491
868
|
break;
|
|
492
869
|
case "platform_read_artifact_logs":
|
|
493
|
-
|
|
870
|
+
// Dev sandbox logs are only served by the hosted tool, not the REST logs route.
|
|
871
|
+
result = toolResult(input.target === "sandbox" ? await callHostedBuildTool(opts, name, input) : await readArtifactLogs(opts, input));
|
|
494
872
|
break;
|
|
495
873
|
case "platform_open_artifact":
|
|
496
874
|
result = toolResult(await openArtifact(opts, stringArg(input, "artifactId")));
|
|
@@ -1472,6 +1850,19 @@ const BUILD_MCP_TOOLS = [
|
|
|
1472
1850
|
required: ["ok", "verified", "product", "verifiedAt"]
|
|
1473
1851
|
}
|
|
1474
1852
|
},
|
|
1853
|
+
{
|
|
1854
|
+
name: "platform_sign_in",
|
|
1855
|
+
description: "Start a fresh Topline browser sign-in. Use it when the person asks to sign in to Topline again, or Topline keeps refusing this computer's sign-in. Returns at once: tell the person a sign-in page opened and ask them to sign in and choose Allow; if no page opened, give them signInUrl. The saved sign-in is replaced only after Allow, and the Topline tools reload then. Not available with a manual token.",
|
|
1856
|
+
annotations: mcpToolAnnotations("platform_sign_in", { readOnly: false, idempotent: true, openWorld: true }),
|
|
1857
|
+
inputSchema: { type: "object", properties: {}, additionalProperties: false },
|
|
1858
|
+
outputSchema: {
|
|
1859
|
+
type: "object",
|
|
1860
|
+
properties: {
|
|
1861
|
+
ok: { type: "boolean" }, status: { type: "string", enum: ["sign_in_started"] }, message: { type: "string" }, signInUrl: { type: "string" }
|
|
1862
|
+
},
|
|
1863
|
+
required: ["ok", "status", "message"]
|
|
1864
|
+
}
|
|
1865
|
+
},
|
|
1475
1866
|
{
|
|
1476
1867
|
name: "platform_init_artifact_app",
|
|
1477
1868
|
description: "Create a minimal, validated artifact app starter inside the configured local workspace.",
|
|
@@ -1609,7 +2000,7 @@ const BUILD_MCP_TOOLS = [
|
|
|
1609
2000
|
},
|
|
1610
2001
|
{
|
|
1611
2002
|
name: "platform_read_artifact_logs",
|
|
1612
|
-
description: "Read bounded, redacted deployment logs for a hosted artifact app.",
|
|
2003
|
+
description: "Read bounded, redacted deployment logs for a hosted artifact app. Pass target \"sandbox\" with sessionId and sandboxId to read your own running dev sandbox's logs instead.",
|
|
1613
2004
|
annotations: mcpToolAnnotations("platform_read_artifact_logs", { readOnly: true, openWorld: true }),
|
|
1614
2005
|
inputSchema: {
|
|
1615
2006
|
type: "object",
|
|
@@ -1617,6 +2008,9 @@ const BUILD_MCP_TOOLS = [
|
|
|
1617
2008
|
artifactId: { type: "string", format: "uuid" },
|
|
1618
2009
|
deploymentRecordId: { type: "string", format: "uuid" },
|
|
1619
2010
|
environment: { type: "string", enum: ["draft", "live"] },
|
|
2011
|
+
target: { type: "string", enum: ["draft", "live", "sandbox"] },
|
|
2012
|
+
sessionId: { type: "string", format: "uuid" },
|
|
2013
|
+
sandboxId: { type: "string", format: "uuid" },
|
|
1620
2014
|
limit: { type: "integer", minimum: 1, maximum: 200 },
|
|
1621
2015
|
severity: { type: "string" },
|
|
1622
2016
|
contains: { type: "string" },
|
|
@@ -1764,9 +2158,9 @@ const BUILD_MCP_TOOLS = [
|
|
|
1764
2158
|
},
|
|
1765
2159
|
{
|
|
1766
2160
|
name: "platform_run_artifact_smoke",
|
|
1767
|
-
description: "Rerun the trusted draft smoke check and return fresh rendered-page evidence. While you hold an open build session on the app, pass its sessionId.",
|
|
2161
|
+
description: "Rerun the trusted draft smoke check and return fresh rendered-page evidence. While you hold an open build session on the app, pass its sessionId. Pass target \"sandbox\" with sessionId and sandboxId to smoke your own running dev sandbox instead (advisory only).",
|
|
1768
2162
|
annotations: mcpToolAnnotations("platform_run_artifact_smoke", { readOnly: false, openWorld: true }),
|
|
1769
|
-
inputSchema: { type: "object", properties: { artifactId: { type: "string", format: "uuid" }, deploymentRecordId: { type: "string", format: "uuid" }, sessionId: { type: "string", format: "uuid" } }, required: ["artifactId"], additionalProperties: false },
|
|
2163
|
+
inputSchema: { type: "object", properties: { artifactId: { type: "string", format: "uuid" }, deploymentRecordId: { type: "string", format: "uuid" }, sessionId: { type: "string", format: "uuid" }, target: { type: "string", enum: ["draft", "sandbox"] }, sandboxId: { type: "string", format: "uuid" } }, required: ["artifactId"], additionalProperties: false },
|
|
1770
2164
|
outputSchema: { type: "object", properties: { ok: { type: "boolean" }, phase: { type: "string" }, artifactId: { type: "string" }, deploymentRecordId: { type: "string" }, smoke: { type: "object" }, validation: { type: "object" } }, required: ["ok", "phase", "artifactId", "deploymentRecordId", "smoke", "validation"] }
|
|
1771
2165
|
},
|
|
1772
2166
|
{
|
|
@@ -1879,6 +2273,7 @@ function withRecoveryOutputSchema(value) {
|
|
|
1879
2273
|
message: { type: "string" },
|
|
1880
2274
|
retryable: { type: "boolean" },
|
|
1881
2275
|
recoveryAction: { type: "string" },
|
|
2276
|
+
signInUrl: { type: "string" },
|
|
1882
2277
|
...(DOMAIN_FORWARD_TOOLS.has(tool.name) ? { recovery: { type: "object", additionalProperties: true } } : {})
|
|
1883
2278
|
},
|
|
1884
2279
|
required: ["code", "message", "retryable", "recoveryAction"],
|
|
@@ -1922,7 +2317,12 @@ const BUILD_MCP_RECOVERY_ERROR_VALUES = {
|
|
|
1922
2317
|
recoveryAction: "Read current domain/address state and the original receipt with the saved pre-call key. Retain the exact original input. Review changed state, scopes or configuration before any new plan/key; never assume a rejected delivery means no effect." }])),
|
|
1923
2318
|
domain_result_unknown: { retryable: false, recoveryAction: "The response did not establish an outcome. Recover the original receipt through platform_get_artifact_address (saved artifactId and apply key) or platform_read_artifact_domains (request/verify kind and key). Preserve the original plan/domain/input/key; an absent, pending or expired receipt does not authorize a fresh key. No mutation is replayed automatically." },
|
|
1924
2319
|
build_session_tool_unavailable: { retryable: false, recoveryAction: "The connection's hosted Build tool list does not offer this build session tool, so the package does not list or run it. Call platform_capability_status to see what is missing, such as a scope or capability, and reconnect through browser sign-in with any missing scope. The package asks the host to list tools again, so the tool comes back once Topline offers it." },
|
|
1925
|
-
authorization_required: { retryable: false, recoveryAction: "
|
|
2320
|
+
authorization_required: { retryable: false, recoveryAction: "Call platform_sign_in to start a fresh browser sign-in, and ask the person to choose Allow. If using a manual bearer token, replace the expired or revoked token instead. Recover existing artifact/deployment progress before retrying a write." },
|
|
2321
|
+
manual_token_sign_in_unavailable: { retryable: false, recoveryAction: "This connection uses a manual bearer token, which only its owner can replace. Ask the person to replace the token in their MCP configuration." },
|
|
2322
|
+
sign_in_unavailable_on_harness_surface: { retryable: false, recoveryAction: "The harness surface signs in with a token, not a browser. Ask the person to check this connection's token." },
|
|
2323
|
+
sign_in_required: { retryable: false, recoveryAction: "Tell the person a Topline sign-in page is open in their browser, and ask them to sign in and choose Allow. If no page opened, give them signInUrl to open when it is present. Do not retry on your own: wait for the person to choose Allow, then call again. Recover existing artifact/deployment progress before retrying a write." },
|
|
2324
|
+
sign_in_renewed: { retryable: true, recoveryAction: "The sign-in is already renewed, so call this tool again; the refused call was not replayed. Recover existing artifact/deployment progress before retrying a write." },
|
|
2325
|
+
sign_in_unavailable: { retryable: true, recoveryAction: "Topline did not answer the sign-in request. Wait briefly, then call platform_sign_in again." },
|
|
1926
2326
|
platform_harness_timeout: { retryable: true, recoveryAction: "Retry the call. For a deployment, use platform_list_artifact_drafts to recover the artifact and platform_wait_artifact_deploy to resume progress." },
|
|
1927
2327
|
platform_mcp_tool_error: { retryable: false, recoveryAction: "Topline refused the call without a code. Read the message, correct the request, then retry. Reconnect only when the message names a missing scope." },
|
|
1928
2328
|
build_session_id_required: { retryable: false, recoveryAction: "The fields named after the code only work inside a build session. Remove them for a plain deploy of an app you created over MCP, or start a session and pass its sessionId." },
|
|
@@ -2028,12 +2428,16 @@ export async function getBearerToken(opts) {
|
|
|
2028
2428
|
[...opts.oauthScopes].sort().join(" ")
|
|
2029
2429
|
].join("\0");
|
|
2030
2430
|
const existing = inFlightBearerTokenRequests.get(key);
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
2034
|
-
inFlightBearerTokenRequests.set(key, pending);
|
|
2431
|
+
const pending = existing ?? getOAuthBearerToken(opts);
|
|
2432
|
+
if (!existing)
|
|
2433
|
+
inFlightBearerTokenRequests.set(key, pending);
|
|
2035
2434
|
try {
|
|
2036
|
-
|
|
2435
|
+
const bearer = await pending;
|
|
2436
|
+
// Remembered for this tool call, so a refusal can tell whether the sign-in changed since.
|
|
2437
|
+
const usage = signInUsage.getStore();
|
|
2438
|
+
if (usage)
|
|
2439
|
+
usage.bearer = bearer;
|
|
2440
|
+
return bearer;
|
|
2037
2441
|
}
|
|
2038
2442
|
finally {
|
|
2039
2443
|
if (inFlightBearerTokenRequests.get(key) === pending)
|
|
@@ -2063,7 +2467,21 @@ async function refreshStoredOAuthToken(opts, stored) {
|
|
|
2063
2467
|
if (existing)
|
|
2064
2468
|
return existing;
|
|
2065
2469
|
const pending = (async () => {
|
|
2066
|
-
|
|
2470
|
+
let refreshed;
|
|
2471
|
+
try {
|
|
2472
|
+
refreshed = await refreshOAuthToken(opts, stored);
|
|
2473
|
+
}
|
|
2474
|
+
catch (err) {
|
|
2475
|
+
// Another server process may have rotated this refresh token a moment
|
|
2476
|
+
// ago; its new sign-in is then in the auth file, not refused.
|
|
2477
|
+
if (!isRefreshTokenRejected(err))
|
|
2478
|
+
throw err;
|
|
2479
|
+
const current = await readStoredOAuthCredentials(opts).catch(() => null);
|
|
2480
|
+
if (current?.refreshToken && current.refreshToken !== stored.refreshToken && current.accessToken
|
|
2481
|
+
&& Date.parse(current.accessTokenExpiresAt ?? "") - Date.now() > 60_000)
|
|
2482
|
+
return current;
|
|
2483
|
+
throw err;
|
|
2484
|
+
}
|
|
2067
2485
|
await writeStoredOAuthCredentials(opts, refreshed);
|
|
2068
2486
|
return refreshed;
|
|
2069
2487
|
})();
|
|
@@ -2152,6 +2570,7 @@ async function runOAuthLogin(opts) {
|
|
|
2152
2570
|
const codePromise = callback.waitForCode(state);
|
|
2153
2571
|
// A denial can land while the browser is still opening; it is reported below.
|
|
2154
2572
|
codePromise.catch(() => undefined);
|
|
2573
|
+
signInUrls.set(path.resolve(opts.authFile), authUrl.toString());
|
|
2155
2574
|
await openBrowser(opts, authUrl.toString());
|
|
2156
2575
|
const code = await codePromise;
|
|
2157
2576
|
const token = await oauthFetchJson(opts, `${issuer}/oauth/token`, {
|
|
@@ -2169,6 +2588,7 @@ async function runOAuthLogin(opts) {
|
|
|
2169
2588
|
return credentialsFromTokenResponse(issuer, resource, clientId, opts.oauthScopes, token);
|
|
2170
2589
|
}
|
|
2171
2590
|
finally {
|
|
2591
|
+
signInUrls.delete(path.resolve(opts.authFile));
|
|
2172
2592
|
await callback.close();
|
|
2173
2593
|
}
|
|
2174
2594
|
}
|
|
@@ -2211,6 +2631,7 @@ function credentialsFromTokenResponse(issuer, resource, clientId, requestedScope
|
|
|
2211
2631
|
accessToken,
|
|
2212
2632
|
accessTokenExpiresAt: new Date(Date.now() + Math.max(60, Math.floor(expiresIn)) * 1000).toISOString(),
|
|
2213
2633
|
refreshToken,
|
|
2634
|
+
obtainedAt: new Date().toISOString(),
|
|
2214
2635
|
scopes: scopeText.split(/[\s,]+/).filter(Boolean)
|
|
2215
2636
|
};
|
|
2216
2637
|
}
|
|
@@ -2239,6 +2660,7 @@ async function readStoredOAuthCredentials(opts) {
|
|
|
2239
2660
|
accessToken: typeof parsed.accessToken === "string" ? parsed.accessToken : undefined,
|
|
2240
2661
|
accessTokenExpiresAt: typeof parsed.accessTokenExpiresAt === "string" ? parsed.accessTokenExpiresAt : undefined,
|
|
2241
2662
|
refreshToken: typeof parsed.refreshToken === "string" ? parsed.refreshToken : undefined,
|
|
2663
|
+
...(typeof parsed.obtainedAt === "string" ? { obtainedAt: parsed.obtainedAt } : {}),
|
|
2242
2664
|
scopes
|
|
2243
2665
|
};
|
|
2244
2666
|
}
|
|
@@ -2246,9 +2668,36 @@ async function readStoredOAuthCredentials(opts) {
|
|
|
2246
2668
|
return null;
|
|
2247
2669
|
}
|
|
2248
2670
|
}
|
|
2671
|
+
/**
|
|
2672
|
+
* Replace the auth file in one step (a temporary file in the same directory,
|
|
2673
|
+
* then a rename), so another process never reads a half-written sign-in.
|
|
2674
|
+
*/
|
|
2249
2675
|
async function writeStoredOAuthCredentials(opts, credentials) {
|
|
2250
2676
|
await mkdir(path.dirname(opts.authFile), { recursive: true });
|
|
2251
|
-
|
|
2677
|
+
const temp = `${opts.authFile}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
|
|
2678
|
+
try {
|
|
2679
|
+
await writeFile(temp, `${JSON.stringify(credentials, null, 2)}\n`, { mode: 0o600, flag: "wx" });
|
|
2680
|
+
// Windows refuses the rename for a moment while another process reads the
|
|
2681
|
+
// file: retry for about 1.5 s, then write in place so a finished Allow is never lost.
|
|
2682
|
+
for (const delay of [25, 50, 100, 200, 400, 700, -1]) {
|
|
2683
|
+
try {
|
|
2684
|
+
await rename(temp, opts.authFile);
|
|
2685
|
+
return;
|
|
2686
|
+
}
|
|
2687
|
+
catch (err) {
|
|
2688
|
+
const code = err.code;
|
|
2689
|
+
if (code !== "EPERM" && code !== "EACCES" && code !== "EBUSY")
|
|
2690
|
+
throw err;
|
|
2691
|
+
if (delay < 0)
|
|
2692
|
+
break;
|
|
2693
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
2694
|
+
}
|
|
2695
|
+
}
|
|
2696
|
+
await writeFile(opts.authFile, `${JSON.stringify(credentials, null, 2)}\n`, { mode: 0o600 });
|
|
2697
|
+
}
|
|
2698
|
+
finally {
|
|
2699
|
+
await rm(temp, { force: true }).catch(() => undefined);
|
|
2700
|
+
}
|
|
2252
2701
|
}
|
|
2253
2702
|
async function startOAuthCallbackServer() {
|
|
2254
2703
|
let resolveCode = null;
|