diff --git a/packages/api/scripts/seed.ts b/packages/api/scripts/seed.ts index 2dfa4b68..381ffc27 100644 --- a/packages/api/scripts/seed.ts +++ b/packages/api/scripts/seed.ts @@ -207,6 +207,7 @@ const meetings = await connect({ account: 'demo@acme-corp.com', credential: encrypt( JSON.stringify({ + auth: 'oauth', clientId: 'demo-client', accessToken: 'demo-access-token', refreshToken: null, @@ -223,6 +224,7 @@ const wiki = await connect({ account: 'demo@acme-corp.com · Acme', credential: encrypt( JSON.stringify({ + auth: 'oauth', clientId: 'demo-client', accessToken: 'demo-access-token', refreshToken: null, @@ -239,6 +241,7 @@ const tracker = await connect({ account: 'demo@acme-corp.com · Acme', credential: encrypt( JSON.stringify({ + auth: 'oauth', clientId: 'demo-client', accessToken: 'demo-access-token', refreshToken: null, diff --git a/packages/api/src/connections/cloudflare/built-in.test.ts b/packages/api/src/connections/cloudflare/built-in.test.ts index 94f3535e..a2895bbd 100644 --- a/packages/api/src/connections/cloudflare/built-in.test.ts +++ b/packages/api/src/connections/cloudflare/built-in.test.ts @@ -163,7 +163,7 @@ describe('the sign-in', () => { expect(toolCalls[0]?.headers.get('authorization')).toBe('Bearer access-1'); const created = createConnection.mock.calls[0]?.[0]; expect(created).toMatchObject({orgId: 'org-1', integrationId: 'cloudflare', account: 'alex@example.com', defaults: ['read']}); - expect(JSON.parse(String(created.credential).replace(/^enc:/, ''))).toMatchObject({clientId: 'client-1', accessToken: 'access-1', refreshToken: 'refresh-1'}); + expect(JSON.parse(String(created.credential).replace(/^enc:/, ''))).toMatchObject({auth: 'oauth', clientId: 'client-1', accessToken: 'access-1', refreshToken: 'refresh-1'}); expect(res.redirect).toHaveBeenCalledWith('https://app.example.com/org-1/connections/conn-1?added'); }); }); @@ -200,7 +200,7 @@ describe('keyConnectRoute', () => { expect(calls.map((call) => JSON.parse(call.body).method)).toEqual(['tools/list', 'tools/call']); expect(findAccountConnection).toHaveBeenCalledWith(expect.objectContaining({orgId: 'org-1', userId: 'user-1'}), {integrationId: 'cloudflare', account: 'Acme', providerAccountId: 'account:acc-1'}); expect(createConnection.mock.calls[0]?.[0]).toMatchObject({account: 'Acme', providerAccountId: 'account:acc-1'}); - expect(JSON.parse(String(createConnection.mock.calls[0]?.[0].credential).replace(/^enc:/, ''))).toEqual({auth: 'key', key: 'account-token'}); + expect(JSON.parse(String(createConnection.mock.calls[0]?.[0].credential).replace(/^enc:/, ''))).toEqual({auth: 'token', token: 'account-token'}); expect(connection).toMatchObject({id: 'conn-1', account: 'Acme'}); }); diff --git a/packages/api/src/connections/custom/custom-mcp.ts b/packages/api/src/connections/custom/custom-mcp.ts index 1d12120d..bca912a8 100644 --- a/packages/api/src/connections/custom/custom-mcp.ts +++ b/packages/api/src/connections/custom/custom-mcp.ts @@ -6,8 +6,9 @@ import {mcpToolReadsOnly, type McpTool} from '@proxy/integrations'; import {readStoredJson} from '../../utils/stored-json'; import {callMcpTool, listMcpTools} from '../mcp/mcp-client'; -import {mcpCredentialSchema, mcpEndpointsSchema, type McpEndpoint, type McpServer} from '../mcp/mcp-oauth'; -import {withMcpToken} from '../mcp/mcp-session'; +import {noAuthSchema, oauthAuthSchema, tokenAuthSchema} from '../mcp/mcp-credential'; +import {mcpEndpointsSchema, type McpEndpoint, type McpServer} from '../mcp/mcp-oauth'; +import {withMcpSignIn} from '../mcp/mcp-session'; /** * A custom MCP server, by its address: connected with no sign-in where the server asks for none, @@ -16,13 +17,14 @@ import {withMcpToken} from '../mcp/mcp-session'; * the agent as the server wrote it (`mcp-discovery.ts` finds out how a server is signed in to). */ -/** What a custom MCP connection stores, encrypted: the server's address and how it is signed in to. */ -export const customCredentialSchema = z.discriminatedUnion('auth', [ - z.object({auth: z.literal('none'), url: z.string()}), - z.object({auth: z.literal('token'), url: z.string(), token: z.string()}), - // Signed in: the server's endpoints beside the tokens, so refreshing needs nothing else. - z.object({auth: z.literal('oauth'), url: z.string(), server: mcpEndpointsSchema, ...mcpCredentialSchema.shape}), -]); +// Signed in: the server's endpoints beside the tokens, so refreshing needs nothing else. +const customSignInSchema = oauthAuthSchema.extend({url: z.string(), server: mcpEndpointsSchema}); + +/** + * What a custom MCP connection stores, encrypted: an MCP credential (`mcp-credential.ts`) with the + * server's address beside it. + */ +export const customCredentialSchema = z.discriminatedUnion('auth', [noAuthSchema.extend({url: z.string()}), tokenAuthSchema.extend({url: z.string()}), customSignInSchema]); export type CustomCredential = z.infer; @@ -68,7 +70,7 @@ function withCustomServer(connection: StoredConnection, use: (server: McpEndp return $(await use(customEndpoint(credential.url), credential.token)); } const server = customServer(credential); - return $(await withMcpToken(server, connection, (accessToken) => use(server, accessToken))); + return $(await withMcpSignIn(server, connection, customSignInSchema, (accessToken) => use(server, accessToken))); }); } diff --git a/packages/api/src/connections/custom/route.test.ts b/packages/api/src/connections/custom/route.test.ts index 819d39a5..b8a32333 100644 --- a/packages/api/src/connections/custom/route.test.ts +++ b/packages/api/src/connections/custom/route.test.ts @@ -303,7 +303,7 @@ describe('handleConnectCustomMcpRoute', () => { ] as const) { const res = await connect({name: 'Web search', url, token: 'key-1234'}); expect(res.sent).toMatchObject({kind: 'connected', connection: {name: 'Web search', account}}); - expect(createConnection.mock.calls.at(-1)?.[0]).toMatchObject({integrationId, name: 'Web search', credential: `enc:${JSON.stringify({auth: 'key', key: 'key-1234'})}`}); + expect(createConnection.mock.calls.at(-1)?.[0]).toMatchObject({integrationId, name: 'Web search', credential: `enc:${JSON.stringify({auth: 'token', token: 'key-1234'})}`}); } expect(probeMcpServer).not.toHaveBeenCalled(); }); @@ -314,7 +314,7 @@ describe('handleConnectCustomMcpRoute', () => { const res = await connect({name: 'Linear test', url: 'https://mcp.linear.app/mcp', token: 'key-1234'}); expect(createConnection).not.toHaveBeenCalled(); - expect(renewConnection.mock.calls[0]?.[0]).toMatchObject({connectionId: 'linear-1', credential: `enc:${JSON.stringify({auth: 'key', key: 'key-1234'})}`}); + expect(renewConnection.mock.calls[0]?.[0]).toMatchObject({connectionId: 'linear-1', credential: `enc:${JSON.stringify({auth: 'token', token: 'key-1234'})}`}); expect(updateConnectionName).not.toHaveBeenCalled(); expect(res.sent).toMatchObject({kind: 'connected', connection: {id: 'linear-1', name: 'Work', account: 'alex@example.com · Acme'}}); }); @@ -324,7 +324,7 @@ describe('handleConnectCustomMcpRoute', () => { const res = await connect({name: 'Web search', url: 'https://mcp.exa.ai/mcp?exaApiKey=key-5678'}); expect(res.sent).toMatchObject({kind: 'connected', connection: {name: 'Web search', account: 'API key ending 5678'}}); - expect(createConnection.mock.calls.at(-1)?.[0]).toMatchObject({integrationId: 'exa', credential: `enc:${JSON.stringify({auth: 'key', key: 'key-5678'})}`}); + expect(createConnection.mock.calls.at(-1)?.[0]).toMatchObject({integrationId: 'exa', credential: `enc:${JSON.stringify({auth: 'token', token: 'key-5678'})}`}); }); test('a token for a built-in integration that takes no key is refused, rather than dropped for a sign-in', async () => { diff --git a/packages/api/src/connections/exa/built-in.test.ts b/packages/api/src/connections/exa/built-in.test.ts index e0b3947e..cc1c77a9 100644 --- a/packages/api/src/connections/exa/built-in.test.ts +++ b/packages/api/src/connections/exa/built-in.test.ts @@ -249,7 +249,7 @@ describe('keyConnectRoute', () => { const created = createConnection.mock.calls[0]?.[0]; expect(created).toMatchObject({orgId: 'org-1', integrationId: 'exa', account: 'API key ending 1234', defaults: ['search', 'fetch']}); expect(created.name).toBeUndefined(); - expect(JSON.parse(String(created.credential).replace(/^enc:/, ''))).toEqual({auth: 'key', key: 'exa-key-1234'}); + expect(JSON.parse(String(created.credential).replace(/^enc:/, ''))).toEqual({auth: 'token', token: 'exa-key-1234'}); expect(connection).toMatchObject({id: 'conn-1', name: null, unavailable: []}); }); @@ -278,7 +278,7 @@ describe('keyConnectRoute', () => { const connection = (await connectWithKey({connection: 'conn-0', key: 'exa-key-5678'})).unwrap(); expect(createConnection).not.toHaveBeenCalled(); - expect(renewConnection.mock.calls[0]?.[0]).toMatchObject({connectionId: 'conn-0', account: 'API key ending 5678', credential: `enc:${JSON.stringify({auth: 'key', key: 'exa-key-5678'})}`}); + expect(renewConnection.mock.calls[0]?.[0]).toMatchObject({connectionId: 'conn-0', account: 'API key ending 5678', credential: `enc:${JSON.stringify({auth: 'token', token: 'exa-key-5678'})}`}); expect(updateConnectionName).not.toHaveBeenCalled(); expect(connection).toMatchObject({id: 'conn-0', name: 'Team Exa'}); }); diff --git a/packages/api/src/connections/granola/built-in.test.ts b/packages/api/src/connections/granola/built-in.test.ts index e3358a3c..7ee69b37 100644 --- a/packages/api/src/connections/granola/built-in.test.ts +++ b/packages/api/src/connections/granola/built-in.test.ts @@ -142,7 +142,7 @@ describe('handleGranolaCallbackRoute', () => { ).toBe(authorizeUrl.searchParams.get('code_challenge') ?? ''); const created = createConnection.mock.calls[0]?.[0]; expect(created).toMatchObject({orgId: 'org-1', integrationId: 'granola', account: 'alex@example.com', defaults: ['readNotes', 'readTranscripts']}); - expect(JSON.parse(String(created.credential).replace(/^enc:/, ''))).toMatchObject({clientId: 'client-1', accessToken: 'access-1', refreshToken: 'refresh-1'}); + expect(JSON.parse(String(created.credential).replace(/^enc:/, ''))).toMatchObject({auth: 'oauth', clientId: 'client-1', accessToken: 'access-1', refreshToken: 'refresh-1'}); expect(res.clearCookie).toHaveBeenCalled(); expect(res.redirect).toHaveBeenCalledWith('https://app.example.com/org-1/connections/conn-1?added'); }); diff --git a/packages/api/src/connections/linear/built-in.test.ts b/packages/api/src/connections/linear/built-in.test.ts index 5e4fcaa4..d7055573 100644 --- a/packages/api/src/connections/linear/built-in.test.ts +++ b/packages/api/src/connections/linear/built-in.test.ts @@ -157,7 +157,7 @@ describe('handleLinearCallbackRoute', () => { ]); const created = createConnection.mock.calls[0]?.[0]; expect(created).toMatchObject({orgId: 'org-1', integrationId: 'linear', account: 'alex@example.com · Acme', defaults: ['read']}); - expect(JSON.parse(String(created.credential).replace(/^enc:/, ''))).toMatchObject({clientId: 'client-1', accessToken: 'access-1', refreshToken: 'refresh-1'}); + expect(JSON.parse(String(created.credential).replace(/^enc:/, ''))).toMatchObject({auth: 'oauth', clientId: 'client-1', accessToken: 'access-1', refreshToken: 'refresh-1'}); expect(res.redirect).toHaveBeenCalledWith('https://app.example.com/org-1/connections/conn-1?added'); }); @@ -296,7 +296,7 @@ describe('keyConnectRoute', () => { }); const created = createConnection.mock.calls[0]?.[0]; expect(created).toMatchObject({integrationId: 'linear', account: 'alex@example.com · Acme', defaults: ['read']}); - expect(JSON.parse(String(created.credential).replace(/^enc:/, ''))).toEqual({auth: 'key', key: 'lin_api_1234'}); + expect(JSON.parse(String(created.credential).replace(/^enc:/, ''))).toEqual({auth: 'token', token: 'lin_api_1234'}); expect(connection).toMatchObject({id: 'conn-1', account: 'alex@example.com · Acme'}); }); diff --git a/packages/api/src/connections/mcp/mcp-connect.ts b/packages/api/src/connections/mcp/mcp-connect.ts index 5dd138ce..f61d4ff4 100644 --- a/packages/api/src/connections/mcp/mcp-connect.ts +++ b/packages/api/src/connections/mcp/mcp-connect.ts @@ -14,8 +14,8 @@ import {saveConnection, signInFlow, signInRoutes, type Connected, type SaveOptio import type {ApiIntegration} from '../integration'; import {requireManaged, type ManagingViewer} from '../managed'; import type {BuiltInMcp, ProviderAccount} from './built-in'; -import {exchangeMcpCode, mcpAuthorizeUrl, registerMcpClient, type McpCredential, type McpServer} from './mcp-oauth'; -import type {McpKeyCredential} from './mcp-session'; +import {exchangeMcpCode, mcpAuthorizeUrl, registerMcpClient, type McpServer} from './mcp-oauth'; +import type {BuiltInCredential} from './mcp-credential'; /** * Connecting an integration built on its MCP server: by signing in to it, as Granola, Notion and @@ -63,9 +63,10 @@ function builtInSignIn(builtIn: BuiltInMcp) { keptSchema, start: (request: SignInRequest) => startMcpSignIn(server, request, {}), finish: ({redirectUri, code, verifier, kept}: {redirectUri: string; code: string; verifier: string; kept: Kept}) => - Do, ApiError>(async ($) => { - const credential = $(await exchangeMcpCode(server, {clientId: kept.clientId, redirectUri, code, verifier})); - const account = $(await accountOf(builtIn, credential.accessToken)); + Do, ApiError>(async ($) => { + const tokens = $(await exchangeMcpCode(server, {clientId: kept.clientId, redirectUri, code, verifier})); + const credential: BuiltInCredential = {auth: 'oauth', ...tokens}; + const account = $(await accountOf(builtIn, tokens.accessToken)); return {...account, credential, defaults: builtIn.defaults, ...anonymity(builtIn), ...(kept.name ? {name: kept.name} : {})}; }), }; @@ -138,7 +139,7 @@ export function connectWithKey(builtIn: BuiltInMcp, viewer: ManagingViewer, args return $(Err(ApiErr.validationError('An API key has no spaces'))); } const account = $(await checkedKeyAccount(builtIn, args.key)); - const credential: McpKeyCredential = {auth: 'key', key: args.key}; + const credential: BuiltInCredential = {auth: 'token', token: args.key}; const connected = {...account, credential, defaults: builtIn.defaults, ...anonymity(builtIn), ...(args.name === undefined ? {} : {name: args.name})}; const {row} = $(await saveConnection(viewer, builtIn.integrationId, connected, {shared: args.shared, connectionId: args.connectionId})); // A key opens all of the integration: how the response reads the credential, which never leaves the api. diff --git a/packages/api/src/connections/mcp/mcp-credential.ts b/packages/api/src/connections/mcp/mcp-credential.ts new file mode 100644 index 00000000..89f355d7 --- /dev/null +++ b/packages/api/src/connections/mcp/mcp-credential.ts @@ -0,0 +1,35 @@ +import {z} from 'zod'; + +import {mcpTokensSchema} from './mcp-oauth'; + +/** + * What every connection to an MCP server stores, encrypted, built in or custom, in one shape: how + * it signs in (`auth`) and what with. `none`: nothing, as a custom server that asks for no sign-in. + * `token`: a token or API key, sent as the bearer token, or as written where it starts with its + * scheme, as `Basic …` (`mcp-client.ts`). `oauth`: a sign-in, its client and tokens, refreshed as + * they run out (`mcp-session.ts`). A custom server's adds its address, and a sign-in's the server's + * endpoints (`custom/custom-mcp.ts`). + */ + +export const noAuthSchema = z.object({auth: z.literal('none')}); + +export const tokenAuthSchema = z.object({auth: z.literal('token'), token: z.string()}); + +export const oauthAuthSchema = z.object({auth: z.literal('oauth'), ...mcpTokensSchema.shape}); + +/** What a connection of an integration built on its MCP server stores: a key, or a sign-in. */ +export const builtInCredentialSchema = z.discriminatedUnion('auth', [tokenAuthSchema, oauthAuthSchema]); + +export type BuiltInCredential = z.infer; + +export type OAuthCredential = z.infer; + +// Before every MCP credential said how it signs in, an integration built in stored a key as +// `{auth: 'key', key}` and a sign-in's tokens bare. Read as they are now until the data migration +// `unify-mcp-credentials` has rewritten them, on every instance; it, and these, can then go. +const legacyKeySchema = z.object({auth: z.literal('key'), key: z.string()}).transform(({key}): BuiltInCredential => ({auth: 'token', token: key})); + +const legacyTokensSchema = mcpTokensSchema.transform((tokens): BuiltInCredential => ({auth: 'oauth', ...tokens})); + +/** A built-in integration's credential as stored, in the shape it has now or the one it had before. */ +export const storedBuiltInCredentialSchema = z.union([builtInCredentialSchema, legacyKeySchema, legacyTokensSchema]); diff --git a/packages/api/src/connections/mcp/mcp-oauth.ts b/packages/api/src/connections/mcp/mcp-oauth.ts index 57587be8..5a78ff12 100644 --- a/packages/api/src/connections/mcp/mcp-oauth.ts +++ b/packages/api/src/connections/mcp/mcp-oauth.ts @@ -64,15 +64,15 @@ const TIMEOUT_MS = 15_000; // Refreshed a minute early, so a token doesn't run out between the check and the call. const EXPIRY_MARGIN_MS = 60_000; -/** What a connection to an MCP server stores, encrypted: the client it signed in with and its tokens. */ -export const mcpCredentialSchema = z.object({ +/** What a sign-in to an MCP server leaves: the client it signed in with and its tokens, kept in the connection's credential (`mcp-credential.ts`). */ +export const mcpTokensSchema = z.object({ clientId: z.string(), accessToken: z.string(), refreshToken: z.string().nullable(), expiresAt: z.string().nullable(), }); -export type McpCredential = z.infer; +export type McpTokens = z.infer; const registrationSchema = z.object({client_id: z.string().min(1)}); @@ -127,7 +127,7 @@ export function mcpAuthorizeUrl(server: McpServer, args: {clientId: string; redi return url.toString(); } -async function requestTokens(server: McpServer, clientId: string, params: Record, previousRefreshToken: string | null): Promise> { +async function requestTokens(server: McpServer, clientId: string, params: Record, previousRefreshToken: string | null): Promise> { const tokens = await checkedRequest( server.tokenUrl, { @@ -147,18 +147,18 @@ async function requestTokens(server: McpServer, clientId: string, params: Record } /** Trades the code the server sent back for the connection's first tokens. */ -export function exchangeMcpCode(server: McpServer, args: {clientId: string; redirectUri: string; code: string; verifier: string}): Promise> { +export function exchangeMcpCode(server: McpServer, args: {clientId: string; redirectUri: string; code: string; verifier: string}): Promise> { return requestTokens(server, args.clientId, {grant_type: 'authorization_code', code: args.code, redirect_uri: args.redirectUri, code_verifier: args.verifier}, null); } /** New tokens for a connection whose access token ran out; turned down once the server revoked it. */ -export async function refreshMcpTokens(server: McpServer, credential: McpCredential): Promise> { +export async function refreshMcpTokens(server: McpServer, credential: McpTokens): Promise> { if (!credential.refreshToken) { return Err(ApiErr.credentialsRejected()); } return requestTokens(server, credential.clientId, {grant_type: 'refresh_token', refresh_token: credential.refreshToken}, credential.refreshToken); } -export function isExpiring(credential: McpCredential): boolean { +export function isExpiring(credential: McpTokens): boolean { return credential.expiresAt !== null && Date.parse(credential.expiresAt) - EXPIRY_MARGIN_MS < Date.now(); } diff --git a/packages/api/src/connections/mcp/mcp-session.test.ts b/packages/api/src/connections/mcp/mcp-session.test.ts index 109c1def..745150b3 100644 --- a/packages/api/src/connections/mcp/mcp-session.test.ts +++ b/packages/api/src/connections/mcp/mcp-session.test.ts @@ -1,6 +1,8 @@ import {beforeEach, describe, expect, mock, test} from 'bun:test'; import {Err, Ok, type Result} from 'ts-results-es'; +import {z} from 'zod'; + import {ApiErr, type ApiError} from '@proxy/utils'; import type {McpServer} from './mcp-oauth'; @@ -42,7 +44,7 @@ const SERVER: McpServer = { const fresh = {clientId: 'client-1', accessToken: 'access-2', refreshToken: 'refresh-2', expiresAt: new Date(Date.now() + 3600_000).toISOString()}; function connectionWith(expiresAt: string | null) { - const credential = {clientId: 'client-1', accessToken: 'access-1', refreshToken: 'refresh-1', expiresAt}; + const credential = {auth: 'oauth', clientId: 'client-1', accessToken: 'access-1', refreshToken: 'refresh-1', expiresAt}; return {id: 'conn-1', credential: `enc:${JSON.stringify(credential)}`}; } @@ -69,7 +71,17 @@ describe('callMcpToolFor', () => { await callMcpToolFor(SERVER, connection, 'list_meetings', {}); expect(callMcpTool).toHaveBeenCalledWith(SERVER, 'access-2', 'list_meetings', {}); - expect(updateConnectionCredential).toHaveBeenCalledWith({connectionId: 'conn-1', credential: `enc:${JSON.stringify(fresh)}`, previous: connection.credential}); + expect(updateConnectionCredential).toHaveBeenCalledWith({connectionId: 'conn-1', credential: `enc:${JSON.stringify({auth: 'oauth', ...fresh})}`, previous: connection.credential}); + }); + + test('tokens stored bare, as before every MCP credential said how it signs in, are read, and saved in the shape they have now', async () => { + const {callMcpToolFor} = await import('./mcp-session'); + const bare = {clientId: 'client-1', accessToken: 'access-1', refreshToken: 'refresh-1', expiresAt: new Date(Date.now() + 10_000).toISOString()}; + const connection = {id: 'conn-1', credential: `enc:${JSON.stringify(bare)}`}; + await callMcpToolFor(SERVER, connection, 'list_meetings', {}); + + expect(refreshMcpTokens).toHaveBeenCalledWith(SERVER, {auth: 'oauth', ...bare}); + expect(updateConnectionCredential.mock.calls[0]?.[0]).toMatchObject({credential: `enc:${JSON.stringify({auth: 'oauth', ...fresh})}`}); }); test('calls at once on a running-out token share one refresh', async () => { @@ -91,8 +103,9 @@ describe('callMcpToolFor', () => { expect((await callMcpToolFor(SERVER, connectionWith(null), 'list_meetings', {})).unwrapErr().kind).toBe('credentials_rejected'); }); - test('whatever else the credential holds, as a custom server’s address, is kept beside the new tokens', async () => { - const {callMcpToolFor} = await import('./mcp-session'); + test('a custom server’s sign-in keeps its address beside the new tokens', async () => { + const {withMcpSignIn} = await import('./mcp-session'); + const {oauthAuthSchema} = await import('./mcp-credential'); const credential = { auth: 'oauth', url: 'https://mcp.example.com/mcp', @@ -102,7 +115,7 @@ describe('callMcpToolFor', () => { expiresAt: new Date(Date.now() + 10_000).toISOString(), }; const connection = {id: 'conn-1', credential: `enc:${JSON.stringify(credential)}`}; - await callMcpToolFor(SERVER, connection, 'search', {}); + await withMcpSignIn(SERVER, connection, oauthAuthSchema.extend({url: z.string()}), (accessToken) => callMcpTool(SERVER, accessToken, 'search', {})); const saved = updateConnectionCredential.mock.calls[0]?.[0] as {credential: string}; expect(JSON.parse(saved.credential.replace(/^enc:/, ''))).toEqual({auth: 'oauth', url: 'https://mcp.example.com/mcp', ...fresh}); @@ -119,7 +132,14 @@ describe('callMcpToolFor', () => { }); describe('callMcpToolFor with an API key', () => { - const connection = {id: 'conn-2', credential: `enc:${JSON.stringify({auth: 'key', key: 'exa-key-1'})}`}; + const connection = {id: 'conn-2', credential: `enc:${JSON.stringify({auth: 'token', token: 'exa-key-1'})}`}; + + test('a key stored as before, `{auth: "key"}`, is sent as it is', async () => { + const {callMcpToolFor} = await import('./mcp-session'); + const legacy = {id: 'conn-2', credential: `enc:${JSON.stringify({auth: 'key', key: 'exa-key-1'})}`}; + expect((await callMcpToolFor(SERVER, legacy, 'web_search_exa', {})).unwrap()).toBe('answer'); + expect(callMcpTool).toHaveBeenCalledWith(SERVER, 'exa-key-1', 'web_search_exa', {}); + }); test('sends the key as the token, and never refreshes it', async () => { const {callMcpToolFor} = await import('./mcp-session'); diff --git a/packages/api/src/connections/mcp/mcp-session.ts b/packages/api/src/connections/mcp/mcp-session.ts index 3d77a67c..c899c813 100644 --- a/packages/api/src/connections/mcp/mcp-session.ts +++ b/packages/api/src/connections/mcp/mcp-session.ts @@ -1,52 +1,67 @@ import {Err, type Result} from 'ts-results-es'; -import {z} from 'zod'; +import type {z} from 'zod'; import {ApiErr, type ApiError} from '@proxy/utils'; import {callWithToken, type TokenRefresher} from '../token-session'; import {callMcpTool} from './mcp-client'; -import {isExpiring, mcpCredentialSchema, refreshMcpTokens, type McpServer} from './mcp-oauth'; +import {storedBuiltInCredentialSchema, type BuiltInCredential, type OAuthCredential} from './mcp-credential'; +import {isExpiring, refreshMcpTokens, type McpServer} from './mcp-oauth'; type StoredConnection = {id: string; credential: string | null}; -/** What a connection made with an API key stores, encrypted, as Exa's and Parallel's may be: the key, sent as the bearer token. */ -export const mcpKeyCredentialSchema = z.object({auth: z.literal('key'), key: z.string()}); +// A credential the session can send: a token or key, or a sign-in's, with whatever else it holds +// beside them, as a custom server's address and endpoints, kept as it is when the tokens are replaced. +type Sendable = Extract | OAuthCredential; -export type McpKeyCredential = z.infer; - -// An API key; or the tokens, and whatever else the credential holds beside them, as a custom -// server's address and endpoints, kept as it is when the tokens are replaced. -const storedCredentialSchema = z.union([mcpKeyCredentialSchema, mcpCredentialSchema.loose()]); - -type StoredCredential = z.infer; - -function isKey(credential: StoredCredential): credential is McpKeyCredential { - return credential.auth === 'key'; +function isSignIn(credential: C): credential is C & OAuthCredential { + return credential.auth === 'oauth'; } -// A key is sent as it is and never refreshed: one the server turns down has to be replaced. -function mcpRefresher(server: McpServer): TokenRefresher { +// A token or key is sent as it is and never refreshed: one the server turns down has to be replaced. +function mcpRefresher(server: McpServer, schema: z.ZodType): TokenRefresher { return { name: server.name, - schema: storedCredentialSchema, - isExpiring: (credential) => !isKey(credential) && isExpiring(credential), + schema, + isExpiring: (credential) => isSignIn(credential) && isExpiring(credential), refresh: async (credential) => { - if (isKey(credential)) { + if (!isSignIn(credential)) { return Err(ApiErr.credentialsRejected()); } - return (await refreshMcpTokens(server, credential)).map((tokens) => ({...credential, ...tokens})); + return (await refreshMcpTokens(server, credential)).map((tokens): C => ({...credential, ...tokens})); }, }; } +// What is sent: the token or key, or the sign-in's access token. +function sent(credential: Sendable): string { + if (credential.auth === 'oauth') { + return credential.accessToken; + } + return credential.token; +} + +/** + * Runs `use` with a custom server's sign-in, read with `schema`, which keeps its address and + * endpoints beside the tokens when they are refreshed, as `withMcpToken` does (`custom/custom-mcp.ts`). + */ +export function withMcpSignIn( + server: McpServer, + connection: StoredConnection, + schema: z.ZodType, + use: (accessToken: string) => Promise>, +): Promise> { + return callWithToken(mcpRefresher(server, schema), connection, (credential) => use(sent(credential))); +} + /** - * Runs `use` with a connection's access token, or its API key: a token refreshed first when it is - * running out, and once more when the server turns it down anyway. A connection the server won't - * refresh any more, or whose key it turns down, is `credentials_rejected`, and has to be signed in - * to again or given a new key. + * Runs `use` with a built-in integration's connection's access token, or its key: a sign-in's + * refreshed first when it is running out, and once more when the server turns it down anyway. A + * connection the server won't refresh any more, or whose key it turns down, is + * `credentials_rejected`, and has to be signed in to again or given a new key. */ export function withMcpToken(server: McpServer, connection: StoredConnection, use: (accessToken: string) => Promise>): Promise> { - return callWithToken(mcpRefresher(server), connection, (credential) => use(isKey(credential) ? credential.key : credential.accessToken)); + return withMcpSignIn(server, connection, storedBuiltInCredentialSchema, use); } /** Calls one of a server's tools with a connection's token, refreshed as `withMcpToken` does. */ diff --git a/packages/api/src/connections/mcp/unify-credentials.test.ts b/packages/api/src/connections/mcp/unify-credentials.test.ts new file mode 100644 index 00000000..800417d8 --- /dev/null +++ b/packages/api/src/connections/mcp/unify-credentials.test.ts @@ -0,0 +1,85 @@ +import {beforeEach, describe, expect, mock, test} from 'bun:test'; +import {Err, Ok, type Result} from 'ts-results-es'; + +import {ApiErr, type ApiError} from '@proxy/utils'; + +const listIntegrationCredentials = mock(); +const rewriteConnectionCredential = mock(); +mock.module('@proxy/db/connection', () => ({listIntegrationCredentials, rewriteConnectionCredential})); + +const error = mock(); +mock.module('../../observability/log', () => ({ + log: {debug: mock(), info: mock(), warn: mock(), error}, + serializeError: mock(() => ({})), +})); + +// Readable stand-ins for encryption; one stored as "garbled" can't be decrypted. +mock.module('../../utils/secret-crypto', () => ({ + encryptSecret: (plaintext: string): Result => Ok(`enc:${plaintext}`), + decryptSecret: (stored: string): Result => (stored === 'garbled' ? Err(ApiErr.internalError(new Error('bad key'))) : Ok(stored.replace(/^enc:/, ''))), +})); + +mock.module('../built-in-mcp', () => ({builtInMcps: () => [{integrationId: 'notion'}, {integrationId: 'exa'}]})); + +const {unifyMcpCredentials} = await import('./unify-credentials'); + +const tokens = {clientId: 'client-1', accessToken: 'access-1', refreshToken: 'refresh-1', expiresAt: null}; +const stored = (credential: object) => `enc:${JSON.stringify(credential)}`; + +beforeEach(() => { + mock.clearAllMocks(); + rewriteConnectionCredential.mockResolvedValue(Ok(true)); +}); + +describe('unifyMcpCredentials', () => { + test('rewrites a key and bare tokens in the shape they have now, each only over the one read, and leaves one in it already', async () => { + listIntegrationCredentials.mockResolvedValue( + Ok([ + {id: 'exa-1', credential: stored({auth: 'key', key: 'exa-key-1'})}, + {id: 'notion-1', credential: stored(tokens)}, + {id: 'notion-2', credential: stored({auth: 'oauth', ...tokens})}, + ]), + ); + + expect((await unifyMcpCredentials()).isOk()).toBe(true); + + expect(listIntegrationCredentials).toHaveBeenCalledWith(['notion', 'exa']); + expect(rewriteConnectionCredential.mock.calls.map((call) => call[0])).toEqual([ + {connectionId: 'exa-1', previous: stored({auth: 'key', key: 'exa-key-1'}), credential: stored({auth: 'token', token: 'exa-key-1'})}, + {connectionId: 'notion-1', previous: stored(tokens), credential: stored({auth: 'oauth', ...tokens})}, + ]); + }); + + test('one changed meanwhile, or not saved, is left for the next start, the rest still rewritten', async () => { + listIntegrationCredentials.mockResolvedValue( + Ok([ + {id: 'exa-1', credential: stored({auth: 'key', key: 'exa-key-1'})}, + {id: 'exa-2', credential: stored({auth: 'key', key: 'exa-key-2'})}, + {id: 'exa-3', credential: stored({auth: 'key', key: 'exa-key-3'})}, + ]), + ); + rewriteConnectionCredential.mockResolvedValueOnce(Ok(false)).mockResolvedValueOnce(Err(ApiErr.dbError(new Error('down')))); + + expect((await unifyMcpCredentials()).isErr()).toBe(true); + expect(rewriteConnectionCredential).toHaveBeenCalledTimes(3); + }); + + test('one that can’t be read is logged and passed over, as it was unusable before too', async () => { + listIntegrationCredentials.mockResolvedValue( + Ok([ + {id: 'notion-1', credential: 'garbled'}, + {id: 'exa-1', credential: stored({auth: 'key', key: 'exa-key-1'})}, + ]), + ); + + expect((await unifyMcpCredentials()).isOk()).toBe(true); + expect(error).toHaveBeenCalledTimes(1); + expect(rewriteConnectionCredential).toHaveBeenCalledTimes(1); + }); + + test('listing them failing has the migration tried again', async () => { + listIntegrationCredentials.mockResolvedValue(Err(ApiErr.dbError(new Error('down')))); + expect((await unifyMcpCredentials()).isErr()).toBe(true); + expect(rewriteConnectionCredential).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/api/src/connections/mcp/unify-credentials.ts b/packages/api/src/connections/mcp/unify-credentials.ts new file mode 100644 index 00000000..25155aec --- /dev/null +++ b/packages/api/src/connections/mcp/unify-credentials.ts @@ -0,0 +1,72 @@ +import {Err, Ok, type Result} from 'ts-results-es'; + +import {ApiErr, type ApiError, Do} from '@proxy/utils'; +import {listIntegrationCredentials, rewriteConnectionCredential, type StoredCredentialRow} from '@proxy/db/connection'; + +import {worthRetrying} from '../../data-migrations/retry'; +import {log, serializeError} from '../../observability/log'; +import {encryptSecret} from '../../utils/secret-crypto'; +import {readStoredJson} from '../../utils/stored-json'; +import {builtInMcps} from '../built-in-mcp'; +import {builtInCredentialSchema, storedBuiltInCredentialSchema} from './mcp-credential'; + +/** + * The data migration `unify-mcp-credentials` (`data-migrations/run.ts`): every connection of an + * integration built on its MCP server given its credential in the shape every MCP credential has + * now (`mcp-credential.ts`), a key as `{auth: 'token', token}` rather than `{auth: 'key', key}`, and + * a sign-in's tokens under `{auth: 'oauth'}` rather than bare. A custom server's were in it already. + * Each is rewritten only while it is still the one read, so tokens refreshed meanwhile are never + * undone; one that changed meanwhile, or couldn't be saved, has the migration tried again on the + * next start. One that can't be read at all, as after a change of `ENCRYPTION_KEY`, is logged and + * passed over, as it was unusable before too. + */ + +// What became of one connection's credential. +type Rewrite = 'rewritten' | 'current' | 'changed'; + +function rewrite(row: StoredCredentialRow): Promise> { + return Do(async ($) => { + if (readStoredJson(row.credential, builtInCredentialSchema).isOk()) { + return 'current' as const; + } + const credential = $(readStoredJson(row.credential, storedBuiltInCredentialSchema)); + const encrypted = $(encryptSecret(JSON.stringify(credential))); + const saved = $(await rewriteConnectionCredential({connectionId: row.id, previous: row.credential, credential: encrypted})); + return saved ? ('rewritten' as const) : ('changed' as const); + }); +} + +/** Rewrites every built-in MCP connection's credential in the shape it has now. */ +export async function unifyMcpCredentials(): Promise> { + const rows = await listIntegrationCredentials(builtInMcps().map((builtIn) => builtIn.integrationId)); + if (rows.isErr()) { + return Err(rows.error); + } + let retry = 0; + let rewritten = 0; + for (const row of rows.value) { + const result = await rewrite(row); + if (result.isErr()) { + const details = {connectionId: row.id, kind: result.error.kind, ...('cause' in result.error ? serializeError(result.error.cause) : {})}; + if (!worthRetrying(result.error)) { + log.error('An MCP credential can’t be read, so it stays as it is', details); + continue; + } + retry += 1; + log.warn('Rewriting an MCP credential failed, to be tried again on the next start', details); + continue; + } + if (result.value === 'changed') { + retry += 1; + continue; + } + if (result.value === 'rewritten') { + rewritten += 1; + } + } + log.info('Rewrote MCP credentials in their current shape', {rewritten, retry}); + if (retry > 0) { + return Err(ApiErr.internalError(new Error(`Rewriting ${retry} MCP credentials is left for the next start`))); + } + return Ok(undefined); +} diff --git a/packages/api/src/connections/notion/built-in.test.ts b/packages/api/src/connections/notion/built-in.test.ts index 9807483e..bc1d9c4a 100644 --- a/packages/api/src/connections/notion/built-in.test.ts +++ b/packages/api/src/connections/notion/built-in.test.ts @@ -137,7 +137,7 @@ describe('handleNotionCallbackRoute', () => { expect(JSON.parse(toolCall?.body ?? '{}').params).toEqual({name: 'notion-get-self', arguments: {}}); const created = createConnection.mock.calls[0]?.[0]; expect(created).toMatchObject({orgId: 'org-1', integrationId: 'notion', account: 'alex@example.com · Acme', defaults: ['read']}); - expect(JSON.parse(String(created.credential).replace(/^enc:/, ''))).toMatchObject({clientId: 'client-1', accessToken: 'access-1', refreshToken: 'refresh-1'}); + expect(JSON.parse(String(created.credential).replace(/^enc:/, ''))).toMatchObject({auth: 'oauth', clientId: 'client-1', accessToken: 'access-1', refreshToken: 'refresh-1'}); expect(res.redirect).toHaveBeenCalledWith('https://app.example.com/org-1/connections/conn-1?added'); }); diff --git a/packages/api/src/connections/parallel/built-in.test.ts b/packages/api/src/connections/parallel/built-in.test.ts index 7162c784..1dc481ab 100644 --- a/packages/api/src/connections/parallel/built-in.test.ts +++ b/packages/api/src/connections/parallel/built-in.test.ts @@ -222,7 +222,7 @@ describe('keyConnectRoute', () => { const created = createConnection.mock.calls[0]?.[0]; expect(created).toMatchObject({orgId: 'org-1', integrationId: 'parallel', account: 'API key ending 1234', defaults: ['search', 'fetch']}); expect(created.name).toBeUndefined(); - expect(JSON.parse(String(created.credential).replace(/^enc:/, ''))).toEqual({auth: 'key', key: 'pk-1234'}); + expect(JSON.parse(String(created.credential).replace(/^enc:/, ''))).toEqual({auth: 'token', token: 'pk-1234'}); expect(connection).toMatchObject({id: 'conn-1', name: null, unavailable: []}); }); @@ -238,7 +238,7 @@ describe('keyConnectRoute', () => { const connection = (await connectWithKey({connection: 'conn-0', key: 'pk-5678'})).unwrap(); expect(createConnection).not.toHaveBeenCalled(); - expect(renewConnection.mock.calls[0]?.[0]).toMatchObject({connectionId: 'conn-0', account: 'API key ending 5678', credential: `enc:${JSON.stringify({auth: 'key', key: 'pk-5678'})}`}); + expect(renewConnection.mock.calls[0]?.[0]).toMatchObject({connectionId: 'conn-0', account: 'API key ending 5678', credential: `enc:${JSON.stringify({auth: 'token', token: 'pk-5678'})}`}); expect(updateConnectionName).not.toHaveBeenCalled(); expect(connection).toMatchObject({id: 'conn-0', name: 'Team Parallel'}); }); diff --git a/packages/api/src/connections/take-over-custom.test.ts b/packages/api/src/connections/take-over-custom.test.ts index 79654983..887173da 100644 --- a/packages/api/src/connections/take-over-custom.test.ts +++ b/packages/api/src/connections/take-over-custom.test.ts @@ -199,19 +199,19 @@ describe('movedCredential', () => { test("keeps a sign-in to the integration's own server, whatever the query of the address", () => { expect(movedCredential(EXA_MCP, {...EXA_SIGN_IN, url: 'https://mcp.exa.ai/mcp?tools=web_search_exa'})).toEqual({ kind: 'moved', - credential: {clientId: 'client-1', accessToken: 'access-1', refreshToken: 'refresh-1', expiresAt: null}, + credential: {auth: 'oauth', clientId: 'client-1', accessToken: 'access-1', refreshToken: 'refresh-1', expiresAt: null}, }); }); test("a token typed in becomes the integration's API key, where it takes one and the token is a bare one", () => { - expect(movedCredential(EXA_MCP, {auth: 'token', url: 'https://mcp.exa.ai/mcp', token: 'key-1'})).toEqual({kind: 'moved', credential: {auth: 'key', key: 'key-1'}}); - expect(movedCredential(PARALLEL_MCP, {auth: 'token', url: 'https://search.parallel.ai/mcp', token: 'pk_1'})).toEqual({kind: 'moved', credential: {auth: 'key', key: 'pk_1'}}); - expect(movedCredential(LINEAR_MCP, {auth: 'token', url: 'https://mcp.linear.app/mcp', token: 'lin_api_1'})).toEqual({kind: 'moved', credential: {auth: 'key', key: 'lin_api_1'}}); + expect(movedCredential(EXA_MCP, {auth: 'token', url: 'https://mcp.exa.ai/mcp', token: 'key-1'})).toEqual({kind: 'moved', credential: {auth: 'token', token: 'key-1'}}); + expect(movedCredential(PARALLEL_MCP, {auth: 'token', url: 'https://search.parallel.ai/mcp', token: 'pk_1'})).toEqual({kind: 'moved', credential: {auth: 'token', token: 'pk_1'}}); + expect(movedCredential(LINEAR_MCP, {auth: 'token', url: 'https://mcp.linear.app/mcp', token: 'lin_api_1'})).toEqual({kind: 'moved', credential: {auth: 'token', token: 'lin_api_1'}}); expect(movedCredential(EXA_MCP, {auth: 'token', url: 'https://mcp.exa.ai/mcp', token: 'Basic abc'})).toEqual({kind: 'moved', credential: null}); }); test("a key in the address, as Exa's own setup writes it, becomes the integration's API key", () => { - expect(movedCredential(EXA_MCP, {auth: 'none', url: 'https://mcp.exa.ai/mcp?exaApiKey=key-2'})).toEqual({kind: 'moved', credential: {auth: 'key', key: 'key-2'}}); + expect(movedCredential(EXA_MCP, {auth: 'none', url: 'https://mcp.exa.ai/mcp?exaApiKey=key-2'})).toEqual({kind: 'moved', credential: {auth: 'token', token: 'key-2'}}); }); test('a server reached with nothing at all stays custom, rather than stop working', () => { @@ -301,7 +301,7 @@ describe('takeOverCustomConnections', () => { connectionId: 'mcp-exa', integrationId: 'exa', account: 'Signed in', - credential: stored({clientId: 'client-1', accessToken: 'access-1', refreshToken: 'refresh-1', expiresAt: null}), + credential: stored({auth: 'oauth', clientId: 'client-1', accessToken: 'access-1', refreshToken: 'refresh-1', expiresAt: null}), defaults: ['search'], grants: [], runs: [{id: 'e-1', collectionId: 'searches', action: 'run', recordTitle: 'bun mocks', query: null}], @@ -310,7 +310,7 @@ describe('takeOverCustomConnections', () => { connectionId: 'mcp-parallel', integrationId: 'parallel', account: 'API key ending 5678', - credential: stored({auth: 'key', key: 'pk_5678'}), + credential: stored({auth: 'token', token: 'pk_5678'}), defaults: ['search', 'fetch'], grants: [], runs: [], @@ -410,7 +410,7 @@ describe('takeOverCustomConnections', () => { connectionId: 'mcp-linear', integrationId: 'linear', account: 'alex@example.com · Acme', - credential: stored({auth: 'key', key: 'lin_api_1'}), + credential: stored({auth: 'token', token: 'lin_api_1'}), defaults: ['read'], }); }); diff --git a/packages/api/src/connections/take-over-custom.ts b/packages/api/src/connections/take-over-custom.ts index f8e17090..7e47d337 100644 --- a/packages/api/src/connections/take-over-custom.ts +++ b/packages/api/src/connections/take-over-custom.ts @@ -13,8 +13,8 @@ import {builtInForHost} from './built-in-mcp'; import {customCredentialSchema, type CustomCredential} from './custom/custom-mcp'; import {keyInAddress, toolParamsSchema, type BuiltInMcp, type ToolParams} from './mcp/built-in'; import {accountOf, checkedKeyAccount} from './mcp/mcp-connect'; -import {isExpiring, refreshMcpTokens, type McpCredential} from './mcp/mcp-oauth'; -import type {McpKeyCredential} from './mcp/mcp-session'; +import {isExpiring, refreshMcpTokens, type McpTokens} from './mcp/mcp-oauth'; +import type {BuiltInCredential, OAuthCredential} from './mcp/mcp-credential'; import {callWithRefresh} from './token-session'; /** @@ -77,9 +77,7 @@ function serverAddress(url: string): string | null { return URL.canParse(url) ? `${new URL(url).origin}${new URL(url).pathname.replace(/\/$/, '')}` : null; } -type Carried = McpCredential | McpKeyCredential; - -type MovedCredential = {kind: 'moved'; credential: Carried | null} | {kind: 'stays'}; +type MovedCredential = {kind: 'moved'; credential: BuiltInCredential | null} | {kind: 'stays'}; /** * What a custom connection's credential becomes as the integration keeps one (`moved`): a sign-in @@ -95,20 +93,20 @@ export function movedCredential(builtIn: BuiltInMcp, custom: CustomCredential | } const inAddress = URL.canParse(custom.url) ? keyInAddress(builtIn, new URL(custom.url)) : null; if (inAddress) { - return {kind: 'moved', credential: {auth: 'key', key: inAddress}}; + return {kind: 'moved', credential: {auth: 'token', token: inAddress}}; } if (custom.auth === 'none') { return {kind: 'stays'}; } if (custom.auth === 'token') { const bare = builtIn.apiKey && !/\s/.test(custom.token); - return {kind: 'moved', credential: bare ? {auth: 'key', key: custom.token} : null}; + return {kind: 'moved', credential: bare ? {auth: 'token', token: custom.token} : null}; } if (serverAddress(custom.url) !== serverAddress(builtIn.server.url) || custom.server.tokenUrl !== builtIn.server.tokenUrl) { return {kind: 'moved', credential: null}; } const {clientId, accessToken, refreshToken, expiresAt} = custom; - return {kind: 'moved', credential: {clientId, accessToken, refreshToken, expiresAt}}; + return {kind: 'moved', credential: {auth: 'oauth', clientId, accessToken, refreshToken, expiresAt}}; } // Nothing carried over: the server's address as the account, until it is signed in to. @@ -127,29 +125,29 @@ function unsignedIn(address: string): {account: string; credential: null} { */ export function movedAccount( builtIn: BuiltInMcp, - credential: Carried | null, + credential: BuiltInCredential | null, address: string, - keep: (tokens: McpCredential) => Promise>, -): Promise> { + keep: (tokens: McpTokens) => Promise>, +): Promise> { return Do(async ($) => { if (!credential) { return unsignedIn(address); } - const named: Result<{account: string; credential: Carried}, ApiError> = - 'key' in credential - ? (await checkedKeyAccount(builtIn, credential.key)).map(({account}) => ({account, credential})) + const named: Result<{account: string; credential: BuiltInCredential}, ApiError> = + credential.auth === 'token' + ? (await checkedKeyAccount(builtIn, credential.token)).map(({account}) => ({account, credential})) : await callWithRefresh( { isExpiring, - refresh: (tokens) => - Do(async ($$) => { - const refreshed = $$(await refreshMcpTokens(builtIn.server, tokens)); + refresh: (signIn) => + Do(async ($$) => { + const refreshed = $$(await refreshMcpTokens(builtIn.server, signIn)); $$(await keep(refreshed)); - return refreshed; + return {...signIn, ...refreshed}; }), }, credential, - async (tokens) => (await accountOf(builtIn, tokens.accessToken)).map(({account}) => ({account, credential: tokens})), + async (signIn) => (await accountOf(builtIn, signIn.accessToken)).map(({account}) => ({account, credential: signIn})), ); if (named.isErr() && named.error.kind === 'credentials_rejected') { return unsignedIn(address); @@ -182,7 +180,7 @@ export function takeOver(connection: CustomMcpConnectionRow, builtIn: BuiltInMcp grants: locked.agentGrants, }); const runs = locked.runs.flatMap((entry) => movedRun(builtIn, entry) ?? []); - const keep = (tokens: McpCredential) => Do(async ($k) => $k(await keepCredential($k(encryptSecret(JSON.stringify({...custom, ...tokens})))))); + const keep = (tokens: McpTokens) => Do(async ($k) => $k(await keepCredential($k(encryptSecret(JSON.stringify({...custom, ...tokens})))))); const {account, credential} = $$(await movedAccount(builtIn, carried.credential, locked.account, keep)); const encrypted = credential ? $$(encryptSecret(JSON.stringify(credential))) : null; return {integrationId: builtIn.integrationId, account, credential: encrypted, ...permissions, runs}; diff --git a/packages/api/src/data-migrations/run.test.ts b/packages/api/src/data-migrations/run.test.ts index a8bf0a87..02a1e959 100644 --- a/packages/api/src/data-migrations/run.test.ts +++ b/packages/api/src/data-migrations/run.test.ts @@ -9,6 +9,7 @@ mock.module('@proxy/db/instance-meta', () => ({hasInstanceMetaKey, setInstanceMe mock.module('../connections/take-over-custom', () => ({takeOverCustomConnections: mock()})); mock.module('../native/vault/vault-entries', () => ({convertOldVaultRecords: mock()})); +mock.module('../connections/mcp/unify-credentials', () => ({unifyMcpCredentials: mock()})); const error = mock(); mock.module('../observability/log', () => ({ diff --git a/packages/api/src/data-migrations/run.ts b/packages/api/src/data-migrations/run.ts index c25677f2..9493dd7c 100644 --- a/packages/api/src/data-migrations/run.ts +++ b/packages/api/src/data-migrations/run.ts @@ -3,6 +3,7 @@ import type {Result} from 'ts-results-es'; import type {ApiError} from '@proxy/utils'; import {hasInstanceMetaKey, setInstanceMetaValue} from '@proxy/db/instance-meta'; +import {unifyMcpCredentials} from '../connections/mcp/unify-credentials'; import {takeOverCustomConnections} from '../connections/take-over-custom'; import {log, serializeError} from '../observability/log'; import {convertOldVaultRecords} from '../native/vault/vault-entries'; @@ -22,6 +23,7 @@ export type DataMigration = {id: string; run: () => Promise> { + const rows = await wrapDb(() => + db.connection.findMany({ + where: {integrationId: {in: integrationIds}, credential: {not: null}}, + select: {id: true, credential: true}, + }), + ); + return rows.map((found) => + found.flatMap(({id, credential}) => (credential === null ? [] : [{id, credential}])), + ); +} + +/** + * Rewrites a connection's credential in another shape, only while it is still `previous`, so tokens + * refreshed meanwhile are never undone: `Ok(false)` when it had changed. Unlike a refresh, it says + * nothing of whether the provider turned the credential down, which stays as it was. + */ +export async function rewriteConnectionCredential(data: { + connectionId: string; + previous: string; + credential: string; +}): Promise> { + const {connectionId, previous, credential} = data; + return ( + await wrapDb(() => + db.connection.updateMany({ + where: {id: connectionId, credential: previous}, + data: {credential}, + }), + ) + ).map(({count}) => count > 0); +} + /** A custom MCP connection, for moving it to a built-in integration: its id, and its server's address, which it shows as its account. */ export type CustomMcpConnectionRow = {id: string; account: string};