Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 12 additions & 6 deletions packages/trueforge/src/apis/mcpServers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -247,14 +247,14 @@ export function createSettingsMcpServersRouter<TTransaction>(deps: McpServersRou
});

let dcrClientToSave: OAuthClientRecord | undefined;
let clearTokensForServerId: string | undefined;
if (manifest.auth?.type === 'dcr') {
const existingClient = existing
? await deps.mcpServerStore.getClient({ id: existing.id }, transaction)
: undefined;
// Register when: brand-new server, client was cleared (e.g. invalid_client), or MCP URL changed
// (resource/AS may differ; reuse would keep stale oauth_server/client for the old AS).
// TODO: make manifest URL immutable after create so re-DCR / stale OAuth tokens are not possible via PUT.
const urlChanged = existing && existing.manifest.url !== manifest.url;
const urlChanged = existing !== undefined && existing.manifest.url !== manifest.url;
const needsDcr = existingClient === undefined || urlChanged;
if (needsDcr) {
dcrClientToSave = await createMcpOAuthClient({
Expand All @@ -264,6 +264,10 @@ export function createSettingsMcpServersRouter<TTransaction>(deps: McpServersRou
clientName: configuration.MCP_DCR_OAUTH_CLIENT_NAME,
});
}
// URL is the OAuth resource/audience — drop every user's tokens for this server.
if (urlChanged) {
clearTokensForServerId = existing.id;
}
}

const saved = await deps.mcpServerStore.upsertServer(
Expand All @@ -275,15 +279,17 @@ export function createSettingsMcpServersRouter<TTransaction>(deps: McpServersRou
transaction,
);
if (dcrClientToSave !== undefined) {
// New DCR registration (create, missing client, or URL change): replace the shared client only.
// Existing per-user tokens are left in place; resolve/refresh fails them if they no longer
// match the new resource/AS, and users re-authorize from there.
// New DCR registration (create, missing client, or URL change): replace the shared client.
await deps.mcpServerStore.saveClient({ id: saved.id, record: dcrClientToSave }, transaction);
}
if (clearTokensForServerId) {
Comment thread
sr07asthana marked this conversation as resolved.
Resolved
await deps.tokenStore.deleteTokensForServer({ id: clearTokensForServerId }, transaction);
Comment thread
sr07asthana marked this conversation as resolved.
Resolved
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
return saved;
});

// A re-upsert preserves `id`, so a DCR server may already carry a token from a prior authorize.
// A re-upsert preserves `id`, so a DCR server may already carry a token from a prior authorize
// (unless this PUT changed the URL and cleared all tokens above).
const token =
record.manifest.auth?.type === 'dcr' ? await deps.tokenStore.getToken({ id: record.id, userRef }) : undefined;
return c.json({ data: toConfiguredMcpServer({ record, token }) }, 200);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { IOAuthTokenStore, OAuthPendingAuthorization, OAuthToken, OAuthToke
import { fromStoredOAuthToken, toStoredOAuthToken } from '../../mcpServerStore';
import type { Database } from '../types';
import { consumePendingAuthorization, savePendingAuthorization } from './queries/pendingAuthorization';
import { deleteToken, getToken, getTokens, saveToken } from './queries/token';
import { deleteToken, deleteTokensForServer, getToken, getTokens, saveToken } from './queries/token';

export class PostgresOAuthTokenStore implements IOAuthTokenStore<Transaction<Database>> {
constructor(private readonly db: Kysely<Database>) {}
Expand Down Expand Up @@ -43,4 +43,8 @@ export class PostgresOAuthTokenStore implements IOAuthTokenStore<Transaction<Dat
deleteToken(params: OAuthTokenKey, transaction?: Transaction<Database>): Promise<void> {
return deleteToken(transaction ?? this.db, params);
}

deleteTokensForServer(params: { id: string }, transaction?: Transaction<Database>): Promise<void> {
return deleteTokensForServer(transaction ?? this.db, params);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,7 @@ export async function deleteToken(db: Kysely<Database>, params: { id: string; us
.where('user_id', '=', params.userRef)
.execute();
}

export async function deleteTokensForServer(db: Kysely<Database>, params: { id: string }): Promise<void> {
await db.deleteFrom('oauth_token').where('oauth_server_id', '=', params.id).execute();
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { IOAuthTokenStore, OAuthPendingAuthorization, OAuthToken, OAuthToke
import { fromStoredOAuthToken, toStoredOAuthToken } from '../../mcpServerStore';
import type { Database } from '../types';
import { consumePendingAuthorization, savePendingAuthorization } from './queries/pendingAuthorization';
import { deleteToken, getToken, getTokens, saveToken } from './queries/token';
import { deleteToken, deleteTokensForServer, getToken, getTokens, saveToken } from './queries/token';

export class SqliteOAuthTokenStore implements IOAuthTokenStore<Transaction<Database>> {
constructor(private readonly db: Kysely<Database>) {}
Expand Down Expand Up @@ -43,4 +43,8 @@ export class SqliteOAuthTokenStore implements IOAuthTokenStore<Transaction<Datab
deleteToken(params: OAuthTokenKey, transaction?: Transaction<Database>): Promise<void> {
return deleteToken(transaction ?? this.db, params);
}

deleteTokensForServer(params: { id: string }, transaction?: Transaction<Database>): Promise<void> {
return deleteTokensForServer(transaction ?? this.db, params);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,7 @@ export async function deleteToken(db: Kysely<Database>, params: { id: string; us
.where('user_id', '=', params.userRef)
.execute();
}

export async function deleteTokensForServer(db: Kysely<Database>, params: { id: string }): Promise<void> {
await db.deleteFrom('oauth_token').where('oauth_server_id', '=', params.id).execute();
}
9 changes: 9 additions & 0 deletions packages/trueforge/src/mcp/auth/inMemoryStores.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,15 @@ export class InMemoryOAuthTokenStore implements IOAuthTokenStore {
async deleteToken(params: OAuthTokenKey): Promise<void> {
this.tokens.delete(tokenMapKey(params));
}

async deleteTokensForServer(params: { id: string }): Promise<void> {
const prefix = `${params.id}\0`;
for (const key of this.tokens.keys()) {
if (key.startsWith(prefix)) {
this.tokens.delete(key);
}
}
}
}

/** In-memory OAuth client store for tests and development without a database. */
Expand Down
2 changes: 2 additions & 0 deletions packages/trueforge/src/mcp/auth/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ export interface IOAuthTokenStore<TTransaction = never> {
getToken(params: OAuthTokenKey, transaction?: TTransaction): Promise<OAuthToken | undefined>;
getTokens(params: { ids: string[]; userRef: string }, transaction?: TTransaction): Promise<Map<string, OAuthToken>>;
deleteToken(params: OAuthTokenKey, transaction?: TTransaction): Promise<void>;
/** Deletes every per-user token for one MCP server id (all users). */
deleteTokensForServer(params: { id: string }, transaction?: TTransaction): Promise<void>;
}

/** Authorization-server endpoints discovered and cached at registration time. */
Expand Down
16 changes: 16 additions & 0 deletions packages/trueforge/tests/db/oauthTokenStoreContractSuite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,22 @@ export function runOAuthTokenStoreContractSuite(getHarness: () => OAuthTokenStor
expect(await h.store.getToken({ id: RESOURCE_ID, userRef: OTHER_USER_REF })).toEqual(forB);
});

it('deleteTokensForServer removes every user token for that resource only', async () => {
const h = getHarness();
await h.seedResource(RESOURCE_ID);
await h.seedResource(OTHER_RESOURCE_ID);
const other = token({ accessToken: 'access-other' });
await h.store.saveToken({ id: RESOURCE_ID, userRef: USER_REF, token: token({ accessToken: 'access-a' }) });
await h.store.saveToken({ id: RESOURCE_ID, userRef: OTHER_USER_REF, token: token({ accessToken: 'access-b' }) });
await h.store.saveToken({ id: OTHER_RESOURCE_ID, userRef: USER_REF, token: other });

await h.store.deleteTokensForServer({ id: RESOURCE_ID });

expect(await h.store.getToken({ id: RESOURCE_ID, userRef: USER_REF })).toBeUndefined();
expect(await h.store.getToken({ id: RESOURCE_ID, userRef: OTHER_USER_REF })).toBeUndefined();
expect(await h.store.getToken({ id: OTHER_RESOURCE_ID, userRef: USER_REF })).toEqual(other);
});

it('savePendingAuthorization + consumePendingAuthorization round-trips, including null fields', async () => {
const h = getHarness();
await h.seedResource(RESOURCE_ID);
Expand Down
21 changes: 14 additions & 7 deletions packages/trueforge/tests/unit/apis/mcpServers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,7 @@ describe('mcp-servers routers', () => {
await tokenStore.deleteToken({ id: record.id, userRef: LOCAL_USER_CONTEXT.userRef });
});

it('PUT URL change re-registers DCR and keeps existing tokens', async () => {
it('PUT URL change re-registers DCR and clears all tokens', async () => {
const record = await seedDcrServerWithClient();
await tokenStore.saveToken({
id: record.id,
Expand All @@ -318,6 +318,16 @@ describe('mcp-servers routers', () => {
scope: null,
},
});
await tokenStore.saveToken({
id: record.id,
userRef: 'other-user',
token: {
accessToken: 'stale-other-user',
refreshToken: 'stale-other-refresh',
expiresAt: '2099-01-01T00:00:00.000Z',
scope: null,
},
});

const newUrl = 'https://mcp.linear.app/v2/mcp';
const asOrigin = 'https://auth.example.com';
Expand Down Expand Up @@ -373,13 +383,11 @@ describe('mcp-servers routers', () => {
),
);
expect(response.status).toBe(200);
// List/GET auth_status is presence-based; tokens are not cleared on re-DCR.
expect(await response.json()).toEqual({
data: configured({ ...putBodyWithDcr, url: newUrl }, 'authenticated'),
});
expect(await tokenStore.getToken({ id: record.id, userRef: LOCAL_USER_CONTEXT.userRef })).toMatchObject({
accessToken: 'stale-for-old-url',
data: configured({ ...putBodyWithDcr, url: newUrl }, 'auth_required'),
});
expect(await tokenStore.getToken({ id: record.id, userRef: LOCAL_USER_CONTEXT.userRef })).toBeUndefined();
expect(await tokenStore.getToken({ id: record.id, userRef: 'other-user' })).toBeUndefined();
expect(await mcpServerStore.getClient({ id: record.id })).toMatchObject({
client: { clientId: 'new-url-client' },
});
Expand All @@ -405,7 +413,6 @@ describe('mcp-servers routers', () => {
},
},
});
await tokenStore.deleteToken({ id: record.id, userRef: LOCAL_USER_CONTEXT.userRef });
}
});

Expand Down
Loading