diff --git a/README.md b/README.md index 3e8f8bc..3313c79 100644 --- a/README.md +++ b/README.md @@ -121,8 +121,11 @@ The launcher (`plugins/glean/start.mjs`) also derives and **exports** three more variables the bundle reads, so these are internal — start.mjs overwrites them on every launch and setting them yourself has no effect: -- `PLUGIN_DATA_DIR` — directory for credentials, caches, the saved server URL, - and `glean-server.log`. Defaults to `~/.glean`, or the host's +- `PLUGIN_DATA_DIR` — host-managed directory used for skills/cache compatibility. + Auth credentials, server configuration, remote-tool cache, and logs use the + stable canonical `~/.glean` directory so terminal and plugin launches share + state. Legacy files in host-managed plugin directories are migrated once into + `~/.glean`. The launcher still defaults this variable to `~/.glean`, or the host's `CLAUDE_PLUGIN_DATA` dir when provided. - `SKILLS_BASE_DIR` — where discovered skill files are written; defaults to `/glean-skills-cache`, or redirected under the launch @@ -134,8 +137,8 @@ every launch and setting them yourself has no effect: - **Sign-in loop or stale auth** — prompt the agent to reset and sign in again (e.g. "reset the Glean setup"). It calls the `setup` tool with `reset=true` to - clear the saved configuration and credentials, then runs `setup` again to - re-authenticate. + clear the saved configuration, grant, and registered OAuth client. The next + setup registers a new client and signs in again. - **Tools return `[SETUP_REQUIRED]`** — the plugin isn't configured or authenticated yet. Prompt the agent to set up Glean (e.g. "set up Glean"). The `setup` tool, called with no arguments, advances through the next missing diff --git a/plugins/glean/dist/index.js b/plugins/glean/dist/index.js index 6aafd8a..5c048ea 100644 --- a/plugins/glean/dist/index.js +++ b/plugins/glean/dist/index.js @@ -3236,8 +3236,8 @@ var require_utils = __commonJS({ } return ind; } - function removeDotSegments(path8) { - let input = path8; + function removeDotSegments(path9) { + let input = path9; const output = []; let nextSlash = -1; let len = 0; @@ -3489,8 +3489,8 @@ var require_schemes = __commonJS({ wsComponent.secure = void 0; } if (wsComponent.resourceName) { - const [path8, query] = wsComponent.resourceName.split("?"); - wsComponent.path = path8 && path8 !== "/" ? path8 : void 0; + const [path9, query] = wsComponent.resourceName.split("?"); + wsComponent.path = path9 && path9 !== "/" ? path9 : void 0; wsComponent.query = query; wsComponent.resourceName = void 0; } @@ -6883,12 +6883,12 @@ var require_dist = __commonJS({ throw new Error(`Unknown format "${name}"`); return f; }; - function addFormats(ajv, list, fs8, exportName) { + function addFormats(ajv, list, fs9, exportName) { var _a3; var _b; (_a3 = (_b = ajv.opts.code).formats) !== null && _a3 !== void 0 ? _a3 : _b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`; for (const f of list) - ajv.addFormat(f, fs8[f]); + ajv.addFormat(f, fs9[f]); } module.exports = exports = formatsPlugin; Object.defineProperty(exports, "__esModule", { value: true }); @@ -6973,17 +6973,17 @@ var require_visit = __commonJS({ visit.BREAK = BREAK; visit.SKIP = SKIP; visit.REMOVE = REMOVE; - function visit_(key, node, visitor, path8) { - const ctrl = callVisitor(key, node, visitor, path8); + function visit_(key, node, visitor, path9) { + const ctrl = callVisitor(key, node, visitor, path9); if (identity.isNode(ctrl) || identity.isPair(ctrl)) { - replaceNode(key, path8, ctrl); - return visit_(key, ctrl, visitor, path8); + replaceNode(key, path9, ctrl); + return visit_(key, ctrl, visitor, path9); } if (typeof ctrl !== "symbol") { if (identity.isCollection(node)) { - path8 = Object.freeze(path8.concat(node)); + path9 = Object.freeze(path9.concat(node)); for (let i = 0; i < node.items.length; ++i) { - const ci = visit_(i, node.items[i], visitor, path8); + const ci = visit_(i, node.items[i], visitor, path9); if (typeof ci === "number") i = ci - 1; else if (ci === BREAK) @@ -6994,13 +6994,13 @@ var require_visit = __commonJS({ } } } else if (identity.isPair(node)) { - path8 = Object.freeze(path8.concat(node)); - const ck = visit_("key", node.key, visitor, path8); + path9 = Object.freeze(path9.concat(node)); + const ck = visit_("key", node.key, visitor, path9); if (ck === BREAK) return BREAK; else if (ck === REMOVE) node.key = null; - const cv = visit_("value", node.value, visitor, path8); + const cv = visit_("value", node.value, visitor, path9); if (cv === BREAK) return BREAK; else if (cv === REMOVE) @@ -7021,17 +7021,17 @@ var require_visit = __commonJS({ visitAsync.BREAK = BREAK; visitAsync.SKIP = SKIP; visitAsync.REMOVE = REMOVE; - async function visitAsync_(key, node, visitor, path8) { - const ctrl = await callVisitor(key, node, visitor, path8); + async function visitAsync_(key, node, visitor, path9) { + const ctrl = await callVisitor(key, node, visitor, path9); if (identity.isNode(ctrl) || identity.isPair(ctrl)) { - replaceNode(key, path8, ctrl); - return visitAsync_(key, ctrl, visitor, path8); + replaceNode(key, path9, ctrl); + return visitAsync_(key, ctrl, visitor, path9); } if (typeof ctrl !== "symbol") { if (identity.isCollection(node)) { - path8 = Object.freeze(path8.concat(node)); + path9 = Object.freeze(path9.concat(node)); for (let i = 0; i < node.items.length; ++i) { - const ci = await visitAsync_(i, node.items[i], visitor, path8); + const ci = await visitAsync_(i, node.items[i], visitor, path9); if (typeof ci === "number") i = ci - 1; else if (ci === BREAK) @@ -7042,13 +7042,13 @@ var require_visit = __commonJS({ } } } else if (identity.isPair(node)) { - path8 = Object.freeze(path8.concat(node)); - const ck = await visitAsync_("key", node.key, visitor, path8); + path9 = Object.freeze(path9.concat(node)); + const ck = await visitAsync_("key", node.key, visitor, path9); if (ck === BREAK) return BREAK; else if (ck === REMOVE) node.key = null; - const cv = await visitAsync_("value", node.value, visitor, path8); + const cv = await visitAsync_("value", node.value, visitor, path9); if (cv === BREAK) return BREAK; else if (cv === REMOVE) @@ -7075,23 +7075,23 @@ var require_visit = __commonJS({ } return visitor; } - function callVisitor(key, node, visitor, path8) { + function callVisitor(key, node, visitor, path9) { if (typeof visitor === "function") - return visitor(key, node, path8); + return visitor(key, node, path9); if (identity.isMap(node)) - return visitor.Map?.(key, node, path8); + return visitor.Map?.(key, node, path9); if (identity.isSeq(node)) - return visitor.Seq?.(key, node, path8); + return visitor.Seq?.(key, node, path9); if (identity.isPair(node)) - return visitor.Pair?.(key, node, path8); + return visitor.Pair?.(key, node, path9); if (identity.isScalar(node)) - return visitor.Scalar?.(key, node, path8); + return visitor.Scalar?.(key, node, path9); if (identity.isAlias(node)) - return visitor.Alias?.(key, node, path8); + return visitor.Alias?.(key, node, path9); return void 0; } - function replaceNode(key, path8, node) { - const parent = path8[path8.length - 1]; + function replaceNode(key, path9, node) { + const parent = path9[path9.length - 1]; if (identity.isCollection(parent)) { parent.items[key] = node; } else if (identity.isPair(parent)) { @@ -7701,10 +7701,10 @@ var require_Collection = __commonJS({ var createNode = require_createNode(); var identity = require_identity(); var Node = require_Node(); - function collectionFromPath(schema, path8, value) { + function collectionFromPath(schema, path9, value) { let v = value; - for (let i = path8.length - 1; i >= 0; --i) { - const k = path8[i]; + for (let i = path9.length - 1; i >= 0; --i) { + const k = path9[i]; if (typeof k === "number" && Number.isInteger(k) && k >= 0) { const a = []; a[k] = v; @@ -7723,7 +7723,7 @@ var require_Collection = __commonJS({ sourceObjects: /* @__PURE__ */ new Map() }); } - var isEmptyPath = (path8) => path8 == null || typeof path8 === "object" && !!path8[Symbol.iterator]().next().done; + var isEmptyPath = (path9) => path9 == null || typeof path9 === "object" && !!path9[Symbol.iterator]().next().done; var Collection = class extends Node.NodeBase { constructor(type, schema) { super(type); @@ -7753,11 +7753,11 @@ var require_Collection = __commonJS({ * be a Pair instance or a `{ key, value }` object, which may not have a key * that already exists in the map. */ - addIn(path8, value) { - if (isEmptyPath(path8)) + addIn(path9, value) { + if (isEmptyPath(path9)) this.add(value); else { - const [key, ...rest] = path8; + const [key, ...rest] = path9; const node = this.get(key, true); if (identity.isCollection(node)) node.addIn(rest, value); @@ -7771,8 +7771,8 @@ var require_Collection = __commonJS({ * Removes a value from the collection. * @returns `true` if the item was found and removed. */ - deleteIn(path8) { - const [key, ...rest] = path8; + deleteIn(path9) { + const [key, ...rest] = path9; if (rest.length === 0) return this.delete(key); const node = this.get(key, true); @@ -7786,8 +7786,8 @@ var require_Collection = __commonJS({ * scalar values from their surrounding node; to disable set `keepScalar` to * `true` (collections are always returned intact). */ - getIn(path8, keepScalar) { - const [key, ...rest] = path8; + getIn(path9, keepScalar) { + const [key, ...rest] = path9; const node = this.get(key, true); if (rest.length === 0) return !keepScalar && identity.isScalar(node) ? node.value : node; @@ -7805,8 +7805,8 @@ var require_Collection = __commonJS({ /** * Checks if the collection includes a value with the key `key`. */ - hasIn(path8) { - const [key, ...rest] = path8; + hasIn(path9) { + const [key, ...rest] = path9; if (rest.length === 0) return this.has(key); const node = this.get(key, true); @@ -7816,8 +7816,8 @@ var require_Collection = __commonJS({ * Sets a value in this collection. For `!!set`, `value` needs to be a * boolean to add/remove the item from the set. */ - setIn(path8, value) { - const [key, ...rest] = path8; + setIn(path9, value) { + const [key, ...rest] = path9; if (rest.length === 0) { this.set(key, value); } else { @@ -10332,9 +10332,9 @@ var require_Document = __commonJS({ this.contents.add(value); } /** Adds a value to the document. */ - addIn(path8, value) { + addIn(path9, value) { if (assertCollection(this.contents)) - this.contents.addIn(path8, value); + this.contents.addIn(path9, value); } /** * Create a new `Alias` node, ensuring that the target `node` has the required anchor. @@ -10409,14 +10409,14 @@ var require_Document = __commonJS({ * Removes a value from the document. * @returns `true` if the item was found and removed. */ - deleteIn(path8) { - if (Collection.isEmptyPath(path8)) { + deleteIn(path9) { + if (Collection.isEmptyPath(path9)) { if (this.contents == null) return false; this.contents = null; return true; } - return assertCollection(this.contents) ? this.contents.deleteIn(path8) : false; + return assertCollection(this.contents) ? this.contents.deleteIn(path9) : false; } /** * Returns item at `key`, or `undefined` if not found. By default unwraps @@ -10431,10 +10431,10 @@ var require_Document = __commonJS({ * scalar values from their surrounding node; to disable set `keepScalar` to * `true` (collections are always returned intact). */ - getIn(path8, keepScalar) { - if (Collection.isEmptyPath(path8)) + getIn(path9, keepScalar) { + if (Collection.isEmptyPath(path9)) return !keepScalar && identity.isScalar(this.contents) ? this.contents.value : this.contents; - return identity.isCollection(this.contents) ? this.contents.getIn(path8, keepScalar) : void 0; + return identity.isCollection(this.contents) ? this.contents.getIn(path9, keepScalar) : void 0; } /** * Checks if the document includes a value with the key `key`. @@ -10445,10 +10445,10 @@ var require_Document = __commonJS({ /** * Checks if the document includes a value at `path`. */ - hasIn(path8) { - if (Collection.isEmptyPath(path8)) + hasIn(path9) { + if (Collection.isEmptyPath(path9)) return this.contents !== void 0; - return identity.isCollection(this.contents) ? this.contents.hasIn(path8) : false; + return identity.isCollection(this.contents) ? this.contents.hasIn(path9) : false; } /** * Sets a value in this document. For `!!set`, `value` needs to be a @@ -10465,13 +10465,13 @@ var require_Document = __commonJS({ * Sets a value in this document. For `!!set`, `value` needs to be a * boolean to add/remove the item from the set. */ - setIn(path8, value) { - if (Collection.isEmptyPath(path8)) { + setIn(path9, value) { + if (Collection.isEmptyPath(path9)) { this.contents = value; } else if (this.contents == null) { - this.contents = Collection.collectionFromPath(this.schema, Array.from(path8), value); + this.contents = Collection.collectionFromPath(this.schema, Array.from(path9), value); } else if (assertCollection(this.contents)) { - this.contents.setIn(path8, value); + this.contents.setIn(path9, value); } } /** @@ -12431,9 +12431,9 @@ var require_cst_visit = __commonJS({ visit.BREAK = BREAK; visit.SKIP = SKIP; visit.REMOVE = REMOVE; - visit.itemAtPath = (cst, path8) => { + visit.itemAtPath = (cst, path9) => { let item = cst; - for (const [field, index] of path8) { + for (const [field, index] of path9) { const tok = item?.[field]; if (tok && "items" in tok) { item = tok.items[index]; @@ -12442,23 +12442,23 @@ var require_cst_visit = __commonJS({ } return item; }; - visit.parentCollection = (cst, path8) => { - const parent = visit.itemAtPath(cst, path8.slice(0, -1)); - const field = path8[path8.length - 1][0]; + visit.parentCollection = (cst, path9) => { + const parent = visit.itemAtPath(cst, path9.slice(0, -1)); + const field = path9[path9.length - 1][0]; const coll = parent?.[field]; if (coll && "items" in coll) return coll; throw new Error("Parent collection not found"); }; - function _visit(path8, item, visitor) { - let ctrl = visitor(item, path8); + function _visit(path9, item, visitor) { + let ctrl = visitor(item, path9); if (typeof ctrl === "symbol") return ctrl; for (const field of ["key", "value"]) { const token = item[field]; if (token && "items" in token) { for (let i = 0; i < token.items.length; ++i) { - const ci = _visit(Object.freeze(path8.concat([[field, i]])), token.items[i], visitor); + const ci = _visit(Object.freeze(path9.concat([[field, i]])), token.items[i], visitor); if (typeof ci === "number") i = ci - 1; else if (ci === BREAK) @@ -12469,10 +12469,10 @@ var require_cst_visit = __commonJS({ } } if (typeof ctrl === "function" && field === "key") - ctrl = ctrl(item, path8); + ctrl = ctrl(item, path9); } } - return typeof ctrl === "function" ? ctrl(item, path8) : ctrl; + return typeof ctrl === "function" ? ctrl(item, path9) : ctrl; } exports.visit = visit; } @@ -13774,14 +13774,14 @@ var require_parser = __commonJS({ case "scalar": case "single-quoted-scalar": case "double-quoted-scalar": { - const fs8 = this.flowScalar(this.type); + const fs9 = this.flowScalar(this.type); if (atNextItem || it.value) { - map.items.push({ start, key: fs8, sep: [] }); + map.items.push({ start, key: fs9, sep: [] }); this.onKeyLine = true; } else if (it.sep) { - this.stack.push(fs8); + this.stack.push(fs9); } else { - Object.assign(it, { key: fs8, sep: [] }); + Object.assign(it, { key: fs9, sep: [] }); this.onKeyLine = true; } return; @@ -13909,13 +13909,13 @@ var require_parser = __commonJS({ case "scalar": case "single-quoted-scalar": case "double-quoted-scalar": { - const fs8 = this.flowScalar(this.type); + const fs9 = this.flowScalar(this.type); if (!it || it.value) - fc.items.push({ start: [], key: fs8, sep: [] }); + fc.items.push({ start: [], key: fs9, sep: [] }); else if (it.sep) - this.stack.push(fs8); + this.stack.push(fs9); else - Object.assign(it, { key: fs8, sep: [] }); + Object.assign(it, { key: fs9, sep: [] }); return; } case "flow-map-end": @@ -14466,10 +14466,10 @@ function mergeDefs(...defs) { function cloneDef(schema) { return mergeDefs(schema._zod.def); } -function getElementAtPath(obj, path8) { - if (!path8) +function getElementAtPath(obj, path9) { + if (!path9) return obj; - return path8.reduce((acc, key) => acc?.[key], obj); + return path9.reduce((acc, key) => acc?.[key], obj); } function promiseAllObject(promisesObj) { const keys = Object.keys(promisesObj); @@ -14878,11 +14878,11 @@ function explicitlyAborted(x, startIndex = 0) { } return false; } -function prefixIssues(path8, issues) { +function prefixIssues(path9, issues) { return issues.map((iss) => { var _a3; (_a3 = iss).path ?? (_a3.path = []); - iss.path.unshift(path8); + iss.path.unshift(path9); return iss; }); } @@ -15029,16 +15029,16 @@ function flattenError(error2, mapper = (issue2) => issue2.message) { } function formatError(error2, mapper = (issue2) => issue2.message) { const fieldErrors = { _errors: [] }; - const processError = (error3, path8 = []) => { + const processError = (error3, path9 = []) => { for (const issue2 of error3.issues) { if (issue2.code === "invalid_union" && issue2.errors.length) { - issue2.errors.map((issues) => processError({ issues }, [...path8, ...issue2.path])); + issue2.errors.map((issues) => processError({ issues }, [...path9, ...issue2.path])); } else if (issue2.code === "invalid_key") { - processError({ issues: issue2.issues }, [...path8, ...issue2.path]); + processError({ issues: issue2.issues }, [...path9, ...issue2.path]); } else if (issue2.code === "invalid_element") { - processError({ issues: issue2.issues }, [...path8, ...issue2.path]); + processError({ issues: issue2.issues }, [...path9, ...issue2.path]); } else { - const fullpath = [...path8, ...issue2.path]; + const fullpath = [...path9, ...issue2.path]; if (fullpath.length === 0) { fieldErrors._errors.push(mapper(issue2)); } else { @@ -22982,9 +22982,9 @@ var StdioServerTransport = class { }; // src/index.ts -import path7 from "node:path"; -import fs7 from "node:fs"; -import { homedir as homedir4, tmpdir } from "node:os"; +import path8 from "node:path"; +import fs8 from "node:fs"; +import { tmpdir } from "node:os"; // node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js var ExperimentalClientTasks = class { @@ -25197,6 +25197,7 @@ var AuthRequiredError = class extends Error { authUrl; }; var pendingTransport; +var pendingRegistrations = /* @__PURE__ */ new WeakMap(); function buildTransport(serverUrl, opts, chatSessionId) { const parsedUrl = new URL(serverUrl); const headers = { @@ -25230,15 +25231,35 @@ async function createRemoteClient(serverUrl, opts, chatSessionId, authRetry = fa } catch (err) { const msg = err instanceof Error ? err.message : String(err); console.error(`[auth] Code exchange failed: ${msg} \u2014 discarding stale auth state`); - authProvider.clearPendingAuth(); pendingTransport = void 0; - await authProvider.invalidateCredentials("all"); + if (!authProvider.abandonPendingSignIn(isInvalidClientError(err))) { + await authProvider.invalidateCredentials("all"); + } return createRemoteClient(serverUrl, opts, chatSessionId); } } if (authProvider?.needsFreshClient()) { - console.error("[auth] Previous auth URL didn't complete \u2014 forcing fresh DCR"); - await authProvider.invalidateCredentials("all"); + if (authProvider.abandonPendingSignIn()) { + console.error( + "[auth] Previous sign-in didn't complete \u2014 retrying with the existing client" + ); + } else { + console.error( + "[auth] Sign-in failed twice with this client \u2014 forcing fresh DCR" + ); + await authProvider.invalidateCredentials("all"); + } + } + let registrationNeeded = false; + if (authProvider?.clientInformation) { + registrationNeeded = !authProvider.clientInformation(); + if (registrationNeeded) { + const pending = pendingRegistrations.get(authProvider); + if (pending) { + await pending; + registrationNeeded = !authProvider.clientInformation(); + } + } } const client = new Client( { name: "glean", version: "1.0.0" }, @@ -25246,9 +25267,22 @@ async function createRemoteClient(serverUrl, opts, chatSessionId, authRetry = fa ); const accessTokenAtConnect = authProvider?.tokens()?.access_token; const transport = buildTransport(serverUrl, opts, chatSessionId); + let trackedRegistration; + let connectPromise; + if (registrationNeeded && authProvider) { + connectPromise = client.connect(transport); + trackedRegistration = connectPromise.then( + () => void 0, + () => void 0 + ); + pendingRegistrations.set(authProvider, trackedRegistration); + } else { + connectPromise = client.connect(transport); + } try { - await client.connect(transport); + await connectPromise; } catch (error2) { + authProvider?.releaseClientRegistrationLock?.(); if (error2 instanceof UnauthorizedError && authProvider) { const refreshedAccessToken = authProvider.tokens()?.access_token; if (!authRetry && refreshedAccessToken && refreshedAccessToken !== accessTokenAtConnect) { @@ -25269,9 +25303,17 @@ async function createRemoteClient(serverUrl, opts, chatSessionId, authRetry = fa return createRemoteClient(serverUrl, opts, chatSessionId, true); } throw error2; + } finally { + if (trackedRegistration && authProvider && pendingRegistrations.get(authProvider) === trackedRegistration) { + pendingRegistrations.delete(authProvider); + } } return client; } +function isInvalidClientError(error2) { + const msg = error2 instanceof Error ? error2.message : String(error2); + return /invalid[_ -]?client|unknown client|client authentication failed/i.test(msg); +} function isLikelyRefreshFailure(error2) { const msg = error2 instanceof Error ? error2.message : String(error2); return /refresh|invalid_grant|invalid_request|oauth/i.test(msg); @@ -25370,47 +25412,247 @@ function closeCallbackServer() { expectedState = void 0; } -// src/token-store.ts +// src/data-dir.ts import fs from "node:fs"; import path from "node:path"; +import { randomUUID } from "node:crypto"; import { homedir } from "node:os"; -var CREDENTIALS_FILENAME = "mcp-credentials.json"; var DIR_MODE = 448; var FILE_MODE = 384; -function resolveCredentialsDir() { - return process.env.PLUGIN_DATA_DIR || path.join(homedir(), ".glean"); +var MIGRATION_MARKER = ".legacy-store-migrated-v1"; +var MIGRATION_LOCK = ".legacy-store-migration.lock"; +var MIGRATED_FILES = [ + "mcp-credentials.json", + "mcp-server-url.json", + "remote-tools-cache.json", + "glean-server.log" +]; +function envValue(name) { + const value = process.env[name]?.trim(); + if (!value || value.startsWith("${")) return void 0; + return value; +} +function resolveDataDir() { + return envValue("GLEAN_AUTH_DATA_DIR") ?? path.join(homedir() || process.env.TMPDIR || "/tmp", ".glean"); +} +function legacyDataDirs() { + const canonical = path.resolve(resolveDataDir()); + const candidates = [envValue("PLUGIN_DATA_DIR"), envValue("CLAUDE_PLUGIN_DATA")]; + return [...new Set(candidates.filter((dir) => !!dir))].map((dir) => path.resolve(dir)).filter((dir) => dir !== canonical); +} +function sleepSync(ms) { + const signal = new Int32Array(new SharedArrayBuffer(4)); + Atomics.wait(signal, 0, 0, ms); +} +function lockPath(name) { + return path.join(resolveDataDir(), `.${name}.lock`); +} +function isStale(lockFile, staleMs) { + try { + return Date.now() - fs.statSync(lockFile).mtimeMs > staleMs; + } catch { + return false; + } +} +function acquireDataFileLockSync(name, options = {}) { + const waitMs = options.waitMs ?? 3e4; + const staleMs = options.staleMs ?? 12e4; + const filePath = lockPath(name); + const dir = path.dirname(filePath); + try { + fs.mkdirSync(dir, { recursive: true, mode: DIR_MODE }); + fs.chmodSync(dir, DIR_MODE); + } catch { + return void 0; + } + const deadline = Date.now() + Math.max(0, waitMs); + do { + try { + const token = randomUUID(); + const fd = fs.openSync(filePath, "wx", FILE_MODE); + try { + fs.writeFileSync( + fd, + JSON.stringify({ + pid: process.pid, + token, + createdAt: (/* @__PURE__ */ new Date()).toISOString() + }), + { encoding: "utf-8" } + ); + } finally { + fs.closeSync(fd); + } + return { path: filePath, token }; + } catch (err) { + const code = err && typeof err === "object" && "code" in err ? err.code : void 0; + if (code !== "EEXIST") return void 0; + if (isStale(filePath, staleMs)) { + try { + fs.rmSync(filePath, { force: true }); + } catch { + } + continue; + } + if (Date.now() >= deadline) return void 0; + sleepSync(Math.min(25, Math.max(1, deadline - Date.now()))); + } + } while (Date.now() <= deadline); + return void 0; +} +function releaseDataFileLock(lock) { + if (!lock) return; + try { + const contents = JSON.parse(fs.readFileSync(lock.path, "utf-8")); + if (contents.token !== lock.token) return; + fs.rmSync(lock.path, { force: true }); + } catch { + } +} +function copyFileAtomically(source, target) { + const dir = path.dirname(target); + fs.mkdirSync(dir, { recursive: true, mode: DIR_MODE }); + fs.chmodSync(dir, DIR_MODE); + const tmp = `${target}.${process.pid}.migration.tmp`; + try { + fs.copyFileSync(source, tmp); + fs.chmodSync(tmp, FILE_MODE); + fs.renameSync(tmp, target); + fs.chmodSync(target, FILE_MODE); + } finally { + try { + fs.rmSync(tmp, { force: true }); + } catch { + } + } +} +function migrateLegacyData() { + const canonical = resolveDataDir(); + const sources = legacyDataDirs(); + if (sources.length === 0) return; + const marker = path.join(canonical, MIGRATION_MARKER); + try { + if (fs.existsSync(marker)) return; + } catch { + return; + } + const lock = acquireDataFileLockSync( + MIGRATION_LOCK.slice(1), + { waitMs: 5e3, staleMs: 6e4 } + ); + if (!lock) return; + try { + if (fs.existsSync(marker)) return; + fs.mkdirSync(canonical, { recursive: true, mode: DIR_MODE }); + fs.chmodSync(canonical, DIR_MODE); + for (const filename of MIGRATED_FILES) { + const candidates = sources.map((dir) => path.join(dir, filename)).filter((file) => { + try { + return fs.statSync(file).isFile(); + } catch { + return false; + } + }).sort((a, b) => fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs); + if (candidates.length === 0) continue; + const target = path.join(canonical, filename); + const newestSource = candidates[0]; + let targetIsOlder = true; + try { + targetIsOlder = fs.statSync(target).mtimeMs < fs.statSync(newestSource).mtimeMs; + } catch { + } + if (!fs.existsSync(target) || targetIsOlder) { + copyFileAtomically(newestSource, target); + console.error(`[auth] Migrated legacy data: ${filename}`); + } + } + fs.writeFileSync( + marker, + JSON.stringify({ migratedAt: (/* @__PURE__ */ new Date()).toISOString(), sources }), + { encoding: "utf-8", mode: FILE_MODE } + ); + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + console.error(`[auth] Failed to migrate legacy data: ${msg}`); + } finally { + releaseDataFileLock(lock); + } +} +function ensureDataDir() { + const dir = resolveDataDir(); + fs.mkdirSync(dir, { recursive: true, mode: DIR_MODE }); + fs.chmodSync(dir, DIR_MODE); + return dir; } + +// src/token-store.ts +import fs2 from "node:fs"; +import path2 from "node:path"; +var CREDENTIALS_FILENAME = "mcp-credentials.json"; +var DIR_MODE2 = 448; +var FILE_MODE2 = 384; +var CLIENT_REGISTRATION_LOCK = "mcp-client-registration"; function credentialsFile() { - return path.join(resolveCredentialsDir(), CREDENTIALS_FILENAME); + return path2.join(resolveDataDir(), CREDENTIALS_FILENAME); } -function loadCredentials() { +function readCredentialsFile(filePath) { try { - const raw = fs.readFileSync(credentialsFile(), "utf-8"); + const raw = fs2.readFileSync(filePath, "utf-8"); return JSON.parse(raw); } catch { return void 0; } } +function loadCredentials() { + migrateLegacyData(); + return readCredentialsFile(credentialsFile()); +} function credentialsMtimeMs() { + migrateLegacyData(); try { - return fs.statSync(credentialsFile()).mtimeMs; + return fs2.statSync(credentialsFile()).mtimeMs; } catch { return void 0; } } -function saveCredentials(tokens, clientInfo) { +function acquireClientRegistrationLock() { + return acquireDataFileLockSync(CLIENT_REGISTRATION_LOCK, { + waitMs: 3e4, + staleMs: 12e4 + }); +} +function releaseClientRegistrationLock(lock) { + releaseDataFileLock(lock); +} +function saveCredentials(tokens, clientInfo, metadata = {}, options = {}) { try { + migrateLegacyData(); const filePath = credentialsFile(); - const dir = path.dirname(filePath); - fs.mkdirSync(dir, { recursive: true, mode: DIR_MODE }); - fs.chmodSync(dir, DIR_MODE); - const data = { tokens, clientInfo }; + const dir = ensureDataDir(); + const existing = readCredentialsFile(filePath); + const incomingTokenTime = metadata.tokenUpdatedAt ?? void 0; + const existingTokenTime = existing?.tokenUpdatedAt ?? void 0; + const existingTokenIsNewer = !options.forceTokenUpdate && existing?.tokens !== void 0 && (tokens === void 0 || existingTokenTime !== void 0 && (incomingTokenTime === void 0 || existingTokenTime > incomingTokenTime)); + const effectiveTokens = existingTokenIsNewer ? existing?.tokens : tokens; + const effectiveTokenTime = existingTokenIsNewer ? existingTokenTime : metadata.tokenUpdatedAt !== void 0 ? metadata.tokenUpdatedAt : existing?.tokenUpdatedAt; + const effectiveClientInfo = !options.forceClientUpdate && clientInfo === void 0 ? existing?.clientInfo : clientInfo; + const data = { + tokens: effectiveTokens, + clientInfo: effectiveClientInfo, + // Omitted metadata means preserve it; null explicitly clears it. + accountEmail: metadata.accountEmail !== void 0 ? metadata.accountEmail : existing?.accountEmail, + clientServerUrl: metadata.clientServerUrl !== void 0 ? metadata.clientServerUrl : existing?.clientServerUrl, + abandonedSignIns: metadata.abandonedSignIns !== void 0 ? metadata.abandonedSignIns : existing?.abandonedSignIns, + tokenUpdatedAt: effectiveTokenTime + }; const tmpPath = `${filePath}.${process.pid}.tmp`; - fs.writeFileSync(tmpPath, JSON.stringify(data, null, 2), { + fs2.writeFileSync(tmpPath, JSON.stringify(data, null, 2), { encoding: "utf-8", - mode: FILE_MODE + mode: FILE_MODE2 }); - fs.renameSync(tmpPath, filePath); + fs2.renameSync(tmpPath, filePath); + fs2.chmodSync(dir, DIR_MODE2); + fs2.chmodSync(filePath, FILE_MODE2); } catch (err) { const msg = err instanceof Error ? err.message : String(err); console.error(`[auth] Failed to persist credentials: ${msg}`); @@ -25418,7 +25660,8 @@ function saveCredentials(tokens, clientInfo) { } function clearCredentials() { try { - fs.rmSync(credentialsFile(), { force: true }); + migrateLegacyData(); + fs2.rmSync(credentialsFile(), { force: true }); } catch (err) { const msg = err instanceof Error ? err.message : String(err); console.error(`[auth] Failed to clear credentials: ${msg}`); @@ -25439,6 +25682,10 @@ function rotationGraceMs() { function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } +function normalizeAccountEmail(email2) { + const normalized = email2?.trim().toLowerCase(); + return normalized || void 0; +} function openBrowser(url2) { if (platform() === "win32") { spawn("cmd", ["/c", "start", '""', "/b", url2.replace(/&/g, "^&")], { @@ -25462,6 +25709,14 @@ var GleanOAuthClientProvider = class { _authUrlPending = false; // mtime at last read; detects sibling rewrites of the shared store. _credentialsMtimeMs; + // Consecutive abandoned sign-ins with the current client. + _abandonedSignIns = 0; + // Held from clientInformation() returning undefined until the SDK either + // persists the registration or the connection attempt fails. + _clientRegistrationLock; + _accountEmail; + _clientServerUrl; + _tokenUpdatedAt; authorizationUrl; /** * Optional hook invoked whenever the in-memory token state changes — @@ -25473,8 +25728,12 @@ var GleanOAuthClientProvider = class { constructor() { const stored = loadCredentials(); if (stored) { - this._tokens = stored.tokens; - this._clientInfo = stored.clientInfo; + this._tokens = stored.tokens ?? void 0; + this._clientInfo = stored.clientInfo ?? void 0; + this._accountEmail = stored.accountEmail ?? void 0; + this._clientServerUrl = stored.clientServerUrl ?? void 0; + this._abandonedSignIns = stored.abandonedSignIns ?? 0; + this._tokenUpdatedAt = stored.tokenUpdatedAt ?? void 0; } this._credentialsMtimeMs = credentialsMtimeMs(); } @@ -25491,9 +25750,27 @@ var GleanOAuthClientProvider = class { if (!stored) return; if (stored.tokens) { this._tokens = stored.tokens; + } else if (stored.tokenUpdatedAt !== void 0 && stored.tokenUpdatedAt !== null && (this._tokenUpdatedAt === void 0 || stored.tokenUpdatedAt > this._tokenUpdatedAt)) { + this._tokens = void 0; } if (stored.clientInfo) { this._clientInfo = stored.clientInfo; + if (this._clientRegistrationLock) { + releaseClientRegistrationLock(this._clientRegistrationLock); + this._clientRegistrationLock = void 0; + } + } + if (stored.accountEmail !== void 0) { + this._accountEmail = stored.accountEmail ?? void 0; + } + if (stored.clientServerUrl !== void 0) { + this._clientServerUrl = stored.clientServerUrl ?? void 0; + } + if (stored.abandonedSignIns !== void 0) { + this._abandonedSignIns = stored.abandonedSignIns ?? 0; + } + if (stored.tokenUpdatedAt !== void 0) { + this._tokenUpdatedAt = stored.tokenUpdatedAt ?? void 0; } } // On invalid_grant, adopt a sibling's newer on-disk token instead of @@ -25509,6 +25786,7 @@ var GleanOAuthClientProvider = class { return false; } this._tokens = diskTokens; + this._tokenUpdatedAt = stored?.tokenUpdatedAt ?? Date.now(); this._credentialsMtimeMs = diskMtime; if (stored?.clientInfo) { this._clientInfo = stored.clientInfo; @@ -25551,12 +25829,26 @@ var GleanOAuthClientProvider = class { }; } clientInformation() { + this.syncTokensFromDisk(); + if (this._clientInfo) return this._clientInfo; + if (!this._clientRegistrationLock) { + this._clientRegistrationLock = acquireClientRegistrationLock(); + this._credentialsMtimeMs = void 0; + this.syncTokensFromDisk(); + if (this._clientInfo) { + releaseClientRegistrationLock(this._clientRegistrationLock); + this._clientRegistrationLock = void 0; + } + } return this._clientInfo; } saveClientInformation(info) { + console.error(`[auth] Registered OAuth client: ${info.client_id}`); this._clientInfo = info; - saveCredentials(this._tokens, this._clientInfo); + saveCredentials(this._tokens, this._clientInfo, this.credentialMetadata()); this._credentialsMtimeMs = credentialsMtimeMs(); + releaseClientRegistrationLock(this._clientRegistrationLock); + this._clientRegistrationLock = void 0; } tokens() { this.syncTokensFromDisk(); @@ -25564,30 +25856,87 @@ var GleanOAuthClientProvider = class { } saveTokens(tokens) { this._tokens = tokens; + this._tokenUpdatedAt = Date.now(); this._authUrlPending = false; - saveCredentials(this._tokens, this._clientInfo); + this._abandonedSignIns = 0; + saveCredentials(this._tokens, this._clientInfo, this.credentialMetadata()); this._credentialsMtimeMs = credentialsMtimeMs(); this.onTokensChanged?.(tokens); } + /** Persist the account/server context without changing the grant. */ + setAccountContext(accountEmail, serverUrl) { + this._accountEmail = normalizeAccountEmail(accountEmail); + this._clientServerUrl = serverUrl; + saveCredentials(this._tokens, this._clientInfo, this.credentialMetadata()); + this._credentialsMtimeMs = credentialsMtimeMs(); + } + /** The account associated with the currently cached grant, if known. */ + accountEmail() { + return this._accountEmail; + } + /** The server for which the cached DCR client was registered, if known. */ + clientServerUrl() { + return this._clientServerUrl; + } + /** + * Force a new user sign-in while retaining a client registered for the same + * server. This is used for account switching; full setup reset clears the + * provider and registered client in the setup tool. + */ + resetAuthentication(accountEmail, serverUrl) { + const hadTokens = this._tokens !== void 0; + this._tokens = void 0; + this._tokenUpdatedAt = Date.now(); + this._accountEmail = normalizeAccountEmail(accountEmail); + this._clientServerUrl = serverUrl; + this._codeVerifier = ""; + this._pendingAuthCode = void 0; + this.authorizationUrl = void 0; + this._authUrlPending = false; + this._abandonedSignIns = 0; + saveCredentials(void 0, this._clientInfo, this.credentialMetadata(), { + forceTokenUpdate: true + }); + this._credentialsMtimeMs = credentialsMtimeMs(); + if (hadTokens) this.onTokensChanged?.(void 0); + } + credentialMetadata() { + return { + accountEmail: this._accountEmail ?? null, + clientServerUrl: this._clientServerUrl ?? null, + abandonedSignIns: this._abandonedSignIns, + tokenUpdatedAt: this._tokenUpdatedAt ?? null + }; + } async invalidateCredentials(scope) { console.error(`[auth] Invalidating credentials: scope=${scope}`); const tokensClearedBefore = this._tokens === void 0; switch (scope) { case "all": + this.releaseClientRegistrationLock(); this._tokens = void 0; this._clientInfo = void 0; + this._accountEmail = void 0; + this._clientServerUrl = void 0; this._codeVerifier = ""; this._authUrlPending = false; + this._abandonedSignIns = 0; clearCredentials(); break; case "client": + this.releaseClientRegistrationLock(); this._clientInfo = void 0; - saveCredentials(this._tokens, void 0); + saveCredentials(this._tokens, void 0, this.credentialMetadata(), { + forceClientUpdate: true + }); break; case "tokens": if (await this.adoptNewerTokenWithGrace()) return; this._tokens = void 0; - saveCredentials(void 0, this._clientInfo); + this._tokenUpdatedAt = Date.now(); + saveCredentials(void 0, this._clientInfo, this.credentialMetadata(), { + forceTokenUpdate: true + }); break; case "verifier": this._codeVerifier = ""; @@ -25597,11 +25946,36 @@ var GleanOAuthClientProvider = class { this.onTokensChanged?.(void 0); } } + releaseClientRegistrationLock() { + releaseClientRegistrationLock(this._clientRegistrationLock); + this._clientRegistrationLock = void 0; + } // True if we previously issued an authorize URL but never received tokens — // implying the URL was likely rejected by the server (e.g. stale client_id). needsFreshClient() { return this._authUrlPending && !this._tokens?.access_token && this._pendingAuthCode === void 0; } + // Abandoned sign-in: keep the client and clear the pending flow. Returns + // false after two consecutive failures (client likely dead → re-register). + abandonPendingSignIn(clientRejected = false) { + const lock = acquireDataFileLockSync("mcp-auth-recovery", { + waitMs: 5e3, + staleMs: 3e4 + }); + try { + this.syncTokensFromDisk(); + this._abandonedSignIns = clientRejected ? 2 : this._abandonedSignIns + 1; + this._codeVerifier = ""; + this._pendingAuthCode = void 0; + this.authorizationUrl = void 0; + this._authUrlPending = false; + saveCredentials(this._tokens, this._clientInfo, this.credentialMetadata()); + this._credentialsMtimeMs = credentialsMtimeMs(); + return !clientRejected && this._abandonedSignIns < 2; + } finally { + releaseDataFileLock(lock); + } + } get pendingAuthCode() { return this._pendingAuthCode; } @@ -25639,11 +26013,11 @@ var GleanOAuthClientProvider = class { // src/skill-writer.ts var import_yaml = __toESM(require_dist2(), 1); -import fs2 from "node:fs/promises"; -import path2 from "node:path"; +import fs3 from "node:fs/promises"; +import path3 from "node:path"; function isInsideDir(filePath, dir) { - const resolved = path2.resolve(filePath); - return resolved.startsWith(path2.resolve(dir) + path2.sep); + const resolved = path3.resolve(filePath); + return resolved.startsWith(path3.resolve(dir) + path3.sep); } function parseFrontmatter(content) { const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---/); @@ -25668,7 +26042,7 @@ function parseFrontmatter(content) { async function evictStaleSkills(baseDir, maxAgeMs, log, now = Date.now()) { let entries; try { - entries = await fs2.readdir(baseDir, { withFileTypes: true }); + entries = await fs3.readdir(baseDir, { withFileTypes: true }); } catch { return; } @@ -25676,12 +26050,12 @@ async function evictStaleSkills(baseDir, maxAgeMs, log, now = Date.now()) { await Promise.all( entries.map(async (entry) => { if (!entry.isDirectory()) return; - const skillDir = path2.resolve(baseDir, entry.name); + const skillDir = path3.resolve(baseDir, entry.name); if (!isInsideDir(skillDir, baseDir)) return; try { - const stat = await fs2.stat(skillDir); + const stat = await fs3.stat(skillDir); if (stat.mtimeMs < cutoff) { - await fs2.rm(skillDir, { recursive: true, force: true }); + await fs3.rm(skillDir, { recursive: true, force: true }); log?.("evict-stale-skill", { skill: entry.name }); } } catch (err) { @@ -25694,21 +26068,21 @@ async function evictStaleSkills(baseDir, maxAgeMs, log, now = Date.now()) { async function writeSkillsToDisk(skills, baseDir) { const index = []; for (const [skillName, fileMap] of Object.entries(skills)) { - const skillDir = path2.resolve(baseDir, skillName); + const skillDir = path3.resolve(baseDir, skillName); if (!isInsideDir(skillDir, baseDir)) { continue; } - await fs2.rm(skillDir, { recursive: true, force: true }); - await fs2.mkdir(skillDir, { recursive: true }); + await fs3.rm(skillDir, { recursive: true, force: true }); + await fs3.mkdir(skillDir, { recursive: true }); const writtenFiles = []; for (const [filePath, content] of Object.entries(fileMap)) { - const fullPath = path2.resolve(skillDir, filePath); + const fullPath = path3.resolve(skillDir, filePath); if (!isInsideDir(fullPath, skillDir)) { continue; } - await fs2.mkdir(path2.dirname(fullPath), { recursive: true }); + await fs3.mkdir(path3.dirname(fullPath), { recursive: true }); const text = typeof content === "string" ? content : JSON.stringify(content); - await fs2.writeFile(fullPath, text, "utf-8"); + await fs3.writeFile(fullPath, text, "utf-8"); writtenFiles.push(fullPath); } const rawSkillMd = fileMap["SKILL.md"] ?? ""; @@ -25776,17 +26150,17 @@ async function handleFindSkills(remoteClient, skillsBaseDir, args) { } // src/tools/run-tool.ts -import fs4 from "node:fs/promises"; +import fs5 from "node:fs/promises"; import os2 from "node:os"; -import path4 from "node:path"; +import path5 from "node:path"; // src/tools/approval-args.ts -import fs3 from "node:fs/promises"; -import path3 from "node:path"; +import fs4 from "node:fs/promises"; +import path4 from "node:path"; import os from "node:os"; // src/session-id.ts -import { randomUUID } from "node:crypto"; +import { randomUUID as randomUUID2 } from "node:crypto"; var fallbackSessionId; function resolveSessionId() { const fromHost = process.env.GLEAN_SESSION_ID?.trim(); @@ -25794,7 +26168,7 @@ function resolveSessionId() { return fromHost; } if (!fallbackSessionId) { - fallbackSessionId = randomUUID(); + fallbackSessionId = randomUUID2(); } return fallbackSessionId; } @@ -25873,10 +26247,10 @@ function formatArgumentsForFile(toolName, args) { async function writeApprovalArgsFile(toolName, args) { const base = process.env.PLUGIN_DATA_DIR || process.env.CLAUDE_PLUGIN_DATA || os.tmpdir(); const sessionId = resolveSessionId().replace(/[^a-zA-Z0-9_-]/g, "-").slice(0, 64); - const dir = path3.join(base, "glean-approvals", sessionId); - await fs3.mkdir(dir, { recursive: true }); - const file = path3.join(dir, "glean-approval-args.md"); - await fs3.writeFile(file, formatArgumentsForFile(toolName, args), "utf-8"); + const dir = path4.join(base, "glean-approvals", sessionId); + await fs4.mkdir(dir, { recursive: true }); + const file = path4.join(dir, "glean-approval-args.md"); + await fs4.writeFile(file, formatArgumentsForFile(toolName, args), "utf-8"); return file; } @@ -25926,7 +26300,7 @@ async function resolveFileArgs(fileArgs, baseArgs, inputSchema) { `file_args.${argName} must be a non-empty string path` ); } - if (!path4.isAbsolute(filePathRaw)) { + if (!path5.isAbsolute(filePathRaw)) { throw new FileArgsError( `file_args.${argName} must be an absolute path; got "${filePathRaw}"` ); @@ -25938,7 +26312,7 @@ async function resolveFileArgs(fileArgs, baseArgs, inputSchema) { } let stat; try { - stat = await fs4.stat(filePathRaw); + stat = await fs5.stat(filePathRaw); } catch (err) { const msg = err instanceof Error ? err.message : String(err); throw new FileArgsError( @@ -25955,7 +26329,7 @@ async function resolveFileArgs(fileArgs, baseArgs, inputSchema) { `file_args.${argName}: "${filePathRaw}" is ${stat.size} bytes, exceeds ${maxBytes} byte limit (set GLEAN_FILE_ARG_MAX_BYTES to override)` ); } - const content = await fs4.readFile(filePathRaw, "utf-8"); + const content = await fs5.readFile(filePathRaw, "utf-8"); const types = declaredParamTypes(inputSchema, argName); if (types.has("object") || types.has("array")) { try { @@ -25978,12 +26352,12 @@ async function resolveFileArgs(fileArgs, baseArgs, inputSchema) { } async function findToolJson(skillsBaseDir, toolName) { try { - const skillDirs = await fs4.readdir(skillsBaseDir, { withFileTypes: true }); + const skillDirs = await fs5.readdir(skillsBaseDir, { withFileTypes: true }); for (const dir of skillDirs) { if (!dir.isDirectory()) continue; - const toolPath = path4.join(skillsBaseDir, dir.name, "tools", `${toolName}.json`); + const toolPath = path5.join(skillsBaseDir, dir.name, "tools", `${toolName}.json`); try { - const content = await fs4.readFile(toolPath, "utf-8"); + const content = await fs5.readFile(toolPath, "utf-8"); return JSON.parse(content); } catch { continue; @@ -26024,13 +26398,13 @@ function primeElicitationCancellation(mcpServer) { }); } function permissionModeMarkerPath() { - const base = process.env.CLAUDE_PLUGIN_DATA || path4.join(os2.homedir(), ".glean"); + const base = process.env.CLAUDE_PLUGIN_DATA || path5.join(os2.homedir(), ".glean"); const sessionId = resolveSessionId().replace(/[^a-zA-Z0-9_-]/g, "-").slice(0, 64); - return path4.join(base, "glean-hitl-mode", `${sessionId}.json`); + return path5.join(base, "glean-hitl-mode", `${sessionId}.json`); } async function currentPermissionMode() { try { - const raw = await fs4.readFile(permissionModeMarkerPath(), "utf-8"); + const raw = await fs5.readFile(permissionModeMarkerPath(), "utf-8"); const parsed = JSON.parse(raw); return typeof parsed.permission_mode === "string" ? parsed.permission_mode : null; } catch { @@ -26127,21 +26501,21 @@ function runToolAnnotations(enableHitl, clientSupportsElicitation, isCursor) { } // src/url-config-store.ts -import fs5 from "node:fs"; -import path5 from "node:path"; -import { homedir as homedir2 } from "node:os"; +import fs6 from "node:fs"; +import path6 from "node:path"; var CONFIG_FILENAME = "mcp-server-url.json"; -var DIR_MODE2 = 448; -var FILE_MODE2 = 384; +var DIR_MODE3 = 448; +var FILE_MODE3 = 384; function resolveConfigDir() { - return process.env.PLUGIN_DATA_DIR || path5.join(homedir2(), ".glean"); + return resolveDataDir(); } function configFile() { - return path5.join(resolveConfigDir(), CONFIG_FILENAME); + return path6.join(resolveConfigDir(), CONFIG_FILENAME); } function loadServerUrl() { + migrateLegacyData(); try { - const raw = fs5.readFileSync(configFile(), "utf-8"); + const raw = fs6.readFileSync(configFile(), "utf-8"); const data = JSON.parse(raw); if (typeof data.serverUrl !== "string" || !data.serverUrl) return void 0; return data.serverUrl; @@ -26150,40 +26524,41 @@ function loadServerUrl() { } } function saveServerUrl(url2) { + migrateLegacyData(); const filePath = configFile(); - const dir = path5.dirname(filePath); - fs5.mkdirSync(dir, { recursive: true, mode: DIR_MODE2 }); - fs5.chmodSync(dir, DIR_MODE2); + const dir = ensureDataDir(); + fs6.chmodSync(dir, DIR_MODE3); const data = { serverUrl: url2 }; - fs5.writeFileSync(filePath, JSON.stringify(data, null, 2), { + fs6.writeFileSync(filePath, JSON.stringify(data, null, 2), { encoding: "utf-8", - mode: FILE_MODE2 + mode: FILE_MODE3 }); - fs5.chmodSync(filePath, FILE_MODE2); + fs6.chmodSync(filePath, FILE_MODE3); } function clearServerUrl() { + migrateLegacyData(); try { - fs5.rmSync(configFile(), { force: true }); + fs6.rmSync(configFile(), { force: true }); } catch { } } // src/remote-tools-cache-store.ts -import fs6 from "node:fs"; -import path6 from "node:path"; -import { homedir as homedir3 } from "node:os"; +import fs7 from "node:fs"; +import path7 from "node:path"; var CACHE_FILENAME = "remote-tools-cache.json"; -var DIR_MODE3 = 448; -var FILE_MODE3 = 384; +var DIR_MODE4 = 448; +var FILE_MODE4 = 384; function resolveCacheDir() { - return process.env.PLUGIN_DATA_DIR || path6.join(homedir3(), ".glean"); + return resolveDataDir(); } function cacheFile() { - return path6.join(resolveCacheDir(), CACHE_FILENAME); + return path7.join(resolveCacheDir(), CACHE_FILENAME); } function readStore() { + migrateLegacyData(); try { - const raw = fs6.readFileSync(cacheFile(), "utf-8"); + const raw = fs7.readFileSync(cacheFile(), "utf-8"); const data = JSON.parse(raw); if (data && typeof data === "object" && !Array.isArray(data)) { return data; @@ -26195,14 +26570,13 @@ function readStore() { } function writeStore(store) { const filePath = cacheFile(); - const dir = path6.dirname(filePath); - fs6.mkdirSync(dir, { recursive: true, mode: DIR_MODE3 }); - fs6.chmodSync(dir, DIR_MODE3); - fs6.writeFileSync(filePath, JSON.stringify(store, null, 2), { + const dir = ensureDataDir(); + fs7.chmodSync(dir, DIR_MODE4); + fs7.writeFileSync(filePath, JSON.stringify(store, null, 2), { encoding: "utf-8", - mode: FILE_MODE3 + mode: FILE_MODE4 }); - fs6.chmodSync(filePath, FILE_MODE3); + fs7.chmodSync(filePath, FILE_MODE4); } function loadRemoteTools(serverUrl) { if (!serverUrl) return []; @@ -26223,16 +26597,17 @@ function saveRemoteTools(serverUrl, tools) { } } function clearRemoteTools(serverUrl) { + migrateLegacyData(); try { if (!serverUrl) { - fs6.rmSync(cacheFile(), { force: true }); + fs7.rmSync(cacheFile(), { force: true }); return; } const store = readStore(); if (store[serverUrl] !== void 0) { delete store[serverUrl]; if (Object.keys(store).length === 0) { - fs6.rmSync(cacheFile(), { force: true }); + fs7.rmSync(cacheFile(), { force: true }); } else { writeStore(store); } @@ -26394,6 +26769,15 @@ function sameOrigin(a, b) { } } +// src/server-url.ts +var MCP_GATEWAY_PATH = "/mcp/gateway/proxy"; +function normalizeServerUrl(raw) { + const parsed = new URL(raw); + const pathname = parsed.pathname.replace(/\/+$/, ""); + const prefix = pathname.endsWith(MCP_GATEWAY_PATH) ? pathname.slice(0, -MCP_GATEWAY_PATH.length) : pathname === "/" ? "" : pathname; + return `${parsed.origin}${prefix}${MCP_GATEWAY_PATH}${parsed.search}`; +} + // src/index.ts function readEnv(...keys) { for (const key of keys) { @@ -26409,10 +26793,6 @@ function resolveServerUrl() { if (fromEnv) return fromEnv; return loadServerUrl(); } -function normalizeServerUrl(raw) { - const parsed = new URL(raw); - return `${parsed.origin}/mcp/gateway/proxy`; -} var SETUP_REQUIRED_TEXT = `[SETUP_REQUIRED] To connect, enter your work email (e.g. you@acme.com) and we'll find your Glean instance automatically. @@ -26421,14 +26801,13 @@ var EMAIL_RESOLVE_FAILED_TEXT = `Double-check the email for typos and try again var SETUP_NEEDED_ERROR = "Glean is not configured yet. Call the `setup` tool first to provide your Glean Server URL before using find_skills or run_tool."; var AUTH_REDIRECT_TO_SETUP_TEXT = "[SETUP_REQUIRED]\n\nAuthentication is required. Call the `setup` tool (no arguments) to sign in to Glean, then retry this tool."; function resolveLogPath() { - const base = process.env.PLUGIN_DATA_DIR || path7.join(homedir4(), ".glean"); - return path7.join(base, "glean-server.log"); + return path8.join(resolveDataDir(), "glean-server.log"); } var LOG_PATH = resolveLogPath(); try { - const logDir = path7.dirname(LOG_PATH); - fs7.mkdirSync(logDir, { recursive: true, mode: 448 }); - fs7.chmodSync(logDir, 448); + const logDir = path8.dirname(LOG_PATH); + fs8.mkdirSync(logDir, { recursive: true, mode: 448 }); + fs8.chmodSync(logDir, 448); } catch { } function logLine(label, detail) { @@ -26437,8 +26816,8 @@ function logLine(label, detail) { const line = `${ts} ${label}${suffix} `; try { - fs7.appendFileSync(LOG_PATH, line, { mode: 384 }); - fs7.chmodSync(LOG_PATH, 384); + fs8.appendFileSync(LOG_PATH, line, { mode: 384 }); + fs8.chmodSync(LOG_PATH, 384); } catch { } console.error(line.trimEnd()); @@ -26447,7 +26826,7 @@ function resolveSkillsBaseDir() { if (process.env.SKILLS_BASE_DIR) { return process.env.SKILLS_BASE_DIR; } - return path7.join(tmpdir(), "glean-skills-cache"); + return path8.join(tmpdir(), "glean-skills-cache"); } var server = new Server( { name: "glean", version: "1.0.0" }, @@ -26515,7 +26894,7 @@ var RUN_TOOL_TOOL = { var SETUP_TOOL = { name: "setup", annotations: { readOnlyHint: true }, - description: "Check or configure the Glean connection. Setup completes in three stages: (1) resolve and save the Server URL, (2) authenticate, (3) fetch the remote tool catalog. Call with no arguments to advance through the next missing stage. Call with email to look up and (re)configure user's Glean instance. Call with reset=true to clear all configuration.", + description: "Check or configure the Glean connection. Setup completes in three stages: (1) resolve and save the Server URL, (2) authenticate, (3) fetch the remote tool catalog. Call with no arguments to advance through the next missing stage. Call with email to look up and (re)configure user's Glean instance. Call with reset=true to clear the current authentication, setup URL, and registered DCR client before starting a new setup flow.", inputSchema: { type: "object", properties: { @@ -26529,7 +26908,7 @@ var SETUP_TOOL = { }, reset: { type: "boolean", - description: "Clear cached URL, credentials, and remote tool cache." + description: "Clear the cached URL, authentication, registered OAuth client, and remote tool cache. The next setup registers a new client." } }, required: [] @@ -26709,6 +27088,10 @@ async function advanceSetup() { if (!serverUrl) { return { content: [{ type: "text", text: SETUP_REQUIRED_TEXT }] }; } + const provider = getOAuthProvider(); + if (provider.clientServerUrl() !== serverUrl) { + provider.setAccountContext(provider.accountEmail(), serverUrl); + } const conn = await connectWithSignIn(serverUrl); if (!conn.ok) return conn.result; const remoteClient = conn.client; @@ -26890,19 +27273,22 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => { clientInfo: server.getClientVersion() ?? null }); if (args.reset === true) { + const hadClient = !!loadCredentials()?.clientInfo; clearServerUrl(); clearCredentials(); clearRemoteTools(); oauthProvider = void 0; cachedRemoteTools = []; - logLine("setup.reset"); + logLine("setup.reset", { + clearedClient: hadClient + }); server.sendToolListChanged().catch(() => { }); return { content: [ { type: "text", - text: "Glean configuration has been reset. Call setup again with your email to reconfigure." + text: "Glean authentication has been reset, including the registered OAuth client. Call setup again with your email to register a new client and sign in." } ] }; @@ -26943,6 +27329,12 @@ ${EMAIL_RESOLVE_FAILED_TEXT}` isError: true }; } + const previousUrl = loadServerUrl(); + const stored = loadCredentials(); + const requestedEmail = normalizeAccountEmail(email2); + const urlChanged = previousUrl !== normalized; + const reusableClient = !!stored?.clientInfo && stored.clientServerUrl === normalized; + const accountChanged = !!requestedEmail && !!stored?.tokens && stored.accountEmail !== requestedEmail; try { saveServerUrl(normalized); } catch (err) { @@ -26954,10 +27346,26 @@ ${EMAIL_RESOLVE_FAILED_TEXT}` isError: true }; } - clearCredentials(); - oauthProvider = void 0; + if (urlChanged && !reusableClient) { + clearCredentials(); + oauthProvider = void 0; + } + const provider = getOAuthProvider(); + if (accountChanged) { + provider.resetAuthentication(requestedEmail, normalized); + } else { + provider.setAccountContext( + requestedEmail ?? provider.accountEmail(), + normalized + ); + } cachedRemoteTools = loadRemoteTools(normalized); - logLine("setup.configured", { serverUrl: normalized }); + logLine("setup.configured", { + serverUrl: normalized, + urlChanged, + reusableClient, + accountChanged + }); } return await advanceSetup(); } diff --git a/plugins/glean/start.mjs b/plugins/glean/start.mjs index 84e549b..2bf85d8 100644 --- a/plugins/glean/start.mjs +++ b/plugins/glean/start.mjs @@ -21,7 +21,9 @@ function val(v) { const launchCwd = process.cwd(); -// Resolve where credentials, caches, and config are stored. +// Resolve the host-managed plugin data directory for skills/cache state. +// Auth credentials and setup state are resolved by the bundle to the stable +// per-user ~/.glean directory, with one-time migration from this legacy path. // CLAUDE_PLUGIN_DATA is the managed lifecycle dir provided by the plugin host. const pluginDataDir = val(process.env.CLAUDE_PLUGIN_DATA) ?? diff --git a/src/auth-provider.ts b/src/auth-provider.ts index cebf440..4c4d198 100644 --- a/src/auth-provider.ts +++ b/src/auth-provider.ts @@ -8,10 +8,18 @@ import { execFile, spawn } from "node:child_process"; import { platform } from "node:os"; import { getCallbackUrl, setExpectedState } from "./auth-callback-server.js"; import { + acquireDataFileLockSync, + releaseDataFileLock, + type DataLockHandle, +} from "./data-dir.js"; +import { + acquireClientRegistrationLock, clearCredentials, credentialsMtimeMs, loadCredentials, + releaseClientRegistrationLock, saveCredentials, + type CredentialMetadata, } from "./token-store.js"; export type InvalidationScope = "all" | "client" | "tokens" | "verifier"; @@ -33,6 +41,11 @@ function sleep(ms: number): Promise { return new Promise((resolve) => setTimeout(resolve, ms)); } +export function normalizeAccountEmail(email: string | undefined): string | undefined { + const normalized = email?.trim().toLowerCase(); + return normalized || undefined; +} + /** * Open `url` in the user's default browser. Used for the self-open sign-in * path when the client does not support URL-mode elicitation (where the client @@ -71,6 +84,14 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { private _authUrlPending = false; // mtime at last read; detects sibling rewrites of the shared store. private _credentialsMtimeMs: number | undefined; + // Consecutive abandoned sign-ins with the current client. + private _abandonedSignIns = 0; + // Held from clientInformation() returning undefined until the SDK either + // persists the registration or the connection attempt fails. + private _clientRegistrationLock: DataLockHandle | undefined; + private _accountEmail: string | undefined; + private _clientServerUrl: string | undefined; + private _tokenUpdatedAt: number | undefined; authorizationUrl: string | undefined; @@ -85,8 +106,12 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { constructor() { const stored = loadCredentials(); if (stored) { - this._tokens = stored.tokens as OAuthTokens | undefined; - this._clientInfo = stored.clientInfo as OAuthClientInformationMixed | undefined; + this._tokens = (stored.tokens ?? undefined) as OAuthTokens | undefined; + this._clientInfo = (stored.clientInfo ?? undefined) as OAuthClientInformationMixed | undefined; + this._accountEmail = stored.accountEmail ?? undefined; + this._clientServerUrl = stored.clientServerUrl ?? undefined; + this._abandonedSignIns = stored.abandonedSignIns ?? 0; + this._tokenUpdatedAt = stored.tokenUpdatedAt ?? undefined; } this._credentialsMtimeMs = credentialsMtimeMs(); } @@ -107,9 +132,35 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { if (!stored) return; if (stored.tokens) { this._tokens = stored.tokens as OAuthTokens; + } else if ( + stored.tokenUpdatedAt !== undefined && + stored.tokenUpdatedAt !== null && + (this._tokenUpdatedAt === undefined || + stored.tokenUpdatedAt > this._tokenUpdatedAt) + ) { + // A newer explicit reset/invalidation is different from a transient + // missing file or a client-only rewrite; propagate the token tombstone. + this._tokens = undefined; } if (stored.clientInfo) { this._clientInfo = stored.clientInfo as OAuthClientInformationMixed; + // A sibling completed the registration while this process was waiting. + if (this._clientRegistrationLock) { + releaseClientRegistrationLock(this._clientRegistrationLock); + this._clientRegistrationLock = undefined; + } + } + if (stored.accountEmail !== undefined) { + this._accountEmail = stored.accountEmail ?? undefined; + } + if (stored.clientServerUrl !== undefined) { + this._clientServerUrl = stored.clientServerUrl ?? undefined; + } + if (stored.abandonedSignIns !== undefined) { + this._abandonedSignIns = stored.abandonedSignIns ?? 0; + } + if (stored.tokenUpdatedAt !== undefined) { + this._tokenUpdatedAt = stored.tokenUpdatedAt ?? undefined; } } @@ -133,6 +184,7 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { return false; } this._tokens = diskTokens; + this._tokenUpdatedAt = stored?.tokenUpdatedAt ?? Date.now(); this._credentialsMtimeMs = diskMtime; if (stored?.clientInfo) { this._clientInfo = stored.clientInfo as OAuthClientInformationMixed; @@ -183,13 +235,35 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { } clientInformation(): OAuthClientInformationMixed | undefined { + // Pick up a sibling's registration; the SDK registers whenever this is undefined. + this.syncTokensFromDisk(); + if (this._clientInfo) return this._clientInfo; + + // The SDK's provider API is synchronous here. Acquire a lock before + // returning undefined and hold it until saveClientInformation() or the + // connection error path. A second process therefore waits for the first + // registration to land instead of registering a second client. + if (!this._clientRegistrationLock) { + this._clientRegistrationLock = acquireClientRegistrationLock(); + // The lock may have been held by a sibling that just completed DCR. + // Force a post-lock read before deciding that registration is needed. + this._credentialsMtimeMs = undefined; + this.syncTokensFromDisk(); + if (this._clientInfo) { + releaseClientRegistrationLock(this._clientRegistrationLock); + this._clientRegistrationLock = undefined; + } + } return this._clientInfo; } saveClientInformation(info: OAuthClientInformationMixed): void { + console.error(`[auth] Registered OAuth client: ${info.client_id}`); this._clientInfo = info; - saveCredentials(this._tokens, this._clientInfo); + saveCredentials(this._tokens, this._clientInfo, this.credentialMetadata()); this._credentialsMtimeMs = credentialsMtimeMs(); + releaseClientRegistrationLock(this._clientRegistrationLock); + this._clientRegistrationLock = undefined; } tokens(): OAuthTokens | undefined { @@ -199,33 +273,96 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { saveTokens(tokens: OAuthTokens): void { this._tokens = tokens; + this._tokenUpdatedAt = Date.now(); this._authUrlPending = false; - saveCredentials(this._tokens, this._clientInfo); + this._abandonedSignIns = 0; + saveCredentials(this._tokens, this._clientInfo, this.credentialMetadata()); // Own write must not look like a sibling change. this._credentialsMtimeMs = credentialsMtimeMs(); this.onTokensChanged?.(tokens); } + /** Persist the account/server context without changing the grant. */ + setAccountContext(accountEmail: string | undefined, serverUrl: string): void { + this._accountEmail = normalizeAccountEmail(accountEmail); + this._clientServerUrl = serverUrl; + saveCredentials(this._tokens, this._clientInfo, this.credentialMetadata()); + this._credentialsMtimeMs = credentialsMtimeMs(); + } + + /** The account associated with the currently cached grant, if known. */ + accountEmail(): string | undefined { + return this._accountEmail; + } + + /** The server for which the cached DCR client was registered, if known. */ + clientServerUrl(): string | undefined { + return this._clientServerUrl; + } + + /** + * Force a new user sign-in while retaining a client registered for the same + * server. This is used for account switching; full setup reset clears the + * provider and registered client in the setup tool. + */ + resetAuthentication(accountEmail: string | undefined, serverUrl: string): void { + const hadTokens = this._tokens !== undefined; + this._tokens = undefined; + this._tokenUpdatedAt = Date.now(); + this._accountEmail = normalizeAccountEmail(accountEmail); + this._clientServerUrl = serverUrl; + this._codeVerifier = ""; + this._pendingAuthCode = undefined; + this.authorizationUrl = undefined; + this._authUrlPending = false; + this._abandonedSignIns = 0; + saveCredentials(undefined, this._clientInfo, this.credentialMetadata(), { + forceTokenUpdate: true, + }); + this._credentialsMtimeMs = credentialsMtimeMs(); + if (hadTokens) this.onTokensChanged?.(undefined); + } + + private credentialMetadata(): CredentialMetadata { + return { + accountEmail: this._accountEmail ?? null, + clientServerUrl: this._clientServerUrl ?? null, + abandonedSignIns: this._abandonedSignIns, + tokenUpdatedAt: this._tokenUpdatedAt ?? null, + }; + } + async invalidateCredentials(scope: InvalidationScope): Promise { console.error(`[auth] Invalidating credentials: scope=${scope}`); const tokensClearedBefore = this._tokens === undefined; switch (scope) { case "all": + this.releaseClientRegistrationLock(); this._tokens = undefined; this._clientInfo = undefined; + this._accountEmail = undefined; + this._clientServerUrl = undefined; this._codeVerifier = ""; this._authUrlPending = false; + // Fresh client → fresh retry budget. + this._abandonedSignIns = 0; clearCredentials(); break; case "client": + this.releaseClientRegistrationLock(); this._clientInfo = undefined; - saveCredentials(this._tokens, undefined); + saveCredentials(this._tokens, undefined, this.credentialMetadata(), { + forceClientUpdate: true, + }); break; case "tokens": // Usually a sibling's rotation — try adopting before clearing. if (await this.adoptNewerTokenWithGrace()) return; this._tokens = undefined; - saveCredentials(undefined, this._clientInfo); + this._tokenUpdatedAt = Date.now(); + saveCredentials(undefined, this._clientInfo, this.credentialMetadata(), { + forceTokenUpdate: true, + }); break; case "verifier": this._codeVerifier = ""; @@ -239,6 +376,11 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { } } + releaseClientRegistrationLock(): void { + releaseClientRegistrationLock(this._clientRegistrationLock); + this._clientRegistrationLock = undefined; + } + // True if we previously issued an authorize URL but never received tokens — // implying the URL was likely rejected by the server (e.g. stale client_id). needsFreshClient(): boolean { @@ -249,6 +391,32 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { ); } + // Abandoned sign-in: keep the client and clear the pending flow. Returns + // false after two consecutive failures (client likely dead → re-register). + abandonPendingSignIn(clientRejected = false): boolean { + const lock = acquireDataFileLockSync("mcp-auth-recovery", { + waitMs: 5_000, + staleMs: 30_000, + }); + try { + // Re-read first so a sibling's token/client metadata is not clobbered by + // this process's recovery bookkeeping. + this.syncTokensFromDisk(); + this._abandonedSignIns = clientRejected + ? 2 + : this._abandonedSignIns + 1; + this._codeVerifier = ""; + this._pendingAuthCode = undefined; + this.authorizationUrl = undefined; + this._authUrlPending = false; + saveCredentials(this._tokens, this._clientInfo, this.credentialMetadata()); + this._credentialsMtimeMs = credentialsMtimeMs(); + return !clientRejected && this._abandonedSignIns < 2; + } finally { + releaseDataFileLock(lock); + } + } + get pendingAuthCode(): string | undefined { return this._pendingAuthCode; } diff --git a/src/data-dir.ts b/src/data-dir.ts new file mode 100644 index 0000000..b872934 --- /dev/null +++ b/src/data-dir.ts @@ -0,0 +1,249 @@ +import fs from "node:fs"; +import path from "node:path"; +import { randomUUID } from "node:crypto"; +import { homedir } from "node:os"; + +const DIR_MODE = 0o700; +const FILE_MODE = 0o600; +const MIGRATION_MARKER = ".legacy-store-migrated-v1"; +const MIGRATION_LOCK = ".legacy-store-migration.lock"; + +// These are the files that historically followed PLUGIN_DATA_DIR. Auth and +// setup state now live in the stable per-user directory so terminal, VS Code, +// Cursor, and managed plugin launches share one state store. +const MIGRATED_FILES = [ + "mcp-credentials.json", + "mcp-server-url.json", + "remote-tools-cache.json", + "glean-server.log", +]; + +export interface DataLockOptions { + waitMs?: number; + staleMs?: number; +} + +export interface DataLockHandle { + path: string; + token: string; +} + +function envValue(name: string): string | undefined { + const value = process.env[name]?.trim(); + if (!value || value.startsWith("${")) return undefined; + return value; +} + +/** + * Stable auth/config directory shared by every host and launcher. + * + * GLEAN_AUTH_DATA_DIR is intentionally an explicit escape hatch for tests and + * controlled deployments. PLUGIN_DATA_DIR is deliberately not used here: it + * is host-managed and was the source of the terminal/plugin store split. + */ +export function resolveDataDir(): string { + return ( + envValue("GLEAN_AUTH_DATA_DIR") ?? + path.join(homedir() || process.env.TMPDIR || "/tmp", ".glean") + ); +} + +function legacyDataDirs(): string[] { + const canonical = path.resolve(resolveDataDir()); + const candidates = [envValue("PLUGIN_DATA_DIR"), envValue("CLAUDE_PLUGIN_DATA")]; + return [...new Set(candidates.filter((dir): dir is string => !!dir))] + .map((dir) => path.resolve(dir)) + .filter((dir) => dir !== canonical); +} + +function sleepSync(ms: number): void { + const signal = new Int32Array(new SharedArrayBuffer(4)); + Atomics.wait(signal, 0, 0, ms); +} + +function lockPath(name: string): string { + return path.join(resolveDataDir(), `.${name}.lock`); +} + +function isStale(lockFile: string, staleMs: number): boolean { + try { + return Date.now() - fs.statSync(lockFile).mtimeMs > staleMs; + } catch { + return false; + } +} + +/** + * Acquire a small cross-process lock using O_EXCL semantics. The returned + * path must be released by the caller. Stale locks are recoverable after the + * configured timeout so a crashed plugin cannot permanently block auth. + */ +export function acquireDataFileLockSync( + name: string, + options: DataLockOptions = {}, +): DataLockHandle | undefined { + const waitMs = options.waitMs ?? 30_000; + const staleMs = options.staleMs ?? 120_000; + const filePath = lockPath(name); + const dir = path.dirname(filePath); + + try { + fs.mkdirSync(dir, { recursive: true, mode: DIR_MODE }); + fs.chmodSync(dir, DIR_MODE); + } catch { + return undefined; + } + + const deadline = Date.now() + Math.max(0, waitMs); + do { + try { + const token = randomUUID(); + const fd = fs.openSync(filePath, "wx", FILE_MODE); + try { + fs.writeFileSync( + fd, + JSON.stringify({ + pid: process.pid, + token, + createdAt: new Date().toISOString(), + }), + { encoding: "utf-8" }, + ); + } finally { + fs.closeSync(fd); + } + return { path: filePath, token }; + } catch (err) { + const code = err && typeof err === "object" && "code" in err + ? (err as { code?: string }).code + : undefined; + if (code !== "EEXIST") return undefined; + if (isStale(filePath, staleMs)) { + try { + fs.rmSync(filePath, { force: true }); + } catch { + /* another process may have replaced or removed the lock */ + } + continue; + } + if (Date.now() >= deadline) return undefined; + sleepSync(Math.min(25, Math.max(1, deadline - Date.now()))); + } + } while (Date.now() <= deadline); + + return undefined; +} + +export function releaseDataFileLock(lock: DataLockHandle | undefined): void { + if (!lock) return; + try { + const contents = JSON.parse(fs.readFileSync(lock.path, "utf-8")) as { + token?: string; + }; + if (contents.token !== lock.token) return; + fs.rmSync(lock.path, { force: true }); + } catch { + /* best effort; stale-lock recovery handles a crashed owner */ + } +} + +function copyFileAtomically(source: string, target: string): void { + const dir = path.dirname(target); + fs.mkdirSync(dir, { recursive: true, mode: DIR_MODE }); + fs.chmodSync(dir, DIR_MODE); + const tmp = `${target}.${process.pid}.migration.tmp`; + try { + fs.copyFileSync(source, tmp); + fs.chmodSync(tmp, FILE_MODE); + fs.renameSync(tmp, target); + fs.chmodSync(target, FILE_MODE); + } finally { + try { + fs.rmSync(tmp, { force: true }); + } catch { + /* ignore cleanup failures */ + } + } +} + +/** + * Migrate files from the old host-managed store(s) once. If both stores exist, + * the newest source file wins; after migration all current code writes only to + * resolveDataDir(). The marker prevents an old, already-running process from + * repeatedly overwriting the canonical store on every request. + */ +export function migrateLegacyData(): void { + const canonical = resolveDataDir(); + const sources = legacyDataDirs(); + if (sources.length === 0) return; + + const marker = path.join(canonical, MIGRATION_MARKER); + try { + if (fs.existsSync(marker)) return; + } catch { + return; + } + + const lock = acquireDataFileLockSync( + MIGRATION_LOCK.slice(1), + { waitMs: 5_000, staleMs: 60_000 }, + ); + if (!lock) return; + + try { + if (fs.existsSync(marker)) return; + fs.mkdirSync(canonical, { recursive: true, mode: DIR_MODE }); + fs.chmodSync(canonical, DIR_MODE); + + for (const filename of MIGRATED_FILES) { + const candidates = sources + .map((dir) => path.join(dir, filename)) + .filter((file) => { + try { + return fs.statSync(file).isFile(); + } catch { + return false; + } + }) + .sort((a, b) => fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs); + if (candidates.length === 0) continue; + + const target = path.join(canonical, filename); + const newestSource = candidates[0]; + let targetIsOlder = true; + try { + targetIsOlder = fs.statSync(target).mtimeMs < fs.statSync(newestSource).mtimeMs; + } catch { + /* target does not exist */ + } + if (!fs.existsSync(target) || targetIsOlder) { + copyFileAtomically(newestSource, target); + console.error(`[auth] Migrated legacy data: ${filename}`); + } + } + + fs.writeFileSync( + marker, + JSON.stringify({ migratedAt: new Date().toISOString(), sources }), + { encoding: "utf-8", mode: FILE_MODE }, + ); + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + console.error(`[auth] Failed to migrate legacy data: ${msg}`); + } finally { + releaseDataFileLock(lock); + } +} + +export function ensureDataDir(): string { + const dir = resolveDataDir(); + fs.mkdirSync(dir, { recursive: true, mode: DIR_MODE }); + fs.chmodSync(dir, DIR_MODE); + return dir; +} + +export const dataDirConstants = { + DIR_MODE, + FILE_MODE, + MIGRATION_MARKER, +}; diff --git a/src/index.ts b/src/index.ts index 82514e9..10230d7 100644 --- a/src/index.ts +++ b/src/index.ts @@ -8,13 +8,17 @@ import { } from "@modelcontextprotocol/sdk/types.js"; import path from "node:path"; import fs from "node:fs"; -import { homedir, tmpdir } from "node:os"; +import { tmpdir } from "node:os"; import { AuthRequiredError, createRemoteClient, type RemoteClientOptions, } from "./remote-client.js"; -import { GleanOAuthClientProvider, openBrowser } from "./auth-provider.js"; +import { + GleanOAuthClientProvider, + normalizeAccountEmail, + openBrowser, +} from "./auth-provider.js"; import { startCallbackServer, closeCallbackServer, @@ -31,7 +35,11 @@ import { saveServerUrl, clearServerUrl, } from "./url-config-store.js"; -import { clearCredentials } from "./token-store.js"; +import { + clearCredentials, + loadCredentials, + saveCredentials, +} from "./token-store.js"; import { loadRemoteTools, saveRemoteTools, @@ -45,6 +53,8 @@ import { } from "./tools/remote-passthrough.js"; import { resolveSessionId } from "./session-id.js"; import { resolveServerUrlFromEmail } from "./config-search.js"; +import { resolveDataDir } from "./data-dir.js"; +import { normalizeServerUrl } from "./server-url.js"; function readEnv(...keys: string[]): string | undefined { for (const key of keys) { @@ -62,11 +72,6 @@ function resolveServerUrl(): string | undefined { return loadServerUrl(); } -function normalizeServerUrl(raw: string): string { - const parsed = new URL(raw); - return `${parsed.origin}/mcp/gateway/proxy`; -} - const SETUP_REQUIRED_TEXT = `[SETUP_REQUIRED]\n\n` + `To connect, enter your work email (e.g. you@acme.com) and we'll find ` + @@ -92,8 +97,7 @@ const AUTH_REDIRECT_TO_SETUP_TEXT = "(no arguments) to sign in to Glean, then retry this tool."; function resolveLogPath(): string { - const base = process.env.PLUGIN_DATA_DIR || path.join(homedir(), ".glean"); - return path.join(base, "glean-server.log"); + return path.join(resolveDataDir(), "glean-server.log"); } const LOG_PATH = resolveLogPath(); @@ -264,7 +268,8 @@ const SETUP_TOOL: Tool = { "(3) fetch the remote tool catalog. Call with no arguments to advance " + "through the next missing stage. Call with email to look up and " + "(re)configure user's Glean instance. Call with reset=true to clear " + - "all configuration.", + "the current authentication, setup URL, and registered DCR client before " + + "starting a new setup flow.", inputSchema: { type: "object" as const, properties: { @@ -284,7 +289,9 @@ const SETUP_TOOL: Tool = { }, reset: { type: "boolean", - description: "Clear cached URL, credentials, and remote tool cache.", + description: + "Clear the cached URL, authentication, registered OAuth client, " + + "and remote tool cache. The next setup registers a new client.", }, }, required: [], @@ -521,6 +528,11 @@ async function advanceSetup(): Promise { return { content: [{ type: "text", text: SETUP_REQUIRED_TEXT }] }; } + const provider = getOAuthProvider(); + if (provider.clientServerUrl() !== serverUrl) { + provider.setAccountContext(provider.accountEmail(), serverUrl); + } + const conn = await connectWithSignIn(serverUrl); if (!conn.ok) return conn.result; const remoteClient = conn.client; @@ -730,12 +742,15 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => { clientInfo: server.getClientVersion() ?? null, }); if (args.reset === true) { + const hadClient = !!loadCredentials()?.clientInfo; clearServerUrl(); clearCredentials(); clearRemoteTools(); oauthProvider = undefined; cachedRemoteTools = []; - logLine("setup.reset"); + logLine("setup.reset", { + clearedClient: hadClient, + }); // Fire-and-forget — tools list is shorter without the dynamic // surface; the host should re-fetch on its next idle cycle. server.sendToolListChanged().catch(() => { @@ -746,8 +761,9 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => { { type: "text", text: - "Glean configuration has been reset. Call setup again with " + - "your email to reconfigure.", + "Glean authentication has been reset, including the registered " + + "OAuth client. Call setup again with your email to register a " + + "new client and sign in.", }, ], }; @@ -795,6 +811,20 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => { }; } + const previousUrl = loadServerUrl(); + const stored = loadCredentials(); + const requestedEmail = normalizeAccountEmail(email); + const urlChanged = previousUrl !== normalized; + const reusableClient = + !!stored?.clientInfo && stored.clientServerUrl === normalized; + // A new email on the same server is an account switch, not a new + // instance: clear only the grant and retain the server-scoped DCR + // client. This lets users change accounts without adding a client. + const accountChanged = + !!requestedEmail && + !!stored?.tokens && + stored.accountEmail !== requestedEmail; + try { saveServerUrl(normalized); } catch (err) { @@ -807,14 +837,33 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => { }; } - // New instance — clear stale auth state. The on-disk remote-tool - // cache for the previous URL is left intact (so switching back is - // instant); we just rehydrate from whatever cache exists for the - // newly configured URL — empty for a first-time server. - clearCredentials(); - oauthProvider = undefined; + // A DCR client is scoped to its server. Reuse a retained client after + // reset only when its recorded server matches; otherwise remove it. + if (urlChanged && !reusableClient) { + clearCredentials(); + oauthProvider = undefined; + } + + const provider = getOAuthProvider(); + if (accountChanged) { + // Email is an account-switch request. Clear only the grant and keep + // the server's DCR client, so switching users does not create a new + // authorized-app entry. + provider.resetAuthentication(requestedEmail, normalized); + } else { + provider.setAccountContext( + requestedEmail ?? provider.accountEmail(), + normalized, + ); + } + cachedRemoteTools = loadRemoteTools(normalized); - logLine("setup.configured", { serverUrl: normalized }); + logLine("setup.configured", { + serverUrl: normalized, + urlChanged, + reusableClient, + accountChanged, + }); // Fall through to advanceSetup, which will now find URL ✓ and try // to drive auth + tool fetch in the same call. } diff --git a/src/remote-client.ts b/src/remote-client.ts index d825947..d58c5df 100644 --- a/src/remote-client.ts +++ b/src/remote-client.ts @@ -111,6 +111,14 @@ export class AuthRequiredError extends Error { } let pendingTransport: StreamableHTTPClientTransport | undefined; +// The provider API is synchronous, so two connect calls in one MCP process can +// both observe an empty client before the SDK's async DCR request completes. +// Serialize that first registration per provider in addition to the OS lock +// used by token-store for sibling processes. +const pendingRegistrations = new WeakMap< + GleanOAuthClientProvider, + Promise +>(); function buildTransport( serverUrl: string, @@ -169,20 +177,42 @@ export async function createRemoteClient( } catch (err) { const msg = err instanceof Error ? err.message : String(err); console.error(`[auth] Code exchange failed: ${msg} — discarding stale auth state`); - authProvider.clearPendingAuth(); pendingTransport = undefined; - await authProvider.invalidateCredentials("all"); + // Keep the registration for code/verifier failures. An explicit + // invalid_client response escalates immediately; generic repeated + // failures use the shared two-attempt recovery budget. + if (!authProvider.abandonPendingSignIn(isInvalidClientError(err))) { + await authProvider.invalidateCredentials("all"); + } return createRemoteClient(serverUrl, opts, chatSessionId); } } - // DCR recovery: we previously issued an authorize URL but never received - // tokens. The URL was likely rejected by the server (most commonly: the - // cached DCR client was deleted server-side). Force a fresh DCR so the next - // URL we generate uses a valid, server-known client_id. + // Unfinished sign-in: reuse the existing registration first; fresh DCR is + // the escalation path. if (authProvider?.needsFreshClient()) { - console.error("[auth] Previous auth URL didn't complete — forcing fresh DCR"); - await authProvider.invalidateCredentials("all"); + if (authProvider.abandonPendingSignIn()) { + console.error( + "[auth] Previous sign-in didn't complete — retrying with the existing client", + ); + } else { + console.error( + "[auth] Sign-in failed twice with this client — forcing fresh DCR", + ); + await authProvider.invalidateCredentials("all"); + } + } + + let registrationNeeded = false; + if (authProvider?.clientInformation) { + registrationNeeded = !authProvider.clientInformation(); + if (registrationNeeded) { + const pending = pendingRegistrations.get(authProvider); + if (pending) { + await pending; + registrationNeeded = !authProvider.clientInformation(); + } + } } const client = new Client( @@ -194,10 +224,25 @@ export async function createRemoteClient( const accessTokenAtConnect = authProvider?.tokens()?.access_token; const transport = buildTransport(serverUrl, opts, chatSessionId); + let trackedRegistration: Promise | undefined; + let connectPromise: Promise; + if (registrationNeeded && authProvider) { + connectPromise = client.connect(transport); + trackedRegistration = connectPromise.then( + () => undefined, + () => undefined, + ); + pendingRegistrations.set(authProvider, trackedRegistration); + } else { + connectPromise = client.connect(transport); + } try { - await client.connect(transport); + await connectPromise; } catch (error) { + // If registration failed before saveClientInformation() ran, do not leave + // the cross-process registration lock behind until stale-lock expiry. + authProvider?.releaseClientRegistrationLock?.(); if (error instanceof UnauthorizedError && authProvider) { const refreshedAccessToken = authProvider.tokens()?.access_token; if ( @@ -230,11 +275,24 @@ export async function createRemoteClient( return createRemoteClient(serverUrl, opts, chatSessionId, true); } throw error; + } finally { + if ( + trackedRegistration && + authProvider && + pendingRegistrations.get(authProvider) === trackedRegistration + ) { + pendingRegistrations.delete(authProvider); + } } return client; } +function isInvalidClientError(error: unknown): boolean { + const msg = error instanceof Error ? error.message : String(error); + return /invalid[_ -]?client|unknown client|client authentication failed/i.test(msg); +} + // Match broadly; the caller's disk re-check gates the actual retry. function isLikelyRefreshFailure(error: unknown): boolean { const msg = error instanceof Error ? error.message : String(error); diff --git a/src/remote-tools-cache-store.ts b/src/remote-tools-cache-store.ts index fa2900b..e3ad5cc 100644 --- a/src/remote-tools-cache-store.ts +++ b/src/remote-tools-cache-store.ts @@ -1,14 +1,18 @@ import fs from "node:fs"; import path from "node:path"; -import { homedir } from "node:os"; import type { Tool } from "@modelcontextprotocol/sdk/types.js"; +import { + ensureDataDir, + migrateLegacyData, + resolveDataDir, +} from "./data-dir.js"; const CACHE_FILENAME = "remote-tools-cache.json"; const DIR_MODE = 0o700; const FILE_MODE = 0o600; function resolveCacheDir(): string { - return process.env.PLUGIN_DATA_DIR || path.join(homedir(), ".glean"); + return resolveDataDir(); } function cacheFile(): string { @@ -23,6 +27,7 @@ interface CacheEntry { type Store = Record; function readStore(): Store { + migrateLegacyData(); try { const raw = fs.readFileSync(cacheFile(), "utf-8"); const data = JSON.parse(raw); @@ -37,8 +42,7 @@ function readStore(): Store { function writeStore(store: Store): void { const filePath = cacheFile(); - const dir = path.dirname(filePath); - fs.mkdirSync(dir, { recursive: true, mode: DIR_MODE }); + const dir = ensureDataDir(); fs.chmodSync(dir, DIR_MODE); fs.writeFileSync(filePath, JSON.stringify(store, null, 2), { encoding: "utf-8", @@ -68,6 +72,7 @@ export function saveRemoteTools(serverUrl: string, tools: Tool[]): void { } export function clearRemoteTools(serverUrl?: string): void { + migrateLegacyData(); try { if (!serverUrl) { fs.rmSync(cacheFile(), { force: true }); diff --git a/src/server-url.ts b/src/server-url.ts new file mode 100644 index 0000000..86c72ee --- /dev/null +++ b/src/server-url.ts @@ -0,0 +1,22 @@ +const MCP_GATEWAY_PATH = "/mcp/gateway/proxy"; + +/** + * Normalize either a normal QE origin or a path-prefixed experimental QE URL + * to the MCP gateway endpoint. + * + * Examples: + * https://acme-be.glean.com + * -> https://acme-be.glean.com/mcp/gateway/proxy + * https://scio-prod-be.glean.com/qe-glean-exp-101 + * -> https://scio-prod-be.glean.com/qe-glean-exp-101/mcp/gateway/proxy + */ +export function normalizeServerUrl(raw: string): string { + const parsed = new URL(raw); + const pathname = parsed.pathname.replace(/\/+$/, ""); + const prefix = pathname.endsWith(MCP_GATEWAY_PATH) + ? pathname.slice(0, -MCP_GATEWAY_PATH.length) + : pathname === "/" + ? "" + : pathname; + return `${parsed.origin}${prefix}${MCP_GATEWAY_PATH}${parsed.search}`; +} diff --git a/src/token-store.ts b/src/token-store.ts index 535a07d..476bc77 100644 --- a/src/token-store.ts +++ b/src/token-store.ts @@ -1,38 +1,64 @@ import fs from "node:fs"; import path from "node:path"; -import { homedir } from "node:os"; +import { + acquireDataFileLockSync, + ensureDataDir, + type DataLockHandle, + migrateLegacyData, + releaseDataFileLock, + resolveDataDir, +} from "./data-dir.js"; const CREDENTIALS_FILENAME = "mcp-credentials.json"; const DIR_MODE = 0o700; const FILE_MODE = 0o600; +const CLIENT_REGISTRATION_LOCK = "mcp-client-registration"; -function resolveCredentialsDir(): string { - return process.env.PLUGIN_DATA_DIR || path.join(homedir(), ".glean"); +export interface CredentialMetadata { + /** Work account used for the last successful/initiated sign-in. */ + accountEmail?: string | null; + /** OAuth clients are server-specific. */ + clientServerUrl?: string | null; + /** Shared recovery budget across sibling plugin processes. */ + abandonedSignIns?: number | null; + /** Local monotonic-ish timestamp for conflict-free token merging. */ + tokenUpdatedAt?: number | null; } -function credentialsFile(): string { - return path.join(resolveCredentialsDir(), CREDENTIALS_FILENAME); -} - -interface StoredCredentials { +export interface StoredCredentials extends CredentialMetadata { tokens?: unknown; clientInfo?: unknown; } -export function loadCredentials(): StoredCredentials | undefined { +export interface SaveCredentialsOptions { + forceTokenUpdate?: boolean; + forceClientUpdate?: boolean; +} + +function credentialsFile(): string { + return path.join(resolveDataDir(), CREDENTIALS_FILENAME); +} + +function readCredentialsFile(filePath: string): StoredCredentials | undefined { try { - const raw = fs.readFileSync(credentialsFile(), "utf-8"); + const raw = fs.readFileSync(filePath, "utf-8"); return JSON.parse(raw) as StoredCredentials; } catch { return undefined; } } +export function loadCredentials(): StoredCredentials | undefined { + migrateLegacyData(); + return readCredentialsFile(credentialsFile()); +} + /** * mtime of the credentials file (epoch ms), or undefined if unreadable. * Cheap change probe: a single stat, no read + parse. */ export function credentialsMtimeMs(): number | undefined { + migrateLegacyData(); try { return fs.statSync(credentialsFile()).mtimeMs; } catch { @@ -40,13 +66,71 @@ export function credentialsMtimeMs(): number | undefined { } } -export function saveCredentials(tokens: unknown, clientInfo: unknown): void { +/** + * Acquire the registration lock before returning undefined from + * clientInformation(). The MCP SDK interprets undefined as permission to call + * /oauth/register, so the lock must span that asynchronous SDK operation and + * is released by saveClientInformation() or the connection error path. + */ +export function acquireClientRegistrationLock(): DataLockHandle | undefined { + return acquireDataFileLockSync(CLIENT_REGISTRATION_LOCK, { + waitMs: 30_000, + staleMs: 120_000, + }); +} + +export function releaseClientRegistrationLock(lock: DataLockHandle | undefined): void { + releaseDataFileLock(lock); +} + +export function saveCredentials( + tokens: unknown, + clientInfo: unknown, + metadata: CredentialMetadata = {}, + options: SaveCredentialsOptions = {}, +): void { try { + migrateLegacyData(); const filePath = credentialsFile(); - const dir = path.dirname(filePath); - fs.mkdirSync(dir, { recursive: true, mode: DIR_MODE }); - fs.chmodSync(dir, DIR_MODE); - const data: StoredCredentials = { tokens, clientInfo }; + const dir = ensureDataDir(); + const existing = readCredentialsFile(filePath); + const incomingTokenTime = metadata.tokenUpdatedAt ?? undefined; + const existingTokenTime = existing?.tokenUpdatedAt ?? undefined; + const existingTokenIsNewer = + !options.forceTokenUpdate && + existing?.tokens !== undefined && + (tokens === undefined || + (existingTokenTime !== undefined && + (incomingTokenTime === undefined || + existingTokenTime > incomingTokenTime))); + const effectiveTokens = existingTokenIsNewer ? existing?.tokens : tokens; + const effectiveTokenTime = existingTokenIsNewer + ? existingTokenTime + : metadata.tokenUpdatedAt !== undefined + ? metadata.tokenUpdatedAt + : existing?.tokenUpdatedAt; + const effectiveClientInfo = + !options.forceClientUpdate && clientInfo === undefined + ? existing?.clientInfo + : clientInfo; + const data: StoredCredentials = { + tokens: effectiveTokens, + clientInfo: effectiveClientInfo, + // Omitted metadata means preserve it; null explicitly clears it. + accountEmail: + metadata.accountEmail !== undefined + ? metadata.accountEmail + : existing?.accountEmail, + clientServerUrl: + metadata.clientServerUrl !== undefined + ? metadata.clientServerUrl + : existing?.clientServerUrl, + abandonedSignIns: + metadata.abandonedSignIns !== undefined + ? metadata.abandonedSignIns + : existing?.abandonedSignIns, + tokenUpdatedAt: effectiveTokenTime, + }; // Temp-file + rename: concurrent readers never see a half-written store. const tmpPath = `${filePath}.${process.pid}.tmp`; fs.writeFileSync(tmpPath, JSON.stringify(data, null, 2), { @@ -54,6 +138,8 @@ export function saveCredentials(tokens: unknown, clientInfo: unknown): void { mode: FILE_MODE, }); fs.renameSync(tmpPath, filePath); + fs.chmodSync(dir, DIR_MODE); + fs.chmodSync(filePath, FILE_MODE); } catch (err) { const msg = err instanceof Error ? err.message : String(err); console.error(`[auth] Failed to persist credentials: ${msg}`); @@ -62,6 +148,7 @@ export function saveCredentials(tokens: unknown, clientInfo: unknown): void { export function clearCredentials(): void { try { + migrateLegacyData(); fs.rmSync(credentialsFile(), { force: true }); } catch (err) { const msg = err instanceof Error ? err.message : String(err); diff --git a/src/url-config-store.ts b/src/url-config-store.ts index df46d7e..6a7d9e6 100644 --- a/src/url-config-store.ts +++ b/src/url-config-store.ts @@ -1,13 +1,17 @@ import fs from "node:fs"; import path from "node:path"; -import { homedir } from "node:os"; +import { + ensureDataDir, + migrateLegacyData, + resolveDataDir, +} from "./data-dir.js"; const CONFIG_FILENAME = "mcp-server-url.json"; const DIR_MODE = 0o700; const FILE_MODE = 0o600; function resolveConfigDir(): string { - return process.env.PLUGIN_DATA_DIR || path.join(homedir(), ".glean"); + return resolveDataDir(); } function configFile(): string { @@ -19,6 +23,7 @@ interface StoredConfig { } export function loadServerUrl(): string | undefined { + migrateLegacyData(); try { const raw = fs.readFileSync(configFile(), "utf-8"); const data = JSON.parse(raw) as StoredConfig; @@ -30,9 +35,9 @@ export function loadServerUrl(): string | undefined { } export function saveServerUrl(url: string): void { + migrateLegacyData(); const filePath = configFile(); - const dir = path.dirname(filePath); - fs.mkdirSync(dir, { recursive: true, mode: DIR_MODE }); + const dir = ensureDataDir(); fs.chmodSync(dir, DIR_MODE); const data: StoredConfig = { serverUrl: url }; fs.writeFileSync(filePath, JSON.stringify(data, null, 2), { @@ -43,6 +48,7 @@ export function saveServerUrl(url: string): void { } export function clearServerUrl(): void { + migrateLegacyData(); try { fs.rmSync(configFile(), { force: true }); } catch { diff --git a/tests/auth-provider.test.ts b/tests/auth-provider.test.ts index 3e4e032..a3863bd 100644 --- a/tests/auth-provider.test.ts +++ b/tests/auth-provider.test.ts @@ -28,6 +28,8 @@ describe("GleanOAuthClientProvider", () => { beforeEach(() => { delete process.env.PLUGIN_DATA_DIR; + delete process.env.CLAUDE_PLUGIN_DATA; + delete process.env.GLEAN_AUTH_DATA_DIR; // Skip the rotation grace window by default so invalidation tests don't // wait out the real 2s poll; the grace test overrides this explicitly. process.env.GLEAN_ROTATION_GRACE_MS = "0"; @@ -215,6 +217,82 @@ describe("GleanOAuthClientProvider", () => { expect(provider.tokens()).toBeUndefined(); }); + // --- Client reuse: an abandoned sign-in must not burn the DCR client. + // Every registration permanently adds a client server-side, so the + // existing one is retried first and a fresh DCR is the escalation path. --- + + it("clientInformation() adopts a sibling's registration from disk", () => { + // Constructed with no credentials — this process would otherwise register. + const provider = new GleanOAuthClientProvider(); + expect(provider.clientInformation()).toBeUndefined(); + + // Sibling process wins the registration race and persists its client. + writeCredFileNewer(undefined, { client_id: "cid_sibling" }); + + expect(provider.clientInformation()).toEqual({ client_id: "cid_sibling" }); + }); + + it("abandonPendingSignIn keeps the registered client and clears the pending flow", async () => { + const provider = new GleanOAuthClientProvider(); + provider.saveClientInformation({ client_id: "cid" } as any); + provider.saveCodeVerifier("v1"); + await provider.redirectToAuthorization( + new URL("https://example.com/oauth/authorize?state=s1"), + ); + expect(provider.needsFreshClient()).toBe(true); + + expect(provider.abandonPendingSignIn()).toBe(true); + + expect(provider.clientInformation()).toEqual({ client_id: "cid" }); + expect(provider.codeVerifier()).toBe(""); + expect(provider.authorizationUrl).toBeUndefined(); + expect(provider.needsFreshClient()).toBe(false); + // Registration untouched on disk — nothing was wiped. + const raw = JSON.parse(fs.readFileSync(credFile, "utf-8")); + expect(raw.clientInfo.client_id).toBe("cid"); + }); + + it("abandonPendingSignIn exhausts after two consecutive abandonments", () => { + const provider = new GleanOAuthClientProvider(); + expect(provider.abandonPendingSignIn()).toBe(true); + expect(provider.abandonPendingSignIn()).toBe(false); + }); + + it("a completed sign-in resets the abandonment budget", () => { + const provider = new GleanOAuthClientProvider(); + expect(provider.abandonPendingSignIn()).toBe(true); + provider.saveTokens({ access_token: "tok" } as any); + // Fresh budget: the next abandonment retries the client again. + expect(provider.abandonPendingSignIn()).toBe(true); + }); + + it("invalidateCredentials('all') resets the budget for the next registration", async () => { + const provider = new GleanOAuthClientProvider(); + expect(provider.abandonPendingSignIn()).toBe(true); + expect(provider.abandonPendingSignIn()).toBe(false); + await provider.invalidateCredentials("all"); + // A freshly registered client gets a fresh retry budget. + expect(provider.abandonPendingSignIn()).toBe(true); + }); + + it("resetAuthentication keeps the client for account switching", () => { + const provider = new GleanOAuthClientProvider(); + provider.saveTokens({ access_token: "tok", refresh_token: "refresh" } as any); + provider.saveClientInformation({ client_id: "cid" } as any); + + provider.resetAuthentication( + "new-account@example.com", + "https://example.com/mcp/gateway/proxy", + ); + + expect(provider.tokens()).toBeUndefined(); + expect(provider.clientInformation()).toEqual({ client_id: "cid" }); + expect(provider.accountEmail()).toBe("new-account@example.com"); + const raw = JSON.parse(fs.readFileSync(credFile, "utf-8")); + expect(raw.tokens).toBeUndefined(); + expect(raw.clientInfo.client_id).toBe("cid"); + }); + it("saveClientInformation persists to disk", () => { const provider = new GleanOAuthClientProvider(); const info = { client_id: "cid", client_secret: "sec" } as any; @@ -391,4 +469,43 @@ describe("GleanOAuthClientProvider", () => { await provider.invalidateCredentials("client"); expect(observed).toEqual([]); }); + + it("switches accounts without creating a new DCR client", () => { + const provider = new GleanOAuthClientProvider(); + provider.saveClientInformation({ client_id: "cid" } as any); + provider.setAccountContext( + "Alice@Example.com", + "https://acme-be.glean.com/mcp/gateway/proxy", + ); + provider.saveTokens({ access_token: "alice-token" } as any); + + provider.resetAuthentication( + "Bob@Example.com", + "https://acme-be.glean.com/mcp/gateway/proxy", + ); + + expect(provider.tokens()).toBeUndefined(); + expect(provider.clientInformation()).toEqual({ client_id: "cid" }); + expect(provider.accountEmail()).toBe("bob@example.com"); + const raw = JSON.parse(fs.readFileSync(credFile, "utf-8")); + expect(raw.clientInfo.client_id).toBe("cid"); + expect(raw.tokens).toBeUndefined(); + expect(raw.accountEmail).toBe("bob@example.com"); + }); + + it("shares the abandoned-sign-in budget across provider instances", () => { + const first = new GleanOAuthClientProvider(); + first.saveClientInformation({ client_id: "cid" } as any); + expect(first.abandonPendingSignIn()).toBe(true); + + const second = new GleanOAuthClientProvider(); + expect(second.abandonPendingSignIn()).toBe(false); + }); + + it("immediately escalates when the server explicitly rejects the client", () => { + const provider = new GleanOAuthClientProvider(); + expect(provider.abandonPendingSignIn(true)).toBe(false); + const raw = JSON.parse(fs.readFileSync(credFile, "utf-8")); + expect(raw.abandonedSignIns).toBe(2); + }); }); diff --git a/tests/remote-client-auth-retry.test.ts b/tests/remote-client-auth-retry.test.ts index f730cc7..7cff58b 100644 --- a/tests/remote-client-auth-retry.test.ts +++ b/tests/remote-client-auth-retry.test.ts @@ -90,6 +90,105 @@ describe("createRemoteClient sibling-refresh retry", () => { }); }); +describe("createRemoteClient abandoned sign-in client reuse", () => { + beforeEach(() => { + connectMock.mockReset(); + }); + + function makeAbandonedProvider(budgetLeft: boolean) { + return { + tokens: () => ({ access_token: "T0" }), + authorizationUrl: undefined, + pendingAuthCode: undefined, + needsFreshClient: () => true, + abandonPendingSignIn: vi.fn(() => budgetLeft), + invalidateCredentials: vi.fn(), + } as any; + } + + it("reuses the existing client on the first abandoned sign-in", async () => { + connectMock.mockResolvedValueOnce(undefined); + const provider = makeAbandonedProvider(true); + + await createRemoteClient( + "https://acme-be.glean.com/mcp/gateway/proxy", + { authProvider: provider }, + "sess-3", + ); + + expect(provider.abandonPendingSignIn).toHaveBeenCalledTimes(1); + // The registration survives — no wipe, no fresh DCR. + expect(provider.invalidateCredentials).not.toHaveBeenCalled(); + }); + + it("falls back to a fresh DCR once the retry budget is exhausted", async () => { + connectMock.mockResolvedValueOnce(undefined); + const provider = makeAbandonedProvider(false); + + await createRemoteClient( + "https://acme-be.glean.com/mcp/gateway/proxy", + { authProvider: provider }, + "sess-4", + ); + + expect(provider.invalidateCredentials).toHaveBeenCalledWith("all"); + }); +}); + +describe("createRemoteClient same-process registration gate", () => { + beforeEach(() => { + connectMock.mockReset(); + }); + + it("allows only one concurrent first-time DCR registration", async () => { + let release!: () => void; + const gate = new Promise((resolve) => { + release = resolve; + }); + let registrationCount = 0; + const provider: any = { + clientInfo: undefined, + tokens: () => ({ access_token: "T0" }), + authorizationUrl: undefined, + pendingAuthCode: undefined, + needsFreshClient: () => false, + clientInformation() { + return this.clientInfo; + }, + saveClientInformation(info: unknown) { + this.clientInfo = info; + registrationCount += 1; + }, + }; + + connectMock.mockImplementation(async () => { + if (registrationCount === 0) { + await gate; + provider.saveClientInformation({ client_id: "cid" }); + } + }); + + const first = createRemoteClient( + "https://acme-be.glean.com/mcp/gateway/proxy", + { authProvider: provider }, + "same-process-1", + ); + // Let the first call enter its async connect and publish the pending gate. + await Promise.resolve(); + const second = createRemoteClient( + "https://acme-be.glean.com/mcp/gateway/proxy", + { authProvider: provider }, + "same-process-2", + ); + await Promise.resolve(); + release(); + + await Promise.all([first, second]); + expect(registrationCount).toBe(1); + expect(connectMock).toHaveBeenCalledTimes(2); + }); +}); + describe("createRemoteClient refresh-collision retry", () => { beforeEach(() => { connectMock.mockReset(); diff --git a/tests/remote-tools-cache-store.test.ts b/tests/remote-tools-cache-store.test.ts index 0c0987f..4638400 100644 --- a/tests/remote-tools-cache-store.test.ts +++ b/tests/remote-tools-cache-store.test.ts @@ -8,7 +8,7 @@ const tmpDir = fs.mkdtempSync( path.join(os.tmpdir(), "remote-tools-cache-store-test-"), ); -vi.stubEnv("PLUGIN_DATA_DIR", tmpDir); +vi.stubEnv("GLEAN_AUTH_DATA_DIR", tmpDir); const { loadRemoteTools, saveRemoteTools, clearRemoteTools } = await import( "../src/remote-tools-cache-store.js" diff --git a/tests/server-url.test.ts b/tests/server-url.test.ts new file mode 100644 index 0000000..2219c20 --- /dev/null +++ b/tests/server-url.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, it } from "vitest"; +import { normalizeServerUrl } from "../src/server-url.js"; + +describe("normalizeServerUrl", () => { + it("adds the MCP gateway path to a normal QE origin", () => { + expect(normalizeServerUrl("https://acme-be.glean.com")).toBe( + "https://acme-be.glean.com/mcp/gateway/proxy", + ); + }); + + it("preserves an experimental QE path prefix", () => { + expect( + normalizeServerUrl("https://scio-prod-be.glean.com/qe-glean-exp-101"), + ).toBe( + "https://scio-prod-be.glean.com/qe-glean-exp-101/mcp/gateway/proxy", + ); + }); + + it("does not duplicate the gateway path", () => { + expect( + normalizeServerUrl( + "https://scio-prod-be.glean.com/qe-glean-exp-101/mcp/gateway/proxy/", + ), + ).toBe( + "https://scio-prod-be.glean.com/qe-glean-exp-101/mcp/gateway/proxy", + ); + }); + + it("preserves query parameters such as sc overrides", () => { + expect( + normalizeServerUrl( + "https://scio-prod-be.glean.com/qe-glean-exp-101?sc=db.debug_mode%3D1", + ), + ).toBe( + "https://scio-prod-be.glean.com/qe-glean-exp-101/mcp/gateway/proxy?sc=db.debug_mode%3D1", + ); + }); +}); diff --git a/tests/token-store.test.ts b/tests/token-store.test.ts index 88685ad..1f9f47c 100644 --- a/tests/token-store.test.ts +++ b/tests/token-store.test.ts @@ -10,19 +10,34 @@ vi.mock("node:os", async () => { return { ...actual, homedir: () => tmpDir }; }); -const { clearCredentials, credentialsMtimeMs, loadCredentials, saveCredentials } = - await import("../src/token-store.js"); +const { + acquireClientRegistrationLock, + clearCredentials, + credentialsMtimeMs, + loadCredentials, + releaseClientRegistrationLock, + saveCredentials, +} = await import("../src/token-store.js"); +const { acquireDataFileLockSync, releaseDataFileLock } = await import( + "../src/data-dir.js" +); describe("token-store", () => { const gleanDir = path.join(tmpDir, ".glean"); const credFile = path.join(gleanDir, "mcp-credentials.json"); + const legacyDir = path.join(tmpDir, "managed-plugin-data"); beforeEach(() => { + delete process.env.PLUGIN_DATA_DIR; + delete process.env.CLAUDE_PLUGIN_DATA; + delete process.env.GLEAN_AUTH_DATA_DIR; fs.rmSync(gleanDir, { recursive: true, force: true }); + fs.rmSync(legacyDir, { recursive: true, force: true }); }); afterEach(() => { fs.rmSync(gleanDir, { recursive: true, force: true }); + fs.rmSync(legacyDir, { recursive: true, force: true }); }); it("returns undefined when credentials file does not exist", () => { @@ -106,4 +121,61 @@ describe("token-store", () => { fs.utimesSync(credFile, future, future); expect(credentialsMtimeMs()!).toBeGreaterThan(first); }); + + it("migrates a host-managed credentials store into the canonical store", () => { + process.env.PLUGIN_DATA_DIR = legacyDir; + fs.mkdirSync(legacyDir, { recursive: true }); + fs.writeFileSync( + path.join(legacyDir, "mcp-credentials.json"), + JSON.stringify({ + tokens: { access_token: "legacy-token" }, + clientInfo: { client_id: "legacy-client" }, + }), + ); + + expect(loadCredentials()).toEqual({ + tokens: { access_token: "legacy-token" }, + clientInfo: { client_id: "legacy-client" }, + }); + expect(fs.existsSync(credFile)).toBe(true); + }); + + it("serializes cross-process lock acquisition", () => { + const first = acquireDataFileLockSync("lock-test", { waitMs: 0 }); + expect(first).toBeTruthy(); + const second = acquireDataFileLockSync("lock-test", { waitMs: 0 }); + expect(second).toBeUndefined(); + releaseDataFileLock(first); + const third = acquireDataFileLockSync("lock-test", { waitMs: 0 }); + expect(third).toBeTruthy(); + releaseDataFileLock(third); + }); + + it("holds a client registration lock until registration completes", () => { + const first = acquireClientRegistrationLock(); + expect(first).toBeTruthy(); + const second = acquireDataFileLockSync("mcp-client-registration", { waitMs: 0 }); + expect(second).toBeUndefined(); + releaseClientRegistrationLock(first); + }); + + it("does not let a metadata write clobber a newer token grant", () => { + saveCredentials( + { access_token: "new-token", refresh_token: "new-refresh" }, + { client_id: "cid" }, + { tokenUpdatedAt: 200 }, + ); + saveCredentials( + undefined, + undefined, + { accountEmail: "user@example.com", tokenUpdatedAt: 100 }, + ); + + expect(loadCredentials()).toMatchObject({ + tokens: { access_token: "new-token", refresh_token: "new-refresh" }, + clientInfo: { client_id: "cid" }, + accountEmail: "user@example.com", + tokenUpdatedAt: 200, + }); + }); }); diff --git a/tests/url-config-store.test.ts b/tests/url-config-store.test.ts index b7c9a5f..a4856af 100644 --- a/tests/url-config-store.test.ts +++ b/tests/url-config-store.test.ts @@ -5,7 +5,7 @@ import os from "node:os"; const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "url-config-store-test-")); -vi.stubEnv("PLUGIN_DATA_DIR", tmpDir); +vi.stubEnv("GLEAN_AUTH_DATA_DIR", tmpDir); const { loadServerUrl, saveServerUrl, clearServerUrl } = await import( "../src/url-config-store.js"