From 7346ef0a7a7ed9ec9fd3c796a99e19e312dacf8d Mon Sep 17 00:00:00 2001 From: myro-june <113972203+myro-june@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:18:13 +0900 Subject: [PATCH 1/4] fix(auth): share OAuth refreshes across server processes via a lock file Every MCP client session starts its own server process, and all of them read one credentials.json. Each process read the file once at startup and refreshed with the refresh token it held in memory. Linear rotates the refresh token on every refresh, so once one process refreshed, the others sent a revoked token and failed with "Failed to refresh the stored Linear access token (... HTTP 400)" until the client reconnected. Refreshes now run under a cross-process lock (credentials.json.lock, created with O_EXCL; a lock older than 60s is reclaimed). Under the lock the file is read again: a token another process already refreshed is reused without a request, and an expired one is refreshed with the newest refresh token from the file. If Linear still rejects the refresh and the file now holds a different refresh token (a server build that does not take the lock rotated it meanwhile), that token is adopted or retried exactly once. `auth login` and `auth logout` also write or delete under the lock, and a refresh no longer recreates credentials that were logged out. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/auth-cli.test.ts | 16 ++ src/__tests__/auth-credential-store.test.ts | 66 +++++ src/__tests__/auth-managed-auth.test.ts | 280 ++++++++++++++++++++ src/auth/cli.ts | 31 ++- src/auth/credential-store.ts | 143 ++++++++++ src/auth/managed-auth.ts | 105 ++++++-- 6 files changed, 606 insertions(+), 35 deletions(-) diff --git a/src/__tests__/auth-cli.test.ts b/src/__tests__/auth-cli.test.ts index 92da909..db08eff 100644 --- a/src/__tests__/auth-cli.test.ts +++ b/src/__tests__/auth-cli.test.ts @@ -250,6 +250,22 @@ describe('auth CLI', () => { expect(fs.existsSync(getCredentialsPath())).toBe(false); }); + it('waits for a running token refresh to finish before deleting the credentials', async () => { + writeStoredCredentials(storedCredentials); + fetchSpy.mockResolvedValueOnce(jsonResponse(200, {})); + const lockPath = path.join(tempDir, 'credentials.json.lock'); + fs.writeFileSync(lockPath, 'refreshing-process'); + + const logout = runAuthCli(['logout'], { print }); + await new Promise((resolve) => setTimeout(resolve, 250)); + const presentWhileLocked = fs.existsSync(getCredentialsPath()); + fs.unlinkSync(lockPath); + + await expect(logout).resolves.toBe(0); + expect(presentWhileLocked).toBe(true); + expect(fs.existsSync(getCredentialsPath())).toBe(false); + }); + it('still deletes local credentials when revocation fails offline', async () => { writeStoredCredentials(storedCredentials); fetchSpy.mockRejectedValueOnce(new TypeError('fetch failed')); diff --git a/src/__tests__/auth-credential-store.test.ts b/src/__tests__/auth-credential-store.test.ts index ee85d08..eb18bc6 100644 --- a/src/__tests__/auth-credential-store.test.ts +++ b/src/__tests__/auth-credential-store.test.ts @@ -5,8 +5,10 @@ import path from 'node:path'; import { deleteStoredCredentials, getCredentialsPath, + getCredentialsLockPath, readStoredCredentials, writeStoredCredentials, + withCredentialsLock, type StoredCredentials, } from '../auth/credential-store.js'; @@ -122,3 +124,67 @@ describe('credential store', () => { expect(deleteStoredCredentials()).toBe(false); }); }); + +describe('credentials lock', () => { + const originalEnv = process.env; + let tempDir: string; + + beforeEach(() => { + process.env = { ...originalEnv }; + tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mcp-linear-lock-')); + process.env.MCP_LINEAR_CONFIG_DIR = tempDir; + }); + + afterEach(() => { + process.env = originalEnv; + fs.rmSync(tempDir, { recursive: true, force: true }); + }); + + it('runs the callback while holding the lock file and removes it afterwards', async () => { + let heldDuringCallback = false; + await withCredentialsLock(async () => { + heldDuringCallback = fs.existsSync(getCredentialsLockPath()); + }); + + expect(heldDuringCallback).toBe(true); + expect(fs.existsSync(getCredentialsLockPath())).toBe(false); + }); + + it('leaves a lock alone that another process took over meanwhile', async () => { + await withCredentialsLock(async () => { + // Our lock was reclaimed as stale and another process now holds it. + fs.writeFileSync(getCredentialsLockPath(), 'other-process-owner'); + }); + + expect(fs.readFileSync(getCredentialsLockPath(), 'utf8')).toBe('other-process-owner'); + }); + + it('times out with a clear message while another process keeps a fresh lock', async () => { + fs.writeFileSync(getCredentialsLockPath(), 'other-process-owner'); + const callback = jest.fn(async () => undefined); + + await expect( + withCredentialsLock(callback, { retryMs: 5, timeoutMs: 50 }), + ).rejects.toThrow(/Timed out waiting for another mcp-linear process/); + expect(callback).not.toHaveBeenCalled(); + expect(fs.readFileSync(getCredentialsLockPath(), 'utf8')).toBe('other-process-owner'); + }); + + it('reclaims a stale lock and cleans up the reclaimed file', async () => { + fs.writeFileSync(getCredentialsLockPath(), 'dead-process-owner'); + const longAgo = new Date(Date.now() - 10 * 60_000); + fs.utimesSync(getCredentialsLockPath(), longAgo, longAgo); + + await withCredentialsLock(async () => undefined, { retryMs: 5 }); + + expect(fs.readdirSync(tempDir)).toEqual([]); + }); + + it('waits instead of spinning when the lock path is a dangling symlink', async () => { + fs.symlinkSync(path.join(tempDir, 'missing-target'), getCredentialsLockPath()); + + await expect( + withCredentialsLock(async () => undefined, { retryMs: 5, timeoutMs: 50 }), + ).rejects.toThrow(/Timed out/); + }); +}); diff --git a/src/__tests__/auth-managed-auth.test.ts b/src/__tests__/auth-managed-auth.test.ts index 5538cb2..2ea8e38 100644 --- a/src/__tests__/auth-managed-auth.test.ts +++ b/src/__tests__/auth-managed-auth.test.ts @@ -163,3 +163,283 @@ describe('stored credential auth', () => { expect(fetchSpy).not.toHaveBeenCalled(); }); }); + +/** + * Several MCP server processes (one per client session) share one credentials + * file. Each `createStoredCredentialAuth` instance below stands in for one + * process: it holds its own in-memory copy, exactly like a separate process. + */ +describe('stored credential auth shared across processes', () => { + const originalEnv = process.env; + let tempDir: string; + let fetchSpy: jest.SpyInstance; + let clock: number; + const now = () => clock; + + /** + * Fake Linear token endpoint with refresh token rotation: every successful + * refresh issues a new refresh token and invalidates the one that was sent. + */ + function fakeTokenEndpoint(initialRefreshToken: string) { + const server = { validRefreshToken: initialRefreshToken, issued: 0, sent: [] as string[] }; + fetchSpy.mockImplementation(async (_url: unknown, init?: RequestInit) => { + const sent = new URLSearchParams(String(init?.body)).get('refresh_token') ?? ''; + server.sent.push(sent); + if (sent !== server.validRefreshToken) { + return jsonResponse(400, { error: 'invalid_grant' }); + } + server.issued += 1; + server.validRefreshToken = `rotated-refresh-token-${server.issued}`; + return jsonResponse(200, { + access_token: `refreshed-access-token-${server.issued}`, + refresh_token: server.validRefreshToken, + token_type: 'Bearer', + expires_in: 3600, + scope: 'read,write', + }); + }); + return server; + } + + /** What another process (old or new code) leaves in the file after rotating. */ + function writeRotatedByOtherProcess( + accessToken: string, + refreshToken: string, + expiresAt: number, + ): void { + writeStoredCredentials({ + clientId: 'client-id-1', + clientSecret: 'client-secret-1', + accessToken, + refreshToken, + expiresAt, + scopes: ['read', 'write'], + }); + } + + const lockPath = () => path.join(tempDir, 'credentials.json.lock'); + + beforeEach(() => { + process.env = { ...originalEnv }; + tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mcp-linear-auth-shared-')); + process.env.MCP_LINEAR_CONFIG_DIR = tempDir; + fetchSpy = jest.spyOn(global, 'fetch'); + clock = NOW; + }); + + afterEach(() => { + jest.restoreAllMocks(); + process.env = originalEnv; + fs.rmSync(tempDir, { recursive: true, force: true }); + }); + + it('reuses the token another process already refreshed instead of sending a revoked refresh token', async () => { + seedCredentials({ expiresAt: NOW - 1_000 }); + const server = fakeTokenEndpoint('stored-refresh-token'); + + const processA = createStoredCredentialAuth({ now }); + const processB = createStoredCredentialAuth({ now }); + + await expect(processA!.getConfig()).resolves.toEqual({ + type: 'oauth', + token: 'refreshed-access-token-1', + }); + await expect(processB!.getConfig()).resolves.toEqual({ + type: 'oauth', + token: 'refreshed-access-token-1', + }); + + expect(server.sent).toEqual(['stored-refresh-token']); + expect(readStoredCredentials()?.refreshToken).toBe('rotated-refresh-token-1'); + }); + + it('sends one refresh request when two processes refresh at the same moment', async () => { + seedCredentials({ expiresAt: NOW - 1_000 }); + const server = fakeTokenEndpoint('stored-refresh-token'); + + const processA = createStoredCredentialAuth({ now, lockRetryMs: 5 }); + const processB = createStoredCredentialAuth({ now, lockRetryMs: 5 }); + + const [configA, configB] = await Promise.all([processA!.getConfig(), processB!.getConfig()]); + + expect(configA.token).toBe('refreshed-access-token-1'); + expect(configB.token).toBe('refreshed-access-token-1'); + expect(server.sent).toEqual(['stored-refresh-token']); + }); + + it('refreshes with the newest refresh token from the file when that token has expired too', async () => { + seedCredentials({ expiresAt: NOW - 1_000 }); + const server = fakeTokenEndpoint('stored-refresh-token'); + + const processA = createStoredCredentialAuth({ now }); + const processB = createStoredCredentialAuth({ now }); + + await processA!.getConfig(); + // Two hours later both processes see an expired access token; B's memory + // still holds the refresh token that A's rotation revoked. + clock = NOW + 2 * 3_600_000; + + await expect(processB!.getConfig()).resolves.toEqual({ + type: 'oauth', + token: 'refreshed-access-token-2', + }); + expect(server.sent).toEqual(['stored-refresh-token', 'rotated-refresh-token-1']); + expect(readStoredCredentials()?.refreshToken).toBe('rotated-refresh-token-2'); + + // A now picks up B's rotation from the file without another request. + await expect(processA!.getConfig()).resolves.toEqual({ + type: 'oauth', + token: 'refreshed-access-token-2', + }); + expect(server.sent).toHaveLength(2); + }); + + it('retries once with the rotated refresh token when a process that ignores the lock rotated it mid-request', async () => { + seedCredentials({ expiresAt: NOW - 1_000 }); + const server = { sent: [] as string[] }; + fetchSpy.mockImplementation(async (_url: unknown, init?: RequestInit) => { + const sent = new URLSearchParams(String(init?.body)).get('refresh_token') ?? ''; + server.sent.push(sent); + if (server.sent.length === 1) { + // An older server build (no lock) rotated the token while our request + // was in flight and wrote an already-expiring access token. + writeRotatedByOtherProcess('other-access-token', 'other-refresh-token', NOW - 500); + return jsonResponse(400, { error: 'invalid_grant' }); + } + if (sent !== 'other-refresh-token') { + return jsonResponse(400, { error: 'invalid_grant' }); + } + return jsonResponse(200, { + access_token: 'retried-access-token', + refresh_token: 'retried-refresh-token', + token_type: 'Bearer', + expires_in: 3600, + scope: 'read,write', + }); + }); + + const auth = createStoredCredentialAuth({ now }); + await expect(auth!.getConfig()).resolves.toEqual({ + type: 'oauth', + token: 'retried-access-token', + }); + expect(server.sent).toEqual(['stored-refresh-token', 'other-refresh-token']); + expect(readStoredCredentials()?.refreshToken).toBe('retried-refresh-token'); + }); + + it('adopts a fresh token written by another process during a rejected refresh without retrying', async () => { + seedCredentials({ expiresAt: NOW - 1_000 }); + fetchSpy.mockImplementation(async () => { + writeRotatedByOtherProcess('other-access-token', 'other-refresh-token', NOW + 3_600_000); + return jsonResponse(400, { error: 'invalid_grant' }); + }); + + const auth = createStoredCredentialAuth({ now }); + await expect(auth!.getConfig()).resolves.toEqual({ + type: 'oauth', + token: 'other-access-token', + }); + expect(fetchSpy).toHaveBeenCalledTimes(1); + }); + + it('gives up after one retry when the rotated refresh token is rejected as well', async () => { + seedCredentials({ expiresAt: NOW - 1_000 }); + let calls = 0; + fetchSpy.mockImplementation(async () => { + calls += 1; + writeRotatedByOtherProcess('other-access-token', `other-refresh-token-${calls}`, NOW - 500); + return jsonResponse(400, { error: 'invalid_grant' }); + }); + + const auth = createStoredCredentialAuth({ now }); + await expect(auth!.getConfig()).rejects.toThrow(/mcp-linear auth login/); + expect(fetchSpy).toHaveBeenCalledTimes(2); + }); + + it('does not resurrect credentials that were logged out before the refresh', async () => { + seedCredentials({ expiresAt: NOW - 1_000 }); + fakeTokenEndpoint('stored-refresh-token'); + + const auth = createStoredCredentialAuth({ now }); + fs.unlinkSync(path.join(tempDir, 'credentials.json')); + + await expect(auth!.getConfig()).rejects.toThrow(/mcp-linear auth login/); + expect(fetchSpy).not.toHaveBeenCalled(); + expect(readStoredCredentials()).toBeUndefined(); + }); + + it('refreshes with the client of the newest login in the file', async () => { + seedCredentials({ expiresAt: NOW - 1_000 }); + const auth = createStoredCredentialAuth({ now }); + // The user logged in again with another OAuth app; that token expired too. + writeStoredCredentials({ + clientId: 'client-id-2', + accessToken: 'second-login-access-token', + refreshToken: 'stored-refresh-token', + expiresAt: NOW - 500, + scopes: ['read'], + }); + const server = fakeTokenEndpoint('stored-refresh-token'); + + await auth!.getConfig(); + + const body = new URLSearchParams(String((fetchSpy.mock.calls[0][1] as RequestInit).body)); + expect(server.sent).toHaveLength(1); + expect(body.get('client_id')).toBe('client-id-2'); + expect(body.has('client_secret')).toBe(false); + expect(readStoredCredentials()?.clientId).toBe('client-id-2'); + }); + + it('releases the refresh lock after refreshing', async () => { + seedCredentials({ expiresAt: NOW - 1_000 }); + fakeTokenEndpoint('stored-refresh-token'); + + const auth = createStoredCredentialAuth({ now }); + await auth!.getConfig(); + + expect(fs.existsSync(lockPath())).toBe(false); + }); + + it('releases the refresh lock when the refresh fails', async () => { + seedCredentials({ expiresAt: NOW - 1_000 }); + fetchSpy.mockResolvedValue(jsonResponse(400, { error: 'invalid_grant' })); + + const auth = createStoredCredentialAuth({ now }); + await expect(auth!.getConfig()).rejects.toThrow(/mcp-linear auth login/); + + expect(fs.existsSync(lockPath())).toBe(false); + }); + + it('waits for a lock held by another process and then uses the token that process wrote', async () => { + seedCredentials({ expiresAt: NOW - 1_000 }); + fakeTokenEndpoint('stored-refresh-token'); + fs.writeFileSync(lockPath(), 'other-process'); + + setTimeout(() => { + writeRotatedByOtherProcess('other-access-token', 'other-refresh-token', NOW + 3_600_000); + fs.unlinkSync(lockPath()); + }, 150); + + const auth = createStoredCredentialAuth({ now, lockRetryMs: 10 }); + await expect(auth!.getConfig()).resolves.toEqual({ + type: 'oauth', + token: 'other-access-token', + }); + expect(fetchSpy).not.toHaveBeenCalled(); + }); + + it('reclaims a lock left behind by a process that died while refreshing', async () => { + seedCredentials({ expiresAt: NOW - 1_000 }); + fakeTokenEndpoint('stored-refresh-token'); + fs.writeFileSync(lockPath(), 'dead-process'); + const longAgo = new Date(Date.now() - 10 * 60_000); + fs.utimesSync(lockPath(), longAgo, longAgo); + + const auth = createStoredCredentialAuth({ now, lockRetryMs: 10 }); + await expect(auth!.getConfig()).resolves.toEqual({ + type: 'oauth', + token: 'refreshed-access-token-1', + }); + expect(fs.existsSync(lockPath())).toBe(false); + }); +}); diff --git a/src/auth/cli.ts b/src/auth/cli.ts index 2f10417..b7a0f26 100644 --- a/src/auth/cli.ts +++ b/src/auth/cli.ts @@ -4,6 +4,7 @@ import { deleteStoredCredentials, getCredentialsPath, readStoredCredentials, + withCredentialsLock, writeStoredCredentials, } from './credential-store.js'; import { exchangeAuthorizationCode, revokeToken } from './oauth-http.js'; @@ -155,16 +156,20 @@ async function runLogin( codeVerifier: verifier, }); - writeStoredCredentials({ - clientId, - ...(clientSecret ? { clientSecret } : {}), - accessToken: tokens.accessToken, - ...(tokens.refreshToken ? { refreshToken: tokens.refreshToken } : {}), - ...(typeof tokens.expiresIn === 'number' - ? { expiresAt: Date.now() + tokens.expiresIn * 1000 } - : {}), - scopes: tokens.scopes.length > 0 ? tokens.scopes : scopes, - }); + // Under the lock so a token refresh in a running server cannot overwrite + // the new login with tokens from the previous grant. + await withCredentialsLock(async () => + writeStoredCredentials({ + clientId, + ...(clientSecret ? { clientSecret } : {}), + accessToken: tokens.accessToken, + ...(tokens.refreshToken ? { refreshToken: tokens.refreshToken } : {}), + ...(typeof tokens.expiresIn === 'number' + ? { expiresAt: Date.now() + tokens.expiresIn * 1000 } + : {}), + scopes: tokens.scopes.length > 0 ? tokens.scopes : scopes, + }), + ); } catch (error) { const reason = error instanceof Error ? error.message : 'unknown error'; print(`Login failed: ${reason}`); @@ -201,6 +206,12 @@ function runStatus(print: (message: string) => void): number { } async function runLogout(print: (message: string) => void): Promise { + // Under the lock so a token refresh in a running server cannot write the + // credentials back after they are deleted. + return withCredentialsLock(() => logoutUnderLock(print)); +} + +async function logoutUnderLock(print: (message: string) => void): Promise { const credentials = readStoredCredentials(); if (!credentials) { // A corrupt or partial file may still exist; remove it regardless. diff --git a/src/auth/credential-store.ts b/src/auth/credential-store.ts index 9ebd8b2..8a0b09b 100644 --- a/src/auth/credential-store.ts +++ b/src/auth/credential-store.ts @@ -133,6 +133,149 @@ export function writeStoredCredentials(credentials: StoredCredentials): void { } } +const LOCK_FILE_NAME = `${CREDENTIALS_FILE_NAME}.lock`; + +/** A lock older than this is treated as left behind by a dead process. */ +export const CREDENTIALS_LOCK_STALE_MS = 60_000; +/** Give up waiting after this long; longer than the stale window so a dead holder is reclaimed first. */ +export const CREDENTIALS_LOCK_TIMEOUT_MS = 75_000; +const CREDENTIALS_LOCK_RETRY_MS = 100; + +export interface CredentialsLockOptions { + retryMs?: number; + staleMs?: number; + timeoutMs?: number; +} + +export function getCredentialsLockPath(): string { + return path.join(getConfigDir(), LOCK_FILE_NAME); +} + +function errorCode(error: unknown): string | undefined { + return typeof error === 'object' && error !== null && 'code' in error + ? String((error as { code: unknown }).code) + : undefined; +} + +function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +/** + * Remove a lock whose holder is presumed dead. Returns true when the caller + * should try to create the lock again right away. + * + * Renaming first means only one waiter wins the removal. A narrow race remains + * (a waiter can rename away a lock that another waiter created a moment + * earlier). The refresh path mostly absorbs it by re-reading the file and + * retrying once when Linear rejects a refresh token that was rotated + * meanwhile; if the rejection arrives before the winner has written the file, + * that one request fails and the next request picks up the winner's tokens. + */ +function reclaimIfStale(lockPath: string, staleMs: number): boolean { + let mtimeMs: number; + try { + // lstat: a dangling symlink makes O_EXCL report EEXIST while stat reports + // ENOENT, which would spin this loop forever. + mtimeMs = fs.lstatSync(lockPath).mtimeMs; + } catch (error) { + if (errorCode(error) === 'ENOENT') return true; + throw error; + } + if (Date.now() - mtimeMs < staleMs) { + return false; + } + + const reclaimedPath = `${lockPath}.${randomBytes(6).toString('hex')}.stale`; + try { + fs.renameSync(lockPath, reclaimedPath); + } catch (error) { + if (errorCode(error) === 'ENOENT') return true; + throw error; + } + try { + fs.unlinkSync(reclaimedPath); + } catch { + // Best effort; the lock path itself is already free. + } + return true; +} + +/** Create the lock file exclusively. Returns false when it already exists. */ +function tryCreateLock(lockPath: string, owner: string): boolean { + let fd: number; + try { + fd = fs.openSync(lockPath, 'wx', 0o600); + } catch (error) { + if (errorCode(error) === 'EEXIST') return false; + throw error; + } + try { + fs.writeSync(fd, owner); + } catch (error) { + // Do not leave an empty lock that blocks every refresh for the stale window. + fs.closeSync(fd); + fs.unlinkSync(lockPath); + throw error; + } + fs.closeSync(fd); + return true; +} + +function releaseLock(lockPath: string, owner: string): void { + try { + // Only remove our own lock: if ours was reclaimed as stale, another + // process may hold the lock now. + if (fs.readFileSync(lockPath, 'utf8') === owner) { + fs.unlinkSync(lockPath); + } + } catch { + // Already gone or unreadable; nothing to release. + } +} + +/** + * Run `fn` while holding an exclusive lock shared by every process that uses + * this config directory. The lock is a file created with O_EXCL; a lock older + * than the stale window is reclaimed so a crashed process cannot block + * refreshes forever. + */ +export async function withCredentialsLock( + fn: () => Promise, + options: CredentialsLockOptions = {}, +): Promise { + const retryMs = options.retryMs ?? CREDENTIALS_LOCK_RETRY_MS; + const staleMs = options.staleMs ?? CREDENTIALS_LOCK_STALE_MS; + const timeoutMs = options.timeoutMs ?? CREDENTIALS_LOCK_TIMEOUT_MS; + + fs.mkdirSync(getConfigDir(), { recursive: true, mode: 0o700 }); + const lockPath = getCredentialsLockPath(); + const owner = `${process.pid}.${randomBytes(8).toString('hex')}`; + const deadline = Date.now() + timeoutMs; + + for (;;) { + if (tryCreateLock(lockPath, owner)) { + break; + } + const reclaimed = reclaimIfStale(lockPath, staleMs); + if (reclaimed && Date.now() < deadline) { + continue; + } + if (Date.now() >= deadline) { + throw new Error( + 'Timed out waiting for another mcp-linear process to finish refreshing the stored Linear access token.', + ); + } + await sleep(retryMs); + } + + try { + return await fn(); + } finally { + releaseLock(lockPath, owner); + } +} + /** * Delete stored credentials. Returns true when a file was removed. */ diff --git a/src/auth/managed-auth.ts b/src/auth/managed-auth.ts index e90d7c6..e9a5beb 100644 --- a/src/auth/managed-auth.ts +++ b/src/auth/managed-auth.ts @@ -1,6 +1,7 @@ import type { LinearAuthConfig } from '../utils/config.js'; import { readStoredCredentials, + withCredentialsLock, writeStoredCredentials, type StoredCredentials, } from './credential-store.js'; @@ -20,6 +21,8 @@ export interface StoredCredentialAuth { export interface StoredCredentialAuthOptions { now?: () => number; + /** Poll interval while another process holds the refresh lock. */ + lockRetryMs?: number; } function needsRefresh(credentials: StoredCredentials, nowMs: number): boolean { @@ -29,9 +32,22 @@ function needsRefresh(credentials: StoredCredentials, nowMs: number): boolean { return credentials.expiresAt - EXPIRY_SKEW_MS <= nowMs; } +function refreshFailure(error: unknown): Error { + const reason = error instanceof Error ? error.message : 'unknown error'; + return new Error( + `Failed to refresh the stored Linear access token (${reason}). Run \`mcp-linear auth login\` again.`, + ); +} + /** * Create an auth provider over credentials saved by `mcp-linear auth login`. * Returns undefined when no usable credentials are stored. + * + * Several server processes (one per MCP client session) may share one + * credentials file. Linear rotates the refresh token on every refresh, so a + * refresh by one process revokes the refresh token the others hold in memory. + * Refreshes therefore run under a cross-process lock and always start from the + * file, not from memory. */ export function createStoredCredentialAuth( options: StoredCredentialAuthOptions = {}, @@ -43,47 +59,86 @@ export function createStoredCredentialAuth( const now = options.now ?? Date.now; let credentials = initial; - // Serialize refreshes so concurrent requests never race a token rotation. + // Serialize refreshes within this process; the file lock serializes them + // across processes. let pendingRefresh: Promise | undefined; - async function refresh(): Promise { - if (!credentials.refreshToken) { - throw new Error( - 'Stored Linear access token has expired and no refresh token is available. Run `mcp-linear auth login` again.', - ); - } - - let tokens; - try { - tokens = await refreshAccessToken({ - refreshToken: credentials.refreshToken, - clientId: credentials.clientId, - ...(credentials.clientSecret ? { clientSecret: credentials.clientSecret } : {}), - }); - } catch (error) { - const reason = error instanceof Error ? error.message : 'unknown error'; - throw new Error( - `Failed to refresh the stored Linear access token (${reason}). Run \`mcp-linear auth login\` again.`, - ); - } + async function requestRefresh(from: StoredCredentials): Promise { + const tokens = await refreshAccessToken({ + refreshToken: from.refreshToken!, + clientId: from.clientId, + ...(from.clientSecret ? { clientSecret: from.clientSecret } : {}), + }); const updated: StoredCredentials = { - clientId: credentials.clientId, - ...(credentials.clientSecret ? { clientSecret: credentials.clientSecret } : {}), + clientId: from.clientId, + ...(from.clientSecret ? { clientSecret: from.clientSecret } : {}), accessToken: tokens.accessToken, // Linear rotates refresh tokens; fall back to the previous one only if // the response omitted a replacement. - refreshToken: tokens.refreshToken ?? credentials.refreshToken, - scopes: tokens.scopes.length > 0 ? tokens.scopes : credentials.scopes, + refreshToken: tokens.refreshToken ?? from.refreshToken, + scopes: tokens.scopes.length > 0 ? tokens.scopes : from.scopes, }; if (typeof tokens.expiresIn === 'number') { updated.expiresAt = now() + tokens.expiresIn * 1000; } + return updated; + } + + async function refreshUnderLock(): Promise { + // Another process may have refreshed while we waited for the lock (or + // since we started); its rotation revoked the refresh token in memory. + const latest = readStoredCredentials(); + if (!latest) { + // `auth logout` removed the file; refreshing from memory would bring + // the credentials back. + throw new Error( + 'Stored Linear credentials were removed (logged out). Run `mcp-linear auth login` again.', + ); + } + if (!needsRefresh(latest, now())) { + credentials = latest; + return; + } + if (!latest.refreshToken) { + throw new Error( + 'Stored Linear access token has expired and no refresh token is available. Run `mcp-linear auth login` again.', + ); + } + + let updated: StoredCredentials; + try { + updated = await requestRefresh(latest); + } catch (error) { + // A process that does not take the lock (an older build still running) + // may have rotated the token while our request was in flight. Pick up + // its result, retrying at most once. + const reread = readStoredCredentials(); + if (!reread?.refreshToken || reread.refreshToken === latest.refreshToken) { + throw refreshFailure(error); + } + if (!needsRefresh(reread, now())) { + credentials = reread; + return; + } + try { + updated = await requestRefresh(reread); + } catch (retryError) { + throw refreshFailure(retryError); + } + } writeStoredCredentials(updated); credentials = updated; } + function refresh(): Promise { + return withCredentialsLock( + refreshUnderLock, + options.lockRetryMs === undefined ? {} : { retryMs: options.lockRetryMs }, + ); + } + return { async getConfig(): Promise { if (needsRefresh(credentials, now())) { From c875a7be11bea698e372d73d8ac9a7b3db871b28 Mon Sep 17 00:00:00 2001 From: Alexey Elizarov Date: Fri, 13 Nov 2026 19:08:03 +0100 Subject: [PATCH 2/4] fix: protect OAuth credentials with OS file locks --- .github/workflows/auth-lock.yml | 40 ++++++ package-lock.json | 77 +++++++++++ package.json | 1 + src/__tests__/auth-cli.test.ts | 16 --- src/__tests__/auth-credential-store.test.ts | 49 ++----- src/__tests__/auth-managed-auth.test.ts | 50 +------ src/__tests__/auth-multiprocess.test.ts | 97 ++++++++++++++ src/__tests__/fixtures/auth-worker.mjs | 41 ++++++ src/auth/credential-store.ts | 141 +++----------------- src/fs-native-extensions.d.ts | 4 + 10 files changed, 293 insertions(+), 223 deletions(-) create mode 100644 .github/workflows/auth-lock.yml create mode 100644 src/__tests__/auth-multiprocess.test.ts create mode 100644 src/__tests__/fixtures/auth-worker.mjs create mode 100644 src/fs-native-extensions.d.ts diff --git a/.github/workflows/auth-lock.yml b/.github/workflows/auth-lock.yml new file mode 100644 index 0000000..dabaf6d --- /dev/null +++ b/.github/workflows/auth-lock.yml @@ -0,0 +1,40 @@ +name: Auth lock portability + +on: + pull_request: + paths: + - 'src/auth/**' + - 'src/__tests__/auth-*' + - 'src/__tests__/fixtures/auth-worker.mjs' + - 'src/fs-native-extensions.d.ts' + - 'package*.json' + - '.github/workflows/auth-lock.yml' + push: + branches: [main] + paths: + - 'src/auth/**' + - 'src/__tests__/auth-*' + - 'src/__tests__/fixtures/auth-worker.mjs' + - 'src/fs-native-extensions.d.ts' + - 'package*.json' + - '.github/workflows/auth-lock.yml' + +permissions: + contents: read + +jobs: + auth-lock: + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + node: [20, 24] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v5 + - uses: actions/setup-node@v5 + with: + node-version: ${{ matrix.node }} + cache: npm + - run: npm ci + - run: npx jest src/__tests__/auth-multiprocess.test.ts --runInBand diff --git a/package-lock.json b/package-lock.json index 842fafb..6ca3db2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -17,6 +17,7 @@ "cors": "^2.8.5", "dotenv": "^16.4.7", "express": "^4.21.2", + "fs-native-extensions": "^1.5.3", "graphql": "^16.10.0", "graphql-request": "^7.1.2", "helmet": "^8.0.0", @@ -2158,6 +2159,54 @@ "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", "dev": true }, + "node_modules/bare-addon-resolve": { + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/bare-addon-resolve/-/bare-addon-resolve-1.12.0.tgz", + "integrity": "sha512-MJHQVQXD2QI0O6Lq6kkRFARfJ2/vlS9NSHdK/aXtKn+0+ysbvFjjOIaKKvNXCBs3PBxX67rny81zo7ne/mceHg==", + "license": "Apache-2.0", + "dependencies": { + "bare-host-parser": "^1.0.0", + "bare-module-resolve": "^1.10.0", + "bare-semver": "^1.0.0" + }, + "peerDependencies": { + "bare-url": "*" + }, + "peerDependenciesMeta": { + "bare-url": { + "optional": true + } + } + }, + "node_modules/bare-host-parser": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/bare-host-parser/-/bare-host-parser-1.0.0.tgz", + "integrity": "sha512-Tzb/ty4aliZzZmMETMzQQUYhVs8s8cLSIweoJEA03xkrDfpLUvEyOkaGWunAxRaDBXMskP0HFvjpxMPCuNh7Nw==", + "license": "Apache-2.0" + }, + "node_modules/bare-module-resolve": { + "version": "1.12.6", + "resolved": "https://registry.npmjs.org/bare-module-resolve/-/bare-module-resolve-1.12.6.tgz", + "integrity": "sha512-tsoOqHmtF6VmNX4LYDBZwvQVkSmEagnbykNjK31LMxz/amyKfjCs4K976n7uJd1bvWfxbpLQ3Fy7qq8an6jR6Q==", + "license": "Apache-2.0", + "dependencies": { + "bare-semver": "^1.0.0" + }, + "peerDependencies": { + "bare-url": "*" + }, + "peerDependenciesMeta": { + "bare-url": { + "optional": true + } + } + }, + "node_modules/bare-semver": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/bare-semver/-/bare-semver-1.1.0.tgz", + "integrity": "sha512-1Hw5qJ7hXdVt3uPUqjeFTuxyvBUJauvz5A1I2jk8gzjZMHp04n//6nV9MDbG9CMw78JHY2lGV0w6s//LrASm2w==", + "license": "Apache-2.0" + }, "node_modules/binary-extensions": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", @@ -3323,6 +3372,16 @@ "node": ">= 0.6" } }, + "node_modules/fs-native-extensions": { + "version": "1.5.3", + "resolved": "https://registry.npmjs.org/fs-native-extensions/-/fs-native-extensions-1.5.3.tgz", + "integrity": "sha512-pl39uoPqAdANcule683Wghiw3UlQc+tDagBtKT8ltKaK/Jxu9cDL5sMjca+4eTgrHnn3I7qRO5jPG/658GOsdg==", + "license": "Apache-2.0", + "dependencies": { + "require-addon": "^1.1.0", + "which-runtime": "^1.2.0" + } + }, "node_modules/fs.realpath": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", @@ -5362,6 +5421,18 @@ "node": ">=8.10.0" } }, + "node_modules/require-addon": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/require-addon/-/require-addon-1.3.0.tgz", + "integrity": "sha512-j8pifaPNZI7ShKY3ihXZwF0qaEjua8zmlqPvDil0a8SBnyRvjCbAiEQuzO0UcoXH1sqU5U/ilXSjYd1W5NYwAA==", + "license": "Apache-2.0", + "dependencies": { + "bare-addon-resolve": "^1.3.0" + }, + "engines": { + "bare": ">=1.10.0" + } + }, "node_modules/require-directory": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", @@ -6166,6 +6237,12 @@ "node": ">= 8" } }, + "node_modules/which-runtime": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/which-runtime/-/which-runtime-1.4.0.tgz", + "integrity": "sha512-0ugbP4CJW4e2D20jvEcC4973dCgIaHI4Rw1PT+26U9zEve7FyYdWAIwUnoeOYvoCfn+wXHoHTKb1KhkYlb60Pw==", + "license": "Apache-2.0" + }, "node_modules/word-wrap": { "version": "1.2.5", "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", diff --git a/package.json b/package.json index e1a3702..c5f9585 100644 --- a/package.json +++ b/package.json @@ -50,6 +50,7 @@ "cors": "^2.8.5", "dotenv": "^16.4.7", "express": "^4.21.2", + "fs-native-extensions": "^1.5.3", "graphql": "^16.10.0", "graphql-request": "^7.1.2", "helmet": "^8.0.0", diff --git a/src/__tests__/auth-cli.test.ts b/src/__tests__/auth-cli.test.ts index db08eff..92da909 100644 --- a/src/__tests__/auth-cli.test.ts +++ b/src/__tests__/auth-cli.test.ts @@ -250,22 +250,6 @@ describe('auth CLI', () => { expect(fs.existsSync(getCredentialsPath())).toBe(false); }); - it('waits for a running token refresh to finish before deleting the credentials', async () => { - writeStoredCredentials(storedCredentials); - fetchSpy.mockResolvedValueOnce(jsonResponse(200, {})); - const lockPath = path.join(tempDir, 'credentials.json.lock'); - fs.writeFileSync(lockPath, 'refreshing-process'); - - const logout = runAuthCli(['logout'], { print }); - await new Promise((resolve) => setTimeout(resolve, 250)); - const presentWhileLocked = fs.existsSync(getCredentialsPath()); - fs.unlinkSync(lockPath); - - await expect(logout).resolves.toBe(0); - expect(presentWhileLocked).toBe(true); - expect(fs.existsSync(getCredentialsPath())).toBe(false); - }); - it('still deletes local credentials when revocation fails offline', async () => { writeStoredCredentials(storedCredentials); fetchSpy.mockRejectedValueOnce(new TypeError('fetch failed')); diff --git a/src/__tests__/auth-credential-store.test.ts b/src/__tests__/auth-credential-store.test.ts index eb18bc6..1c6ceca 100644 --- a/src/__tests__/auth-credential-store.test.ts +++ b/src/__tests__/auth-credential-store.test.ts @@ -140,51 +140,20 @@ describe('credentials lock', () => { fs.rmSync(tempDir, { recursive: true, force: true }); }); - it('runs the callback while holding the lock file and removes it afterwards', async () => { - let heldDuringCallback = false; + it('does not take over a lock held by a live process just because it is old', async () => { await withCredentialsLock(async () => { - heldDuringCallback = fs.existsSync(getCredentialsLockPath()); + const old = new Date(Date.now() - 120_000); + fs.utimesSync(getCredentialsLockPath(), old, old); + await expect(withCredentialsLock(async () => undefined, { retryMs: 5, timeoutMs: 50 })) + .rejects.toThrow(/Timed out/); }); - - expect(heldDuringCallback).toBe(true); - expect(fs.existsSync(getCredentialsLockPath())).toBe(false); }); - it('leaves a lock alone that another process took over meanwhile', async () => { + it('retains the lock file and releases it for the next holder', async () => { await withCredentialsLock(async () => { - // Our lock was reclaimed as stale and another process now holds it. - fs.writeFileSync(getCredentialsLockPath(), 'other-process-owner'); + expect(fs.existsSync(getCredentialsLockPath())).toBe(true); }); - - expect(fs.readFileSync(getCredentialsLockPath(), 'utf8')).toBe('other-process-owner'); - }); - - it('times out with a clear message while another process keeps a fresh lock', async () => { - fs.writeFileSync(getCredentialsLockPath(), 'other-process-owner'); - const callback = jest.fn(async () => undefined); - - await expect( - withCredentialsLock(callback, { retryMs: 5, timeoutMs: 50 }), - ).rejects.toThrow(/Timed out waiting for another mcp-linear process/); - expect(callback).not.toHaveBeenCalled(); - expect(fs.readFileSync(getCredentialsLockPath(), 'utf8')).toBe('other-process-owner'); - }); - - it('reclaims a stale lock and cleans up the reclaimed file', async () => { - fs.writeFileSync(getCredentialsLockPath(), 'dead-process-owner'); - const longAgo = new Date(Date.now() - 10 * 60_000); - fs.utimesSync(getCredentialsLockPath(), longAgo, longAgo); - - await withCredentialsLock(async () => undefined, { retryMs: 5 }); - - expect(fs.readdirSync(tempDir)).toEqual([]); - }); - - it('waits instead of spinning when the lock path is a dangling symlink', async () => { - fs.symlinkSync(path.join(tempDir, 'missing-target'), getCredentialsLockPath()); - - await expect( - withCredentialsLock(async () => undefined, { retryMs: 5, timeoutMs: 50 }), - ).rejects.toThrow(/Timed out/); + await expect(withCredentialsLock(async () => 'acquired')).resolves.toBe('acquired'); + expect(fs.existsSync(getCredentialsLockPath())).toBe(true); }); }); diff --git a/src/__tests__/auth-managed-auth.test.ts b/src/__tests__/auth-managed-auth.test.ts index 2ea8e38..9f0eaca 100644 --- a/src/__tests__/auth-managed-auth.test.ts +++ b/src/__tests__/auth-managed-auth.test.ts @@ -5,6 +5,7 @@ import path from 'node:path'; import { readStoredCredentials, writeStoredCredentials, + withCredentialsLock, type StoredCredentials, } from '../auth/credential-store.js'; import { createStoredCredentialAuth } from '../auth/managed-auth.js'; @@ -217,7 +218,6 @@ describe('stored credential auth shared across processes', () => { }); } - const lockPath = () => path.join(tempDir, 'credentials.json.lock'); beforeEach(() => { process.env = { ...originalEnv }; @@ -390,56 +390,12 @@ describe('stored credential auth shared across processes', () => { expect(readStoredCredentials()?.clientId).toBe('client-id-2'); }); - it('releases the refresh lock after refreshing', async () => { - seedCredentials({ expiresAt: NOW - 1_000 }); - fakeTokenEndpoint('stored-refresh-token'); - - const auth = createStoredCredentialAuth({ now }); - await auth!.getConfig(); - - expect(fs.existsSync(lockPath())).toBe(false); - }); - it('releases the refresh lock when the refresh fails', async () => { seedCredentials({ expiresAt: NOW - 1_000 }); fetchSpy.mockResolvedValue(jsonResponse(400, { error: 'invalid_grant' })); - const auth = createStoredCredentialAuth({ now }); await expect(auth!.getConfig()).rejects.toThrow(/mcp-linear auth login/); - - expect(fs.existsSync(lockPath())).toBe(false); - }); - - it('waits for a lock held by another process and then uses the token that process wrote', async () => { - seedCredentials({ expiresAt: NOW - 1_000 }); - fakeTokenEndpoint('stored-refresh-token'); - fs.writeFileSync(lockPath(), 'other-process'); - - setTimeout(() => { - writeRotatedByOtherProcess('other-access-token', 'other-refresh-token', NOW + 3_600_000); - fs.unlinkSync(lockPath()); - }, 150); - - const auth = createStoredCredentialAuth({ now, lockRetryMs: 10 }); - await expect(auth!.getConfig()).resolves.toEqual({ - type: 'oauth', - token: 'other-access-token', - }); - expect(fetchSpy).not.toHaveBeenCalled(); - }); - - it('reclaims a lock left behind by a process that died while refreshing', async () => { - seedCredentials({ expiresAt: NOW - 1_000 }); - fakeTokenEndpoint('stored-refresh-token'); - fs.writeFileSync(lockPath(), 'dead-process'); - const longAgo = new Date(Date.now() - 10 * 60_000); - fs.utimesSync(lockPath(), longAgo, longAgo); - - const auth = createStoredCredentialAuth({ now, lockRetryMs: 10 }); - await expect(auth!.getConfig()).resolves.toEqual({ - type: 'oauth', - token: 'refreshed-access-token-1', - }); - expect(fs.existsSync(lockPath())).toBe(false); + fetchSpy.mockRestore(); + await expect(withCredentialsLock(async () => 'acquired', { timeoutMs: 100 })).resolves.toBe('acquired'); }); }); diff --git a/src/__tests__/auth-multiprocess.test.ts b/src/__tests__/auth-multiprocess.test.ts new file mode 100644 index 0000000..f75a521 --- /dev/null +++ b/src/__tests__/auth-multiprocess.test.ts @@ -0,0 +1,97 @@ +import { fork, type ChildProcess } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { once } from 'node:events'; +import { readStoredCredentials, writeStoredCredentials } from '../auth/credential-store.js'; + +jest.setTimeout(30_000); + +type Message = { event: string; token?: string; code?: number; message?: string }; +let directory: string; +let children: ChildProcess[]; + +function start(action: string): ChildProcess { + const child = fork(path.resolve('src/__tests__/fixtures/auth-worker.mjs'), [action], { + execArgv: ['--loader', 'ts-node/esm'], + env: { ...process.env, MCP_LINEAR_CONFIG_DIR: directory, TS_NODE_TRANSPILE_ONLY: 'true', NODE_NO_WARNINGS: '1' }, + stdio: ['ignore', 'ignore', 'inherit', 'ipc'], + }); + children.push(child); + return child; +} + +async function message(child: ChildProcess): Promise { + const [value] = await once(child, 'message'); + if (value.event === 'error') throw new Error(value.message); + return value; +} + +beforeEach(() => { + directory = fs.mkdtempSync(path.join(os.tmpdir(), 'mcp-linear-multiprocess-')); + process.env.MCP_LINEAR_CONFIG_DIR = directory; + children = []; +}); +afterEach(async () => { + for (const child of children) { + if (child.exitCode === null && child.signalCode === null) { + child.kill('SIGKILL'); + await once(child, 'exit'); + } + } + delete process.env.MCP_LINEAR_CONFIG_DIR; + fs.rmSync(directory, { recursive: true, force: true }); +}); + +it('does not steal an old lock held by a live process and recovers after it dies', async () => { + const holder = start('hold'); + expect((await message(holder)).event).toBe('held'); + const lock = path.join(directory, 'credentials.json.lock'); + const old = new Date(Date.now() - 120_000); + fs.utimesSync(lock, old, old); + const contender = start('acquire'); + const acquired = message(contender); + let finished = false; + void acquired.then(() => { finished = true; }); + await new Promise((resolve) => setTimeout(resolve, 1500)); + expect(finished).toBe(false); + const exited = once(holder, 'exit'); + holder.kill('SIGKILL'); + await exited; + expect((await acquired).event).toBe('result'); +}); + +it.each(['logout', 'login'])('serializes %s behind a refresh in another process', async (action) => { + writeStoredCredentials({ clientId: 'old-client', accessToken: 'old-access', refreshToken: 'old-refresh', expiresAt: Date.now() - 1000, scopes: [] }); + const refresh = start('refresh'); + expect((await message(refresh)).event).toBe('started'); + expect((await message(refresh)).event).toBe('request'); + const other = start(action); + expect((await message(other)).event).toBe('started'); + const result = message(other); + let finished = false; + void result.then(() => { finished = true; }); + await new Promise((resolve) => setTimeout(resolve, 250)); + expect(finished).toBe(false); + const refreshed = message(refresh); + refresh.send('continue'); + expect((await refreshed).token).toBe('rotated-access'); + expect((await result).event).toBe('result'); + if (action === 'logout') expect(readStoredCredentials()).toBeUndefined(); + else expect(readStoredCredentials()?.accessToken).toBe('new-access'); +}); + +it('shares one refresh between two separate server processes', async () => { + writeStoredCredentials({ clientId: 'client', accessToken: 'old', refreshToken: 'old-refresh', expiresAt: Date.now() - 1000, scopes: [] }); + const first = start('refresh'); + expect((await message(first)).event).toBe('started'); + expect((await message(first)).event).toBe('request'); + const second = start('refresh'); + expect((await message(second)).event).toBe('started'); + const secondResult = message(second); + const firstResult = message(first); + first.send('continue'); + expect((await firstResult).token).toBe('rotated-access'); + expect(await secondResult).toEqual({ event: 'result', token: 'rotated-access' }); + expect(readStoredCredentials()?.refreshToken).toBe('rotated-refresh'); +}); diff --git a/src/__tests__/fixtures/auth-worker.mjs b/src/__tests__/fixtures/auth-worker.mjs new file mode 100644 index 0000000..6618ccb --- /dev/null +++ b/src/__tests__/fixtures/auth-worker.mjs @@ -0,0 +1,41 @@ +import { withCredentialsLock, writeStoredCredentials } from '../../auth/credential-store.ts'; +import { createStoredCredentialAuth } from '../../auth/managed-auth.ts'; +import { runAuthCli } from '../../auth/cli.ts'; + +const waitForContinue = () => new Promise((resolve) => process.once('message', resolve)); +const send = (message) => process.send(message); +try { + const action = process.argv[2]; + if (action === 'hold') { + await withCredentialsLock(async () => { + send({ event: 'held' }); + await waitForContinue(); + }); + } else if (action === 'refresh') { + globalThis.fetch = async () => { + send({ event: 'request' }); + await waitForContinue(); + return new Response(JSON.stringify({ access_token: 'rotated-access', refresh_token: 'rotated-refresh', expires_in: 3600 }), { status: 200 }); + }; + const auth = createStoredCredentialAuth({ lockRetryMs: 10 }); + send({ event: 'started' }); + const result = await auth.getConfig(); + send({ event: 'result', token: result.token }); + } else if (action === 'logout') { + globalThis.fetch = async () => new Response('{}', { status: 200 }); + send({ event: 'started' }); + const code = await runAuthCli(['logout'], { print: () => {} }); + send({ event: 'result', code }); + } else if (action === 'login') { + send({ event: 'started' }); + await withCredentialsLock(async () => writeStoredCredentials({ clientId: 'new-client', accessToken: 'new-access', refreshToken: 'new-refresh', expiresAt: Date.now() + 3600000, scopes: [] }), { retryMs: 10 }); + send({ event: 'result' }); + } else if (action === 'acquire') { + await withCredentialsLock(async () => send({ event: 'result' }), { retryMs: 10, timeoutMs: 3000 }); + } + process.disconnect(); +} catch (error) { + send({ event: 'error', message: error.message }); + process.exitCode = 1; + process.disconnect(); +} diff --git a/src/auth/credential-store.ts b/src/auth/credential-store.ts index 8a0b09b..1cc68b3 100644 --- a/src/auth/credential-store.ts +++ b/src/auth/credential-store.ts @@ -2,6 +2,7 @@ import { randomBytes } from 'node:crypto'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; +import nativeFs from 'fs-native-extensions'; /** * Credentials persisted by `mcp-linear auth login`. @@ -134,16 +135,11 @@ export function writeStoredCredentials(credentials: StoredCredentials): void { } const LOCK_FILE_NAME = `${CREDENTIALS_FILE_NAME}.lock`; - -/** A lock older than this is treated as left behind by a dead process. */ -export const CREDENTIALS_LOCK_STALE_MS = 60_000; -/** Give up waiting after this long; longer than the stale window so a dead holder is reclaimed first. */ -export const CREDENTIALS_LOCK_TIMEOUT_MS = 75_000; +const CREDENTIALS_LOCK_TIMEOUT_MS = 75_000; const CREDENTIALS_LOCK_RETRY_MS = 100; export interface CredentialsLockOptions { retryMs?: number; - staleMs?: number; timeoutMs?: number; } @@ -151,128 +147,33 @@ export function getCredentialsLockPath(): string { return path.join(getConfigDir(), LOCK_FILE_NAME); } -function errorCode(error: unknown): string | undefined { - return typeof error === 'object' && error !== null && 'code' in error - ? String((error as { code: unknown }).code) - : undefined; -} - -function sleep(ms: number): Promise { - return new Promise((resolve) => setTimeout(resolve, ms)); -} - -/** - * Remove a lock whose holder is presumed dead. Returns true when the caller - * should try to create the lock again right away. - * - * Renaming first means only one waiter wins the removal. A narrow race remains - * (a waiter can rename away a lock that another waiter created a moment - * earlier). The refresh path mostly absorbs it by re-reading the file and - * retrying once when Linear rejects a refresh token that was rotated - * meanwhile; if the rejection arrives before the winner has written the file, - * that one request fails and the next request picks up the winner's tokens. - */ -function reclaimIfStale(lockPath: string, staleMs: number): boolean { - let mtimeMs: number; - try { - // lstat: a dangling symlink makes O_EXCL report EEXIST while stat reports - // ENOENT, which would spin this loop forever. - mtimeMs = fs.lstatSync(lockPath).mtimeMs; - } catch (error) { - if (errorCode(error) === 'ENOENT') return true; - throw error; - } - if (Date.now() - mtimeMs < staleMs) { - return false; - } - - const reclaimedPath = `${lockPath}.${randomBytes(6).toString('hex')}.stale`; - try { - fs.renameSync(lockPath, reclaimedPath); - } catch (error) { - if (errorCode(error) === 'ENOENT') return true; - throw error; - } - try { - fs.unlinkSync(reclaimedPath); - } catch { - // Best effort; the lock path itself is already free. - } - return true; -} - -/** Create the lock file exclusively. Returns false when it already exists. */ -function tryCreateLock(lockPath: string, owner: string): boolean { - let fd: number; - try { - fd = fs.openSync(lockPath, 'wx', 0o600); - } catch (error) { - if (errorCode(error) === 'EEXIST') return false; - throw error; - } - try { - fs.writeSync(fd, owner); - } catch (error) { - // Do not leave an empty lock that blocks every refresh for the stale window. - fs.closeSync(fd); - fs.unlinkSync(lockPath); - throw error; - } - fs.closeSync(fd); - return true; -} - -function releaseLock(lockPath: string, owner: string): void { - try { - // Only remove our own lock: if ours was reclaimed as stale, another - // process may hold the lock now. - if (fs.readFileSync(lockPath, 'utf8') === owner) { - fs.unlinkSync(lockPath); - } - } catch { - // Already gone or unreadable; nothing to release. - } -} - -/** - * Run `fn` while holding an exclusive lock shared by every process that uses - * this config directory. The lock is a file created with O_EXCL; a lock older - * than the stale window is reclaimed so a crashed process cannot block - * refreshes forever. - */ +/** Hold an OS lock on a permanent file; the OS releases it if the process exits. */ export async function withCredentialsLock( fn: () => Promise, options: CredentialsLockOptions = {}, ): Promise { - const retryMs = options.retryMs ?? CREDENTIALS_LOCK_RETRY_MS; - const staleMs = options.staleMs ?? CREDENTIALS_LOCK_STALE_MS; - const timeoutMs = options.timeoutMs ?? CREDENTIALS_LOCK_TIMEOUT_MS; - fs.mkdirSync(getConfigDir(), { recursive: true, mode: 0o700 }); - const lockPath = getCredentialsLockPath(); - const owner = `${process.pid}.${randomBytes(8).toString('hex')}`; - const deadline = Date.now() + timeoutMs; - - for (;;) { - if (tryCreateLock(lockPath, owner)) { - break; - } - const reclaimed = reclaimIfStale(lockPath, staleMs); - if (reclaimed && Date.now() < deadline) { - continue; - } - if (Date.now() >= deadline) { - throw new Error( - 'Timed out waiting for another mcp-linear process to finish refreshing the stored Linear access token.', - ); - } - await sleep(retryMs); - } - + const fd = fs.openSync( + getCredentialsLockPath(), + fs.constants.O_CREAT | fs.constants.O_RDWR | (fs.constants.O_NOFOLLOW ?? 0), + 0o600, + ); + const deadline = Date.now() + (options.timeoutMs ?? CREDENTIALS_LOCK_TIMEOUT_MS); + let locked = false; try { + while (!(locked = nativeFs.tryLock(fd))) { + if (Date.now() >= deadline) { + throw new Error('Timed out waiting for another mcp-linear process to finish using the stored Linear credentials.'); + } + await new Promise((resolve) => setTimeout(resolve, options.retryMs ?? CREDENTIALS_LOCK_RETRY_MS)); + } return await fn(); } finally { - releaseLock(lockPath, owner); + try { + if (locked) nativeFs.unlock(fd); + } finally { + fs.closeSync(fd); + } } } diff --git a/src/fs-native-extensions.d.ts b/src/fs-native-extensions.d.ts new file mode 100644 index 0000000..7f18622 --- /dev/null +++ b/src/fs-native-extensions.d.ts @@ -0,0 +1,4 @@ +declare module 'fs-native-extensions' { + const nativeFs: { tryLock(fd: number): boolean; unlock(fd: number): void }; + export default nativeFs; +} From 00c1a8a5bd4bd1c3129e912e1a74d38ea5ee0038 Mon Sep 17 00:00:00 2001 From: Alexey Elizarov Date: Fri, 13 Nov 2026 19:10:35 +0100 Subject: [PATCH 3/4] test: synchronize lock contender startup --- src/__tests__/auth-multiprocess.test.ts | 1 + src/__tests__/fixtures/auth-worker.mjs | 1 + 2 files changed, 2 insertions(+) diff --git a/src/__tests__/auth-multiprocess.test.ts b/src/__tests__/auth-multiprocess.test.ts index f75a521..549e651 100644 --- a/src/__tests__/auth-multiprocess.test.ts +++ b/src/__tests__/auth-multiprocess.test.ts @@ -50,6 +50,7 @@ it('does not steal an old lock held by a live process and recovers after it dies const old = new Date(Date.now() - 120_000); fs.utimesSync(lock, old, old); const contender = start('acquire'); + expect((await message(contender)).event).toBe('started'); const acquired = message(contender); let finished = false; void acquired.then(() => { finished = true; }); diff --git a/src/__tests__/fixtures/auth-worker.mjs b/src/__tests__/fixtures/auth-worker.mjs index 6618ccb..77b4b0e 100644 --- a/src/__tests__/fixtures/auth-worker.mjs +++ b/src/__tests__/fixtures/auth-worker.mjs @@ -31,6 +31,7 @@ try { await withCredentialsLock(async () => writeStoredCredentials({ clientId: 'new-client', accessToken: 'new-access', refreshToken: 'new-refresh', expiresAt: Date.now() + 3600000, scopes: [] }), { retryMs: 10 }); send({ event: 'result' }); } else if (action === 'acquire') { + send({ event: 'started' }); await withCredentialsLock(async () => send({ event: 'result' }), { retryMs: 10, timeoutMs: 3000 }); } process.disconnect(); From bf6d1820ac1f547cc5b27d55f7b5bd1e1e58018e Mon Sep 17 00:00:00 2001 From: Alexey Elizarov Date: Fri, 13 Nov 2026 19:32:38 +0100 Subject: [PATCH 4/4] fix: validate Docker runtime and real OAuth login serialization --- .dockerignore | 5 +++++ .github/workflows/auth-lock.yml | 28 +++++++++++++++++++++++ Dockerfile | 30 ++++++------------------- src/__tests__/auth-multiprocess.test.ts | 5 +++-- src/__tests__/fixtures/auth-worker.mjs | 28 +++++++++++++++++++---- 5 files changed, 67 insertions(+), 29 deletions(-) create mode 100644 .dockerignore diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..00d0278 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,5 @@ +.git +node_modules +dist +coverage +.codegraph diff --git a/.github/workflows/auth-lock.yml b/.github/workflows/auth-lock.yml index dabaf6d..1591714 100644 --- a/.github/workflows/auth-lock.yml +++ b/.github/workflows/auth-lock.yml @@ -3,6 +3,9 @@ name: Auth lock portability on: pull_request: paths: + - 'Dockerfile' + - '.dockerignore' + - 'scripts/mcp-smoke-test.mjs' - 'src/auth/**' - 'src/__tests__/auth-*' - 'src/__tests__/fixtures/auth-worker.mjs' @@ -12,6 +15,9 @@ on: push: branches: [main] paths: + - 'Dockerfile' + - '.dockerignore' + - 'scripts/mcp-smoke-test.mjs' - 'src/auth/**' - 'src/__tests__/auth-*' - 'src/__tests__/fixtures/auth-worker.mjs' @@ -38,3 +44,25 @@ jobs: cache: npm - run: npm ci - run: npx jest src/__tests__/auth-multiprocess.test.ts --runInBand + + docker: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + - uses: actions/setup-node@v5 + with: + node-version: 24 + cache: npm + - run: npm ci + - run: npm test + - run: npm run build + - run: docker build -t mcp-linear:auth-lock . + - name: Verify native credential lock in the production image + run: >- + docker run --rm mcp-linear:auth-lock node --input-type=module -e + "import { withCredentialsLock } from './dist/auth/credential-store.js'; + await withCredentialsLock(async () => {});" + - name: Verify MCP server in the production image + run: >- + docker run --rm -v "$PWD/scripts:/app/scripts:ro" + mcp-linear:auth-lock node scripts/mcp-smoke-test.mjs diff --git a/Dockerfile b/Dockerfile index e4a62ad..47a4d19 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,33 +1,17 @@ -# Generated by https://smithery.ai. See: https://smithery.ai/docs/config#dockerfile -FROM node:lts-alpine AS builder +FROM node:24-bookworm-slim AS builder WORKDIR /app - -# Copy package.json and package-lock.json if exists -COPY package.json ./ - -# Install dependencies without running scripts to avoid issues -RUN npm install --ignore-scripts - -# Copy the rest of the files +COPY package.json package-lock.json ./ +RUN npm ci --ignore-scripts COPY . ./ - -# Build the project RUN npm run build - -FROM node:lts-alpine +FROM node:24-bookworm-slim WORKDIR /app - -# Copy only necessary files for runtime -COPY package.json ./ +COPY package.json package-lock.json ./ +RUN npm ci --omit=dev --ignore-scripts COPY --from=builder /app/dist ./dist -# Install only production dependencies -RUN npm install --production --ignore-scripts - EXPOSE 3000 - -# Run the server -CMD ["npm", "start"] \ No newline at end of file +CMD ["npm", "start"] diff --git a/src/__tests__/auth-multiprocess.test.ts b/src/__tests__/auth-multiprocess.test.ts index 549e651..c98c640 100644 --- a/src/__tests__/auth-multiprocess.test.ts +++ b/src/__tests__/auth-multiprocess.test.ts @@ -74,12 +74,13 @@ it.each(['logout', 'login'])('serializes %s behind a refresh in another process' void result.then(() => { finished = true; }); await new Promise((resolve) => setTimeout(resolve, 250)); expect(finished).toBe(false); + expect(readStoredCredentials()?.accessToken).toBe('old-access'); const refreshed = message(refresh); refresh.send('continue'); expect((await refreshed).token).toBe('rotated-access'); - expect((await result).event).toBe('result'); + expect(await result).toEqual({ event: 'result', code: 0 }); if (action === 'logout') expect(readStoredCredentials()).toBeUndefined(); - else expect(readStoredCredentials()?.accessToken).toBe('new-access'); + else expect(readStoredCredentials()).toMatchObject({ clientId: 'new-client', accessToken: 'new-access', refreshToken: 'new-refresh', scopes: ['read'] }); }); it('shares one refresh between two separate server processes', async () => { diff --git a/src/__tests__/fixtures/auth-worker.mjs b/src/__tests__/fixtures/auth-worker.mjs index 77b4b0e..89f241b 100644 --- a/src/__tests__/fixtures/auth-worker.mjs +++ b/src/__tests__/fixtures/auth-worker.mjs @@ -1,4 +1,5 @@ -import { withCredentialsLock, writeStoredCredentials } from '../../auth/credential-store.ts'; +import http from 'node:http'; +import { withCredentialsLock } from '../../auth/credential-store.ts'; import { createStoredCredentialAuth } from '../../auth/managed-auth.ts'; import { runAuthCli } from '../../auth/cli.ts'; @@ -27,9 +28,28 @@ try { const code = await runAuthCli(['logout'], { print: () => {} }); send({ event: 'result', code }); } else if (action === 'login') { - send({ event: 'started' }); - await withCredentialsLock(async () => writeStoredCredentials({ clientId: 'new-client', accessToken: 'new-access', refreshToken: 'new-refresh', expiresAt: Date.now() + 3600000, scopes: [] }), { retryMs: 10 }); - send({ event: 'result' }); + globalThis.fetch = async () => { + send({ event: 'started' }); + return new Response(JSON.stringify({ access_token: 'new-access', refresh_token: 'new-refresh', expires_in: 3600, scope: 'read' }), { status: 200 }); + }; + const code = await runAuthCli(['login', '--client-id', 'new-client', '--redirect-port', '0'], { + print: () => {}, + openBrowser: async (url) => { + const authorization = new URL(url); + const callback = new URL(authorization.searchParams.get('redirect_uri')); + callback.hostname = '127.0.0.1'; + callback.searchParams.set('code', 'test-authorization-code'); + callback.searchParams.set('state', authorization.searchParams.get('state')); + await new Promise((resolve, reject) => { + http.get(callback, { agent: false }, (response) => { + response.resume(); + response.on('end', resolve); + }).on('error', reject); + }); + return true; + }, + }); + send({ event: 'result', code }); } else if (action === 'acquire') { send({ event: 'started' }); await withCredentialsLock(async () => send({ event: 'result' }), { retryMs: 10, timeoutMs: 3000 });