Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
60 changes: 56 additions & 4 deletions docs/use/execute.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,11 @@ helpers are runtime exports:
valid identifier names, or **`await codemode["capability-id"](input)`** for
non-identifier capability ids
- use
**`import { refreshAccessToken, createAuthenticatedFetch } from 'kody:runtime'`**
for integration OAuth helpers
**`import { refreshAccessToken, createAuthenticatedFetch, oauthClientCredentials } from 'kody:runtime'`**
for OAuth helpers
- use **`import { secretHeaders } from 'kody:runtime'`** when an approved
`fetch` request needs host-derived auth headers from saved secrets, such as
Basic Auth from a saved client id and client secret
- use **`import { storage } from 'kody:runtime'`** when the execute call is
bound to a storage id
- use **`import { workflows } from 'kody:runtime'`** to queue Cloudflare
Expand Down Expand Up @@ -230,9 +233,9 @@ reconnect the MCP client if the host caches server instructions.
## Network and OAuth helpers

The sandbox exposes global **`fetch`** plus secret placeholders in approved
contexts. OAuth helpers are imported from **`kody:runtime`**:
contexts. OAuth and secret-header helpers are imported from **`kody:runtime`**:

**`import { refreshAccessToken, createAuthenticatedFetch } from 'kody:runtime'`**
**`import { refreshAccessToken, createAuthenticatedFetch, oauthClientCredentials, secretHeaders } from 'kody:runtime'`**

`createAuthenticatedFetch(providerName)` is async. Await it before calling the
returned fetch wrapper:
Expand All @@ -247,6 +250,55 @@ accounts may exist, such as `google`, `google-business`, or
`google-youtube-brand`. Call **`integration_list`** up front when a provider may
have multiple accounts connected.

For OAuth 2 `client_credentials` token exchanges that require
`Authorization: Basic base64(client_id:client_secret)`, save the client id and
client secret separately. Do **not** ask the user to precompute or save the
derived Basic header. Use `secretHeaders.basic(...)` directly in a fetch header,
or use `oauthClientCredentials(...)` for the token request:

```ts
import { oauthClientCredentials } from 'kody:runtime'

export default async function main() {
const token = await oauthClientCredentials({
tokenUrl: 'https://api-m.paypal.com/v1/oauth2/token',
clientIdSecret: 'paypalClientId',
clientSecretSecret: 'paypalClientSecret',
scope: 'user',
})

return { tokenType: token.token_type, hasAccessToken: !!token.access_token }
}
```

The lower-level PayPal token request is:

```ts
import { secretHeaders } from 'kody:runtime'

export default async function main() {
const body = new URLSearchParams({ grant_type: 'client_credentials' })
const response = await fetch('https://api-m.paypal.com/v1/oauth2/token', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: secretHeaders.basic({
usernameSecret: 'paypalClientId',
passwordSecret: 'paypalClientSecret',
scope: 'user',
}),
},
body,
})
return await response.json()
}
```

Kody resolves both saved secrets server-side, requires the token endpoint host
to be approved for both secrets, and only sends the derived Basic header in the
outbound request.

See [Secrets, values, and host approval](./secrets-and-values.md) for
placeholders, host approval, and **`codemode.secret_list`** / **`secret_set`**.

Expand Down
25 changes: 25 additions & 0 deletions docs/use/secrets-and-values.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,31 @@ Outbound **`fetch`** can include placeholders such as **`{{secret:tokenName}}`**
or **`{{secret:tokenName|scope=user}}`** in the URL, headers, or body. The host
resolves them for **approved** destinations.

When an API requires Basic Auth derived from two saved secrets, import
**`secretHeaders`** from **`kody:runtime`** and put the opaque helper result in
the outbound fetch header:

```ts
import { secretHeaders } from 'kody:runtime'

await fetch('https://api-m.paypal.com/v1/oauth2/token', {
method: 'POST',
headers: {
Authorization: secretHeaders.basic({
usernameSecret: 'paypalClientId',
passwordSecret: 'paypalClientSecret',
scope: 'user',
}),
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({ grant_type: 'client_credentials' }),
})
```

Kody resolves both secrets and sends only the derived `Basic ...` header to the
approved host. The target host must be approved separately for both saved
secrets.

Some capability fields opt in with **`x-kody-secret: true`**; those accept the
same placeholder form instead of raw credentials.

Expand Down
110 changes: 110 additions & 0 deletions packages/worker/src/mcp/execute-modules/codemode-utils.node.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ import {
createAuthenticatedFetch,
createExecuteHelperPrelude,
getExecuteHelperCapabilityNames,
oauthClientCredentials,
refreshAccessToken,
secretHeaders,
} from './codemode-utils.ts'

type SecretSetCall = {
Expand All @@ -22,6 +24,8 @@ type SandboxHelpers = {
) => Promise<
(input: ExecuteRequestInput, init?: RequestInit) => Promise<Response>
>
secretHeaders: typeof secretHeaders
oauthClientCredentials: typeof oauthClientCredentials
}

const spotifyIntegration = {
Expand Down Expand Up @@ -200,6 +204,112 @@ test('createExecuteHelperPrelude persists rotated refresh token and access token
)
})

test('secretHeaders.basic returns an opaque Basic Auth placeholder', () => {
expect(
secretHeaders.basic({
usernameSecret: 'paypalClientId',
passwordSecret: 'paypalClientSecret',
scope: 'user',
}),
).toBe(
'{{secret-basic:username=paypalClientId,password=paypalClientSecret|scope=user}}',
)
})

test('oauthClientCredentials posts a Basic placeholder through fetch', async () => {
const fetchCalls: Array<Request> = []
const fetchStub: typeof globalThis.fetch = async (
input: ExecuteRequestInput,
init?: RequestInit,
) => {
const request = new Request(input, init)
fetchCalls.push(request)
return new Response(
JSON.stringify({
access_token: 'paypal-access-token',
token_type: 'Bearer',
}),
{
status: 200,
headers: { 'content-type': 'application/json' },
},
)
}

const tokenResponse = await withPatchedFetch(fetchStub, () =>
oauthClientCredentials({
tokenUrl: 'https://api-m.paypal.com/v1/oauth2/token',
clientIdSecret: 'paypalClientId',
clientSecretSecret: 'paypalClientSecret',
scope: 'user',
body: {
scope: 'openid',
},
}),
)

expect(tokenResponse).toEqual({
access_token: 'paypal-access-token',
token_type: 'Bearer',
})
expect(fetchCalls).toHaveLength(1)
expect(fetchCalls[0]?.method).toBe('POST')
expect(fetchCalls[0]?.headers.get('authorization')).toBe(
'{{secret-basic:username=paypalClientId,password=paypalClientSecret|scope=user}}',
)
expect(fetchCalls[0]?.headers.get('content-type')).toBe(
'application/x-www-form-urlencoded',
)
expect(await fetchCalls[0]?.text()).toBe(
new URLSearchParams({
scope: 'openid',
grant_type: 'client_credentials',
}).toString(),
)
})

test('createExecuteHelperPrelude exposes secret and client credentials helpers', async () => {
const prelude = createExecuteHelperPrelude()
const createSandboxHelpers = new Function(
'codemode',
`${prelude}; return { secretHeaders, oauthClientCredentials };`,
) as (codemodeNamespace: CodemodeNamespace) => SandboxHelpers
const fetchCalls: Array<Request> = []
const fetchStub: typeof globalThis.fetch = async (
input: ExecuteRequestInput,
init?: RequestInit,
) => {
const request = new Request(input, init)
fetchCalls.push(request)
return new Response(JSON.stringify({ access_token: 'access-token' }), {
status: 200,
headers: { 'content-type': 'application/json' },
})
}

const helpers = createSandboxHelpers({} satisfies CodemodeNamespace)
expect(
helpers.secretHeaders.basic({
usernameSecret: 'paypalClientId',
passwordSecret: 'paypalClientSecret',
scope: 'user',
}),
).toBe(
'{{secret-basic:username=paypalClientId,password=paypalClientSecret|scope=user}}',
)
await withPatchedFetch(fetchStub, () =>
helpers.oauthClientCredentials({
tokenUrl: 'https://api-m.paypal.com/v1/oauth2/token',
clientIdSecret: 'paypalClientId',
clientSecretSecret: 'paypalClientSecret',
scope: 'user',
}),
)
expect(fetchCalls[0]?.headers.get('authorization')).toBe(
'{{secret-basic:username=paypalClientId,password=paypalClientSecret|scope=user}}',
)
})

test('getExecuteHelperCapabilityNames includes secret_set for refresh persistence', () => {
expect(getExecuteHelperCapabilityNames()).toEqual([
'integration_get',
Expand Down
Loading
Loading