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
198 changes: 198 additions & 0 deletions packages/worker/src/mcp/execute-modules/codemode-utils.node.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
import { expect, test } from 'vitest'
import {
createAuthenticatedFetch,
createExecuteHelperPrelude,
getExecuteHelperCapabilityNames,
refreshAccessToken,
} from './codemode-utils.ts'

type SecretSetCall = {
name: string
value: string
scope: string
}

const spotifyConnector = {
name: 'spotify',
tokenUrl: 'https://accounts.spotify.test/api/token',
apiBaseUrl: 'https://api.spotify.test/v1',
flow: 'pkce' as const,
clientIdValueName: 'spotifyClientId',
clientSecretSecretName: null,
accessTokenSecretName: 'spotifyAccessToken',
refreshTokenSecretName: 'spotifyRefreshToken',
requiredHosts: ['api.spotify.test'],
}

function createCodemode(payload: Record<string, unknown>) {
const secretSetCalls: Array<SecretSetCall> = []
const codemode = {
async connector_get({ name }: { name: string }) {
expect(name).toBe('spotify')
return { connector: spotifyConnector }
},
async value_get({ name }: { name: string }) {
expect(name).toBe('spotifyClientId')
return { value: 'spotify-client-id' }
},
async secret_set(args: SecretSetCall) {
secretSetCalls.push(args)
return {
name: args.name,
scope: args.scope,
}
},
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

const fetchCalls: Array<Request> = []
const fetchStub = async (input: RequestInfo | URL, init?: RequestInit) => {

Check failure on line 48 in packages/worker/src/mcp/execute-modules/codemode-utils.node.test.ts

View workflow job for this annotation

GitHub Actions / 🧪 Typecheck

Cannot find name 'RequestInfo'. Did you mean 'RequestInit'?
const request = new Request(input, init)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
fetchCalls.push(request)
if (request.url === spotifyConnector.tokenUrl) {
return new Response(JSON.stringify(payload), {
status: 200,
headers: { 'content-type': 'application/json' },
})
}
return new Response(JSON.stringify({ ok: true }), {
status: 200,
headers: { 'content-type': 'application/json' },
})
}

return { codemode, secretSetCalls, fetchCalls, fetchStub }
}

async function withPatchedFetch<T>(
fetchImpl: typeof globalThis.fetch,
callback: () => Promise<T>,
) {
const originalFetch = globalThis.fetch
globalThis.fetch = fetchImpl
try {
return await callback()
} finally {
globalThis.fetch = originalFetch
}
}

test('refreshAccessToken persists rotated refresh token and access token', async () => {
const { codemode, secretSetCalls, fetchStub, fetchCalls } = createCodemode({
access_token: 'new-access-token',
refresh_token: 'new-refresh-token',
})

const accessToken = await withPatchedFetch(fetchStub, () =>
refreshAccessToken(codemode, 'spotify'),

Check failure on line 86 in packages/worker/src/mcp/execute-modules/codemode-utils.node.test.ts

View workflow job for this annotation

GitHub Actions / 🧪 Typecheck

Argument of type '{ connector_get({ name }: { name: string; }): Promise<{ connector: { name: string; tokenUrl: string; apiBaseUrl: string; flow: "pkce"; clientIdValueName: string; clientSecretSecretName: null; accessTokenSecretName: string; refreshTokenSecretName: string; requiredHosts: string[]; }; }>; value_get({ name }: { ...; }):...' is not assignable to parameter of type 'CodemodeNamespace'.
)

expect(accessToken).toBe('new-access-token')
expect(secretSetCalls).toEqual([
{
name: 'spotifyRefreshToken',
value: 'new-refresh-token',
scope: 'user',
},
{
name: 'spotifyAccessToken',
value: 'new-access-token',
scope: 'user',
},
])
expect(fetchCalls).toHaveLength(1)
expect(fetchCalls[0]?.method).toBe('POST')
expect(await fetchCalls[0]?.text()).toContain(
'refresh_token=%7B%7Bsecret%3AspotifyRefreshToken%7Cscope%3Duser%7D%7D',
)
})

test('createAuthenticatedFetch persists refreshed access token even without refresh token rotation', async () => {
const { codemode, secretSetCalls, fetchStub, fetchCalls } = createCodemode({
access_token: 'new-access-token',
})

const authenticatedFetch = await withPatchedFetch(fetchStub, () =>
createAuthenticatedFetch(codemode, 'spotify'),

Check failure on line 115 in packages/worker/src/mcp/execute-modules/codemode-utils.node.test.ts

View workflow job for this annotation

GitHub Actions / 🧪 Typecheck

Argument of type '{ connector_get({ name }: { name: string; }): Promise<{ connector: { name: string; tokenUrl: string; apiBaseUrl: string; flow: "pkce"; clientIdValueName: string; clientSecretSecretName: null; accessTokenSecretName: string; refreshTokenSecretName: string; requiredHosts: string[]; }; }>; value_get({ name }: { ...; }):...' is not assignable to parameter of type 'CodemodeNamespace'.
)
const response = await withPatchedFetch(fetchStub, () =>
authenticatedFetch('/me?market=US'),
)

expect(secretSetCalls).toEqual([
{
name: 'spotifyAccessToken',
value: 'new-access-token',
scope: 'user',
},
])
expect(fetchCalls).toHaveLength(2)
expect(fetchCalls[1]?.url).toBe('https://api.spotify.test/v1/me?market=US')
expect(fetchCalls[1]?.headers.get('authorization')).toBe(
'Bearer new-access-token',
)
expect(await response.json()).toEqual({ ok: true })
})

test('createExecuteHelperPrelude persists rotated refresh token and access token', async () => {
const { codemode, secretSetCalls, fetchStub, fetchCalls } = createCodemode({
access_token: 'new-access-token',
refresh_token: 'new-refresh-token',
})
const prelude = createExecuteHelperPrelude()
const createSandboxHelpers = new Function(
'codemode',
`${prelude}; return { refreshAccessToken, createAuthenticatedFetch };`,
) as (
codemode: typeof codemode,

Check failure on line 146 in packages/worker/src/mcp/execute-modules/codemode-utils.node.test.ts

View workflow job for this annotation

GitHub Actions / 🧪 Typecheck

'codemode' is referenced directly or indirectly in its own type annotation.
) => {
refreshAccessToken: (providerName: string) => Promise<string>
createAuthenticatedFetch: (
providerName: string,
) => Promise<(input: RequestInfo | URL, init?: RequestInit) => Promise<Response>>

Check failure on line 151 in packages/worker/src/mcp/execute-modules/codemode-utils.node.test.ts

View workflow job for this annotation

GitHub Actions / 🧪 Typecheck

Cannot find name 'RequestInfo'. Did you mean 'RequestInit'?
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

const helpers = createSandboxHelpers(codemode)
const accessToken = await withPatchedFetch(fetchStub, () =>
helpers.refreshAccessToken('spotify'),
)
const authenticatedFetch = await withPatchedFetch(fetchStub, () =>
helpers.createAuthenticatedFetch('spotify'),
)
await withPatchedFetch(fetchStub, () => authenticatedFetch('/me'))

expect(accessToken).toBe('new-access-token')
expect(secretSetCalls).toEqual([
{
name: 'spotifyRefreshToken',
value: 'new-refresh-token',
scope: 'user',
},
{
name: 'spotifyAccessToken',
value: 'new-access-token',
scope: 'user',
},
{
name: 'spotifyRefreshToken',
value: 'new-refresh-token',
scope: 'user',
},
{
name: 'spotifyAccessToken',
value: 'new-access-token',
scope: 'user',
},
])
expect(fetchCalls).toHaveLength(3)
expect(fetchCalls[2]?.headers.get('authorization')).toBe(
'Bearer new-access-token',
)
})

test('getExecuteHelperCapabilityNames includes secret_set for refresh persistence', () => {
expect(getExecuteHelperCapabilityNames()).toEqual([
'connector_get',
'value_get',
'secret_set',
])
})
83 changes: 82 additions & 1 deletion packages/worker/src/mcp/execute-modules/codemode-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,11 @@ type ValueGetResult = {

type ExecuteRequestInput = string | URL | Request

const executeHelperCapabilityNames = ['connector_get', 'value_get'] as const
const executeHelperCapabilityNames = [
'connector_get',
'value_get',
'secret_set',
] as const

export async function refreshAccessToken(
codemode: CodemodeNamespace,
Expand Down Expand Up @@ -109,6 +113,30 @@ async function readClientId(
return value.value
}

async function persistSecret(
codemode: CodemodeNamespace,
providerName: string,
secretName: string,
secretKind: 'access token' | 'refresh token',
value: string,
) {
const secretSet = codemode.secret_set
if (typeof secretSet !== 'function') {
throw new Error('codemode.secret_set is not available in this sandbox.')
}
const normalizedSecretName = secretName.trim()
if (!normalizedSecretName) {
throw new Error(
`Connector "${providerName}" does not define an ${secretKind} secret name.`,
)
}
await secretSet({
name: normalizedSecretName,
value,
scope: 'user',
})
}

async function refreshAccessTokenWithConnector(
codemode: CodemodeNamespace,
providerName: string,
Expand Down Expand Up @@ -168,6 +196,23 @@ async function refreshAccessTokenWithConnector(
)
}

if (typeof payload.refresh_token === 'string' && payload.refresh_token.length > 0) {
await persistSecret(
codemode,
providerName,
refreshTokenSecretName,
'refresh token',
payload.refresh_token,
)
}
await persistSecret(
codemode,
providerName,
connector.accessTokenSecretName,
'access token',
payload.access_token,
)

return payload.access_token
}

Expand Down Expand Up @@ -272,6 +317,28 @@ const __kodyReadClientId = async (connector) => {
}
return value.value;
};
const __kodyPersistSecret = async (
providerName,
secretName,
secretKind,
value,
) => {
const secretSet = codemode.secret_set;
if (typeof secretSet !== 'function') {
throw new Error('codemode.secret_set is not available in this sandbox.');
}
const normalizedSecretName = secretName.trim();
if (!normalizedSecretName) {
throw new Error(
\`Connector "\${providerName}" does not define an \${secretKind} secret name.\`,
);
}
await secretSet({
name: normalizedSecretName,
value,
scope: 'user',
});
};
const __kodyGetNormalizedApiBaseUrl = (connector) => {
if (!connector.apiBaseUrl) return null;
return connector.apiBaseUrl.endsWith('/')
Expand Down Expand Up @@ -364,6 +431,20 @@ const __kodyRefreshAccessToken = async (providerName) => {
\`Token refresh for connector "\${providerName}" did not return an access_token.\`,
);
}
if (typeof payload.refresh_token === 'string' && payload.refresh_token.length > 0) {
await __kodyPersistSecret(
providerName,
refreshTokenSecretName,
'refresh token',
payload.refresh_token,
);
}
await __kodyPersistSecret(
providerName,
connector.accessTokenSecretName,
'access token',
payload.access_token,
);
return payload.access_token;
};
const __kodyCreateAuthenticatedFetch = async (providerName) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,5 +56,5 @@ test('infers capabilities from execute-time helper names', () => {
}`
const { helperNames, inferencePartial } = inferCodemodeCapabilities(src)
expect(inferencePartial).toBe(false)
expect(helperNames).toEqual(['connector_get', 'value_get'])
expect(helperNames).toEqual(['connector_get', 'secret_set', 'value_get'])
})
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { parse, type Node, type Program } from 'acorn'

const executeHelperCapabilities = ['connector_get', 'value_get'] as const
const executeHelperCapabilities = [
'connector_get',
'value_get',
'secret_set',
] as const
const executeHelperNames = new Set([
'refreshAccessToken',
'createAuthenticatedFetch',
Expand Down
Loading