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 new file mode 100644 index 0000000..1591714 --- /dev/null +++ b/.github/workflows/auth-lock.yml @@ -0,0 +1,68 @@ +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' + - 'src/fs-native-extensions.d.ts' + - 'package*.json' + - '.github/workflows/auth-lock.yml' + push: + branches: [main] + paths: + - 'Dockerfile' + - '.dockerignore' + - 'scripts/mcp-smoke-test.mjs' + - '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 + + 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/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-credential-store.test.ts b/src/__tests__/auth-credential-store.test.ts index ee85d08..1c6ceca 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,36 @@ 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('does not take over a lock held by a live process just because it is old', async () => { + await withCredentialsLock(async () => { + 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/); + }); + }); + + it('retains the lock file and releases it for the next holder', async () => { + await withCredentialsLock(async () => { + expect(fs.existsSync(getCredentialsLockPath())).toBe(true); + }); + 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 5538cb2..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'; @@ -163,3 +164,238 @@ 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'], + }); + } + + + 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 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/); + 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..c98c640 --- /dev/null +++ b/src/__tests__/auth-multiprocess.test.ts @@ -0,0 +1,99 @@ +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'); + expect((await message(contender)).event).toBe('started'); + 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); + expect(readStoredCredentials()?.accessToken).toBe('old-access'); + const refreshed = message(refresh); + refresh.send('continue'); + expect((await refreshed).token).toBe('rotated-access'); + expect(await result).toEqual({ event: 'result', code: 0 }); + if (action === 'logout') expect(readStoredCredentials()).toBeUndefined(); + 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 () => { + 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..89f241b --- /dev/null +++ b/src/__tests__/fixtures/auth-worker.mjs @@ -0,0 +1,62 @@ +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'; + +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') { + 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 }); + } + process.disconnect(); +} catch (error) { + send({ event: 'error', message: error.message }); + process.exitCode = 1; + process.disconnect(); +} 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..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`. @@ -133,6 +134,49 @@ export function writeStoredCredentials(credentials: StoredCredentials): void { } } +const LOCK_FILE_NAME = `${CREDENTIALS_FILE_NAME}.lock`; +const CREDENTIALS_LOCK_TIMEOUT_MS = 75_000; +const CREDENTIALS_LOCK_RETRY_MS = 100; + +export interface CredentialsLockOptions { + retryMs?: number; + timeoutMs?: number; +} + +export function getCredentialsLockPath(): string { + return path.join(getConfigDir(), LOCK_FILE_NAME); +} + +/** 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 { + fs.mkdirSync(getConfigDir(), { recursive: true, mode: 0o700 }); + 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 { + try { + if (locked) nativeFs.unlock(fd); + } finally { + fs.closeSync(fd); + } + } +} + /** * 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())) { 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; +}