Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(control-api): u2 oauth provider adapters (monday, clickup, vercel) + pkce
Diego Zacariasb6b2d3ce4ebb
diff --git a/charts/clerum-crds/crds/mcpserver.yaml b/charts/clerum-crds/crds/mcpserver.yamlindex a2ae068ae..bbfe02131 100644--- a/charts/clerum-crds/crds/mcpserver.yaml+++ b/charts/clerum-crds/crds/mcpserver.yaml@@ -139,13 +139,16 @@ spec:# Known-shape adapters baked into control-api# (src/oauth/providers.ts). Adding a provider is a control-api# change — servers cannot speak OAuth to arbitrary endpoints.- # U2 extends: monday, clickup, vercel.+ # U2 adds: monday, clickup, vercel (monday + vercel use PKCE).enum:- salesforce- slack- notion- microsoft-graph+ - monday+ - clickup+ - verceldescription: >-Known-shape adapter. control-api owns the authorize/tokenURLs and response-shape parsing per provider. Immutable.diff --git a/charts/clerum-crds/crds/workflowrecipe.yaml b/charts/clerum-crds/crds/workflowrecipe.yamlindex 66841ad7a..f00d106a2 100644--- a/charts/clerum-crds/crds/workflowrecipe.yaml+++ b/charts/clerum-crds/crds/workflowrecipe.yaml@@ -1612,6 +1612,10 @@ spec:# O2: known-shape adapters baked into control-api.# Adding a provider is a control-api change — recipes# cannot speak OAuth to arbitrary endpoints.+ # U2 (spec 06) scopes monday/clickup/vercel to McpServers+ # ONLY — they are deliberately NOT added here. The+ # asymmetry is fail-closed: a recipe declaring one is+ # rejected at admission, which is the intended behavior.enum:- salesforce- slackdiff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex d052d9440..9bb4e2174 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.433",+ "version": "0.1.434","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.433",+ "version": "0.1.434","dependencies": {"@clerum/image-policy": "file:../packages/image-policy","@clerum/llm-providers": "file:../packages/llm-providers",diff --git a/control-api/package.json b/control-api/package.jsonindex e2b561351..87c5b1e45 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.433",+ "version": "0.1.434","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/oauth/authorizeUrlHelper.ts b/control-api/src/oauth/authorizeUrlHelper.tsindex 88d91356b..1d3e91fbd 100644--- a/control-api/src/oauth/authorizeUrlHelper.ts+++ b/control-api/src/oauth/authorizeUrlHelper.ts@@ -5,7 +5,8 @@ import {SecretNotFoundError,type SecretReader,} from './callback.js'-import { type OAuthProvider, getOAuthProviderAdapter } from './providers.js'+import { computeCodeChallengeS256, deriveCodeVerifier } from './pkce.js'+import { getOAuthProviderAdapter, isKnownOAuthProvider } from './providers.js'import { signOAuthState } from './state.js'/**@@ -87,7 +88,7 @@ export async function buildAuthorizeUrl(return { kind: 'background_access_not_enabled' }}- if (!isKnownProvider(decl.provider)) {+ if (!isKnownOAuthProvider(decl.provider)) {return { kind: 'unsupported_provider', provider: decl.provider }}const adapter = getOAuthProviderAdapter(decl.provider)@@ -118,24 +119,21 @@ export async function buildAuthorizeUrl(background: input.background ?? false,})+ // PKCE (DEC-1): derive the verifier deterministically from the signed state,+ // then send its S256 challenge. The callback re-derives the same verifier from+ // the round-tripped state — nothing PKCE-related is stored server-side.+ let codeChallenge: string | undefined+ if (adapter.usesPkce) {+ codeChallenge = computeCodeChallengeS256(deriveCodeVerifier(deps.stateSecret, state))+ }+const authorizeUrl = adapter.buildAuthorizeUrl({clientId,redirectUri: input.redirectUri,state,scopes: decl.scopes ?? [],+ codeChallenge,})return { kind: 'ok', authorizeUrl }}--const KNOWN_PROVIDERS: ReadonlySet<OAuthProvider> = new Set([- 'salesforce',- 'slack',- 'notion',- 'microsoft-graph',- 'google',-])--function isKnownProvider(value: string): value is OAuthProvider {- return KNOWN_PROVIDERS.has(value as OAuthProvider)-}diff --git a/control-api/src/oauth/callback.ts b/control-api/src/oauth/callback.tsindex 06b2a2b55..db35b8de3 100644--- a/control-api/src/oauth/callback.ts+++ b/control-api/src/oauth/callback.ts@@ -1,8 +1,10 @@import type { DbClient } from '../db.js'+import { deriveCodeVerifier } from './pkce.js'import {type OAuthProvider,type ParsedTokenResponse,getOAuthProviderAdapter,+ isKnownOAuthProvider,} from './providers.js'import { signOAuthState, verifyOAuthStateSignature } from './state.js'import { setUserGrantBackground, upsertOAuthGrant } from './store.js'@@ -203,15 +205,21 @@ export async function handleOAuthCallback(// ─── 4. Exchange code with provider ───────────────────────────────────const provider = clientDecl.provider- if (!isKnownProvider(provider)) {+ if (!isKnownOAuthProvider(provider)) {return { kind: 'unsupported_provider', provider }}const adapter = getOAuthProviderAdapter(provider)+ // PKCE (DEC-1): re-derive the verifier from the EXACT round-tripped state+ // string — the same signed value the authorize URL derived its challenge from.+ const codeVerifier = adapter.usesPkce+ ? deriveCodeVerifier(deps.stateSecret, input.state)+ : undefinedconst tokenRequest = adapter.buildTokenRequest({code: input.code,clientId,clientSecret,redirectUri: input.redirectUri,+ codeVerifier,})let parsed: ParsedTokenResponse@@ -294,18 +302,6 @@ export async function handleOAuthCallback(// ─── helpers ──────────────────────────────────────────────────────────────-const KNOWN_PROVIDERS: ReadonlySet<OAuthProvider> = new Set([- 'salesforce',- 'slack',- 'notion',- 'microsoft-graph',- 'google',-])--function isKnownProvider(value: string): value is OAuthProvider {- return KNOWN_PROVIDERS.has(value as OAuthProvider)-}-async function safeReadText(response: Response): Promise<string> {try {return (await response.text()).slice(0, 2000)diff --git a/control-api/src/oauth/pkce.ts b/control-api/src/oauth/pkce.tsnew file mode 100644index 000000000..a074241f0--- /dev/null+++ b/control-api/src/oauth/pkce.ts@@ -0,0 +1,48 @@+import { createHash, createHmac } from 'node:crypto'++/**+ * PKCE (RFC 7636) helpers for the auth-code OAuth flow, used by the providers+ * that require Proof Key for Code Exchange (currently monday + vercel; see+ * `OAuthProviderAdapter.usesPkce`).+ *+ * Design decision (spec 06 §U2, DEC-1): the `code_verifier` is NOT stored and+ * NOT randomly generated. It is DERIVED deterministically from the already+ * HMAC-signed `state` string, so the callback can re-derive the exact same+ * verifier from the round-tripped state without any server-side session store.+ *+ * deriveCodeVerifier(secret, state)+ * = base64url( HMAC-SHA256(secret, "pkce-verifier:" + state) )+ *+ * The message is domain-separated from the state signature itself: the state+ * signature signs `"${STATE_VERSION}." + payload` (state.ts), while the+ * verifier HMACs `"pkce-verifier:" + <full state string>`. The two message+ * spaces are disjoint (a state string always starts with `v1.`, never with+ * `pkce-verifier:`), so the verifier can never collide with a valid state+ * signature.+ *+ * HMAC-SHA256 is 32 bytes → 43 base64url chars, which satisfies RFC 7636's+ * 43-char minimum verifier length and its `[A-Za-z0-9-._~]` charset (base64url+ * emits only `[A-Za-z0-9-_]`, a strict subset).+ */++const PKCE_VERIFIER_MESSAGE_PREFIX = 'pkce-verifier:'++/**+ * Deterministically derive the PKCE `code_verifier` from the signed OAuth state.+ * Pure: same (secret, state) always yields the same verifier; a different state+ * yields a different verifier. The callback re-derives it from the exact+ * round-tripped state string to reconstruct the verifier at token-exchange time.+ */+export function deriveCodeVerifier(secret: string, state: string): string {+ return createHmac('sha256', secret)+ .update(`${PKCE_VERIFIER_MESSAGE_PREFIX}${state}`)+ .digest('base64url')+}++/**+ * Compute the S256 `code_challenge` for a verifier: base64url(SHA256(verifier)).+ * Anchored on RFC 7636 Appendix B.1 in the unit tests.+ */+export function computeCodeChallengeS256(verifier: string): string {+ return createHash('sha256').update(verifier).digest('base64url')+}diff --git a/control-api/src/oauth/providers.ts b/control-api/src/oauth/providers.tsindex ee13f7427..14f16d401 100644--- a/control-api/src/oauth/providers.ts+++ b/control-api/src/oauth/providers.ts@@ -1,10 +1,23 @@/*** Known-shape OAuth provider adapters supported by control-api. The string- * union mirrors the CRD enum (charts/clerum-crds/crds/workflowrecipe.yaml,- * spec.oauthClients[].provider) and the workflow-recipes types.ts- * `OAuthProvider`. Adding a provider requires updating ALL three sites.+ * union mirrors the CRD enum (charts/clerum-crds/crds/mcpserver.yaml ++ * workflowrecipe.yaml, provider enums) and the workflow-recipes types.ts+ * `OAuthProvider`. Adding a provider requires updating the CRD enum(s) and the+ * workflow-recipes union. Within control-api, `KNOWN_OAUTH_PROVIDERS` is derived+ * from `ADAPTERS` (single source of truth) — no per-call-site provider lists.+ *+ * U2 (spec 06 §U2) adds monday, clickup, vercel. monday + vercel require PKCE+ * (see `usesPkce` / pkce.ts).*/-export type OAuthProvider = 'salesforce' | 'slack' | 'notion' | 'microsoft-graph' | 'google'+export type OAuthProvider =+ | 'salesforce'+ | 'slack'+ | 'notion'+ | 'microsoft-graph'+ | 'google'+ | 'monday'+ | 'clickup'+ | 'vercel'/*** Known-shape OAuth provider adapters. Each adapter encapsulates the@@ -28,6 +41,13 @@ export interface AuthorizeUrlInput {redirectUri: stringstate: stringscopes: string[]+ /**+ * PKCE S256 `code_challenge`, present only for adapters with `usesPkce`. The+ * caller (authorizeUrlHelper) derives it from the signed state via+ * `computeCodeChallengeS256(deriveCodeVerifier(secret, state))`. PKCE adapters+ * emit BOTH `code_challenge` AND `code_challenge_method=S256`.+ */+ codeChallenge?: string}export interface TokenExchangeInput {@@ -35,6 +55,12 @@ export interface TokenExchangeInput {clientId: stringclientSecret: stringredirectUri: string+ /**+ * PKCE `code_verifier`, present only for adapters with `usesPkce`. The callback+ * re-derives it from the exact round-tripped state via+ * `deriveCodeVerifier(secret, state)`. Never present on the refresh path.+ */+ codeVerifier?: string}export interface TokenRequest {@@ -61,6 +87,13 @@ export interface ParsedTokenResponse {export interface OAuthProviderAdapter {provider: OAuthProvider+ /**+ * When true, this provider requires PKCE: `buildAuthorizeUrl` emits+ * `code_challenge` + `code_challenge_method=S256`, and `buildTokenRequest`+ * carries the `code_verifier`. Optional so existing (non-PKCE) adapters stay+ * unchanged. Refresh never uses PKCE.+ */+ usesPkce?: boolean/** Default scopes if recipe omits them. May be empty for providers that demand explicit scopes. */defaultScopes: ReadonlyArray<string>buildAuthorizeUrl(input: AuthorizeUrlInput): string@@ -113,6 +146,16 @@ function standardTokenRequest(input: TokenExchangeInput,extraHeaders: Record<string, string> = {}): TokenRequest {+ const params: Record<string, string> = {+ grant_type: 'authorization_code',+ code: input.code,+ client_id: input.clientId,+ client_secret: input.clientSecret,+ redirect_uri: input.redirectUri,+ }+ // PKCE: appended only when the adapter set `codeVerifier`. Non-PKCE adapters+ // pass no verifier, so their emitted body stays byte-identical.+ if (input.codeVerifier) params.code_verifier = input.codeVerifierreturn {url,method: 'POST',@@ -121,13 +164,7 @@ function standardTokenRequest(accept: 'application/json',...extraHeaders,},- body: urlEncode({- grant_type: 'authorization_code',- code: input.code,- client_id: input.clientId,- client_secret: input.clientSecret,- redirect_uri: input.redirectUri,- }),+ body: urlEncode(params),}}@@ -325,14 +362,192 @@ const GOOGLE: OAuthProviderAdapter = {parseTokenResponse: parseStandardOAuth2,}+// ─── monday (OAuth 2.1, PKCE) ───────────────────────────────────────────+//+// Docs: https://developer.monday.com/apps/docs/oauth (authorize) and+// https://developer.monday.com/apps/docs/migrating-to-the-new-oauth-flow+// (OAuth 2.1 token exchange + refresh, verified 2026-08-11).+// monday's OAuth 2.1 flow REQUIRES PKCE (code_challenge_method=S256) and issues+// short-lived access tokens + refresh tokens. The token endpoint is the OAuth 2.1+// endpoint `/oauth_ms/oauth/token` (distinct from the legacy `/oauth2/token`),+// and it takes a JSON body (verbatim per the migration doc's curl examples), NOT+// form-urlencoded. Confidential client: client_secret is sent together with+// code_verifier.+const MONDAY: OAuthProviderAdapter = {+ provider: 'monday',+ usesPkce: true,+ // monday requires explicit scopes; no safe default.+ defaultScopes: [],+ buildAuthorizeUrl({ clientId, redirectUri, state, scopes, codeChallenge }) {+ const params: Record<string, string> = {+ client_id: clientId,+ redirect_uri: redirectUri,+ response_type: 'code',+ state,+ }+ // monday uses space-separated scopes.+ if (scopes.length > 0) params.scope = scopes.join(' ')+ // PKCE is mandatory in monday's OAuth 2.1 flow — always emit BOTH.+ if (codeChallenge) {+ params.code_challenge = codeChallenge+ params.code_challenge_method = 'S256'+ }+ return `https://auth.monday.com/oauth2/authorize?${urlEncode(params)}`+ },+ buildTokenRequest(input) {+ // JSON body per the OAuth 2.1 migration doc (not form-urlencoded).+ const body: Record<string, string> = {+ grant_type: 'authorization_code',+ client_id: input.clientId,+ client_secret: input.clientSecret,+ code: input.code,+ redirect_uri: input.redirectUri,+ }+ if (input.codeVerifier) body.code_verifier = input.codeVerifier+ return {+ url: 'https://auth.monday.com/oauth_ms/oauth/token',+ method: 'POST',+ headers: { 'content-type': 'application/json', accept: 'application/json' },+ body: JSON.stringify(body),+ }+ },+ buildRefreshRequest(input) {+ return {+ url: 'https://auth.monday.com/oauth_ms/oauth/token',+ method: 'POST',+ headers: { 'content-type': 'application/json', accept: 'application/json' },+ body: JSON.stringify({+ grant_type: 'refresh_token',+ client_id: input.clientId,+ client_secret: input.clientSecret,+ refresh_token: input.refreshToken,+ }),+ }+ },+ parseTokenResponse: parseStandardOAuth2,+}++// ─── clickup (no PKCE, non-standard token endpoint, no refresh) ─────────+//+// Docs: https://developer.clickup.com/docs/authentication and+// https://developer.clickup.com/reference/getaccesstoken (verified+// 2026-08-11).+// ClickUp does NOT use PKCE. Its token endpoint is non-standard: the body carries+// ONLY client_id, client_secret, code — there is NO `grant_type` and NO+// `redirect_uri` (per the official Get Access Token reference). Tokens are+// non-expiring with NO refresh token, so buildRefreshRequest throws (like Notion)+// and parseTokenResponse returns no refreshToken/expiresIn. The `state` param IS+// round-tripped back on the redirect (verified) — it is ClickUp's only integrity+// binding, and the callback re-verifies its HMAC signature.+const CLICKUP: OAuthProviderAdapter = {+ provider: 'clickup',+ defaultScopes: [],+ buildAuthorizeUrl({ clientId, redirectUri, state }) {+ // ClickUp's authorize endpoint takes only client_id, redirect_uri, state —+ // no response_type, no scope query param.+ const params: Record<string, string> = {+ client_id: clientId,+ redirect_uri: redirectUri,+ state,+ }+ return `https://app.clickup.com/api?${urlEncode(params)}`+ },+ buildTokenRequest(input) {+ // Bespoke: no grant_type, no redirect_uri — ClickUp accepts a form-encoded+ // body of client_id + client_secret + code only.+ return {+ url: 'https://api.clickup.com/api/v2/oauth/token',+ method: 'POST',+ headers: {+ 'content-type': 'application/x-www-form-urlencoded',+ accept: 'application/json',+ },+ body: urlEncode({+ client_id: input.clientId,+ client_secret: input.clientSecret,+ code: input.code,+ }),+ }+ },+ buildRefreshRequest() {+ // ClickUp tokens do not expire and there is no refresh token to exchange.+ throw new Error('ClickUp does not support refresh tokens')+ },+ parseTokenResponse(body) {+ if (!isObject(body)) throw new Error('ClickUp token response must be an object')+ return {+ accessToken: asString(body['access_token'], 'access_token'),+ refreshToken: undefined,+ expiresIn: undefined,+ tokenType: asOptionalString(body['token_type'], 'token_type') ?? 'Bearer',+ }+ },+}++// ─── vercel (Sign in with Vercel, PKCE) ─────────────────────────────────+//+// Docs: https://vercel.com/docs/sign-in-with-vercel/authorization-server-api+// (verified 2026-08-11, doc last-updated 2026-03-30).+// Vercel REQUIRES `code_challenge` + `code_challenge_method=S256`. It issues a+// refresh token when the `offline_access` scope is requested, so that scope is in+// defaultScopes to earn one (mirrors microsoft-graph's baseline). client_secret is+// optional (confidential client accepted) — we send it. Standard form-encoded+// token + refresh; the shared helper appends code_verifier on the exchange.+const VERCEL: OAuthProviderAdapter = {+ provider: 'vercel',+ usesPkce: true,+ // offline_access earns a refresh token; openid/email/profile are the standard+ // Sign in with Vercel scopes. Recipe-supplied scopes override this baseline.+ defaultScopes: ['openid', 'email', 'profile', 'offline_access'],+ buildAuthorizeUrl({ clientId, redirectUri, state, scopes, codeChallenge }) {+ const effectiveScopes = scopes.length > 0 ? scopes : VERCEL.defaultScopes+ const params: Record<string, string> = {+ client_id: clientId,+ redirect_uri: redirectUri,+ response_type: 'code',+ scope: effectiveScopes.join(' '),+ state,+ }+ if (codeChallenge) {+ params.code_challenge = codeChallenge+ params.code_challenge_method = 'S256'+ }+ return `https://vercel.com/oauth/authorize?${urlEncode(params)}`+ },+ buildTokenRequest(input) {+ return standardTokenRequest('https://api.vercel.com/login/oauth/token', input)+ },+ buildRefreshRequest(input) {+ return standardRefreshRequest('https://api.vercel.com/login/oauth/token', input)+ },+ parseTokenResponse: parseStandardOAuth2,+}+const ADAPTERS: Record<OAuthProvider, OAuthProviderAdapter> = {salesforce: SALESFORCE,slack: SLACK,notion: NOTION,'microsoft-graph': MICROSOFT_GRAPH,google: GOOGLE,+ monday: MONDAY,+ clickup: CLICKUP,+ vercel: VERCEL,}export function getOAuthProviderAdapter(provider: OAuthProvider): OAuthProviderAdapter {return ADAPTERS[provider]}++/**+ * The single source of truth for "is this a known provider". Derived from+ * `ADAPTERS` so admission, authorize, callback, and refresh can never drift+ * (they previously kept three hand-maintained copies of this set). Iterable for+ * tests via `[...KNOWN_OAUTH_PROVIDERS]`.+ */+export const KNOWN_OAUTH_PROVIDERS: ReadonlySet<OAuthProvider> = new Set(+ Object.keys(ADAPTERS) as OAuthProvider[]+)++export function isKnownOAuthProvider(value: string): value is OAuthProvider {+ return KNOWN_OAUTH_PROVIDERS.has(value as OAuthProvider)+}diff --git a/control-api/src/oauth/tokenHelper.ts b/control-api/src/oauth/tokenHelper.tsindex e5d286348..e8166e5f6 100644--- a/control-api/src/oauth/tokenHelper.ts+++ b/control-api/src/oauth/tokenHelper.ts@@ -7,9 +7,9 @@ import {type SecretReader,} from './callback.js'import {- type OAuthProvider,type ParsedTokenResponse,getOAuthProviderAdapter,+ isKnownOAuthProvider,} from './providers.js'import { type OAuthGrantKey, getOAuthGrant, upsertOAuthGrant } from './store.js'@@ -85,7 +85,7 @@ export async function getAccessToken(const decl = recipe.spec?.oauthClients?.find(c => c.id === input.oauthClientId)if (!decl) return { kind: 'unknown_oauth_client' }- if (!isKnownProvider(decl.provider)) {+ if (!isKnownOAuthProvider(decl.provider)) {return { kind: 'unsupported_provider', provider: decl.provider }}@@ -173,15 +173,3 @@ export async function getAccessToken(: undefinedreturn { kind: 'ok', accessToken: parsed.accessToken, expiresAt }}--const KNOWN_PROVIDERS: ReadonlySet<OAuthProvider> = new Set([- 'salesforce',- 'slack',- 'notion',- 'microsoft-graph',- 'google',-])--function isKnownProvider(value: string): value is OAuthProvider {- return KNOWN_PROVIDERS.has(value as OAuthProvider)-}diff --git a/control-api/src/utils/log/redact.ts b/control-api/src/utils/log/redact.tsindex 9f4c52484..a72746bed 100644--- a/control-api/src/utils/log/redact.ts+++ b/control-api/src/utils/log/redact.ts@@ -17,6 +17,8 @@ export const TOKEN_LEAK_REDACT_PATHS: readonly string[] = ['claimToken','client_secret','clientSecret',+ 'code_verifier',+ 'codeVerifier',]/** Asserted by unit tests so redactions can grow but never shrink. */@@ -30,4 +32,6 @@ export const REQUIRED_REDACT_PATHS: readonly string[] = ['claimToken','client_secret','clientSecret',+ 'code_verifier',+ 'codeVerifier',]diff --git a/control-api/test/crd.mcpServerOauth.test.ts b/control-api/test/crd.mcpServerOauth.test.tsindex 8707b53c1..3b311d877 100644--- a/control-api/test/crd.mcpServerOauth.test.ts+++ b/control-api/test/crd.mcpServerOauth.test.ts@@ -52,13 +52,16 @@ describe('McpServer CRD — OAuth surface (U1)', () => {expect(grantScope.default).toBe('user')})- it('provider enum lists exactly the adapters shipped today (U2 extends monday/clickup/vercel)', () => {+ it('provider enum lists exactly the adapters shipped today (U2 adds monday/clickup/vercel)', () => {expect(specSchema.properties.oauth.properties.provider.enum).toEqual(['salesforce','slack','notion','microsoft-graph','google',+ 'monday',+ 'clickup',+ 'vercel',])})diff --git a/control-api/test/oauth.pkce.test.ts b/control-api/test/oauth.pkce.test.tsnew file mode 100644index 000000000..a7d8c78c4--- /dev/null+++ b/control-api/test/oauth.pkce.test.ts@@ -0,0 +1,207 @@+import { describe, expect, it, vi } from 'vitest'+import { createHash, randomBytes } from 'node:crypto'+import { buildAuthorizeUrl } from '../src/oauth/authorizeUrlHelper.js'+import {+ type CallbackDeps,+ type RecipeReader,+ type RecipeWithOAuthClients,+ type SecretReader,+ handleOAuthCallback,+} from '../src/oauth/callback.js'+import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'+import { computeCodeChallengeS256, deriveCodeVerifier } from '../src/oauth/pkce.js'+import type { OAuthProvider } from '../src/oauth/providers.js'++const STATE_SECRET = 'test-state-hmac-secret-32-bytes-padding'+const ENCRYPTION_KEY = deriveOAuthEncryptionKey(+ '00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff'+)++function base64urlSha256(input: string): string {+ return createHash('sha256').update(input).digest('base64url')+}++// ─── T2: property tests on the pure PKCE helpers ────────────────────────++describe('deriveCodeVerifier (PKCE, T2 properties)', () => {+ it('is deterministic: same secret + state ⇒ same verifier', () => {+ for (let i = 0; i < 2000; i++) {+ const state = randomBytes(24).toString('base64url')+ expect(deriveCodeVerifier(STATE_SECRET, state)).toBe(deriveCodeVerifier(STATE_SECRET, state))+ }+ })++ it('different state ⇒ different verifier (no collisions over a large sample)', () => {+ const seen = new Map<string, string>()+ for (let i = 0; i < 5000; i++) {+ const state = `v1.${randomBytes(24).toString('base64url')}.sig`+ const verifier = deriveCodeVerifier(STATE_SECRET, state)+ const prior = seen.get(verifier)+ // If two distinct states ever map to the same verifier, that's a break.+ if (prior !== undefined) expect(prior).toBe(state)+ seen.set(verifier, state)+ }+ })++ it('a different secret ⇒ different verifier for the same state', () => {+ const state = 'v1.payload.sig'+ expect(deriveCodeVerifier(STATE_SECRET, state)).not.toBe(+ deriveCodeVerifier(`${STATE_SECRET}-other`, state)+ )+ })++ it('verifier is always 43 chars and in the RFC 7636 base64url charset', () => {+ for (let i = 0; i < 2000; i++) {+ const state = randomBytes(1 + (i % 40)).toString('base64url')+ const verifier = deriveCodeVerifier(STATE_SECRET, state)+ expect(verifier).toHaveLength(43)+ expect(verifier).toMatch(/^[A-Za-z0-9_-]{43}$/)+ }+ })+})++describe('computeCodeChallengeS256 (PKCE)', () => {+ // RFC 7636 Appendix B.1 test vector — anchors the S256 transform.+ it('matches the RFC 7636 Appendix B.1 vector', () => {+ const verifier = 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk'+ expect(computeCodeChallengeS256(verifier)).toBe('E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM')+ })++ it('agrees with base64url(sha256(verifier)) for arbitrary verifiers', () => {+ for (let i = 0; i < 1000; i++) {+ const verifier = deriveCodeVerifier(STATE_SECRET, randomBytes(20).toString('base64url'))+ expect(computeCodeChallengeS256(verifier)).toBe(base64urlSha256(verifier))+ }+ })+})++// ─── T1: load-bearing round-trip through the REAL authorize + callback ──+//+// Produce a state via the real signOAuthState (inside buildAuthorizeUrl), pull+// the code_challenge off the authorize URL, run the SAME state through the real+// callback with a spy on the token request, and assert+// base64url(sha256(captured_verifier)) === extracted_challenge. The challenge is+// never hand-written — it's whatever the authorize URL emitted.++interface StubDb {+ query: ReturnType<typeof vi.fn>+}++function recipeFor(provider: OAuthProvider): RecipeWithOAuthClients {+ return {+ metadata: { name: 'connectors', namespace: 'sandbox-recipes' },+ spec: {+ oauthClients: [+ {+ id: 'oauth1',+ provider,+ clientIdRef: { name: 'creds', key: 'client-id' },+ clientSecretRef: { name: 'creds', key: 'client-secret' },+ scopes: [],+ },+ ],+ },+ }+}++function readers(provider: OAuthProvider): {+ recipeReader: RecipeReader+ secretReader: SecretReader+} {+ return {+ recipeReader: { read: vi.fn(async () => recipeFor(provider)) },+ secretReader: {+ read: vi.fn(async () => ({ 'client-id': 'CID', 'client-secret': 'CSEC' })),+ },+ }+}++/** Extract the token-exchange `code_verifier` from a captured fetch request. */+function extractCodeVerifier(body: string, contentType: string | undefined): string | undefined {+ if (contentType?.includes('application/json')) {+ return JSON.parse(body).code_verifier+ }+ return new URLSearchParams(body).get('code_verifier') ?? undefined+}++async function roundTrip(provider: OAuthProvider): Promise<{+ challenge: string | null+ verifier: string | undefined+}> {+ const { recipeReader, secretReader } = readers(provider)++ const authResult = await buildAuthorizeUrl(+ {+ recipeNamespace: 'sandbox-recipes',+ recipeName: 'connectors',+ oauthClientId: 'oauth1',+ userId: 'user-1',+ grantKind: 'user',+ redirectUri: 'https://control.example.com/api/v1/oauth-callback/oauth1',+ },+ { recipeReader, secretReader, stateSecret: STATE_SECRET }+ )+ expect(authResult.kind).toBe('ok')+ if (authResult.kind !== 'ok') throw new Error('authorize failed')++ const authUrl = new URL(authResult.authorizeUrl)+ const state = authUrl.searchParams.get('state')+ const challenge = authUrl.searchParams.get('code_challenge')+ expect(state).toBeTruthy()+ expect(authUrl.searchParams.get('code_challenge_method')).toBe('S256')++ // Spy on the token request; capture the outgoing verifier.+ let capturedVerifier: string | undefined+ const db: StubDb = { query: vi.fn().mockResolvedValue({ rows: [], rowCount: 0 }) }+ const fetchFn = vi.fn(+ async (_url: string, init: { body: string; headers: Record<string, string> }) => {+ capturedVerifier = extractCodeVerifier(init.body, init.headers['content-type'])+ return {+ ok: true,+ status: 200,+ json: async () => ({+ access_token: 'AT',+ refresh_token: 'RT',+ expires_in: 3600,+ token_type: 'Bearer',+ }),+ text: async () => '',+ } as Response+ }+ )++ const deps: CallbackDeps = {+ db: db as unknown as CallbackDeps['db'],+ recipeReader,+ secretReader,+ fetchFn: fetchFn as unknown as typeof fetch,+ stateSecret: STATE_SECRET,+ encryptionKey: ENCRYPTION_KEY,+ }++ const cbResult = await handleOAuthCallback(+ {+ oauthClientId: 'oauth1',+ code: 'AUTH_CODE',+ // The EXACT round-tripped state string.+ state: state as string,+ redirectUri: 'https://control.example.com/api/v1/oauth-callback/oauth1',+ },+ deps+ )+ expect(cbResult.kind).toBe('ok')+ expect(fetchFn).toHaveBeenCalledTimes(1)++ return { challenge, verifier: capturedVerifier }+}++describe('PKCE round-trip (T1, load-bearing) — authorize challenge binds to callback verifier', () => {+ for (const provider of ['monday', 'vercel'] as OAuthProvider[]) {+ it(`${provider}: sha256(callback verifier) === authorize code_challenge`, async () => {+ const { challenge, verifier } = await roundTrip(provider)+ expect(challenge).toBeTruthy()+ expect(verifier).toBeTruthy()+ expect(base64urlSha256(verifier as string)).toBe(challenge)+ })+ }+})diff --git a/control-api/test/oauth.providers.test.ts b/control-api/test/oauth.providers.test.tsindex 3ab736a85..4a7643ee2 100644--- a/control-api/test/oauth.providers.test.ts+++ b/control-api/test/oauth.providers.test.ts@@ -1,23 +1,39 @@import { describe, expect, it } from 'vitest'-import { type OAuthProvider, getOAuthProviderAdapter } from '../src/oauth/providers.js'+import {+ KNOWN_OAUTH_PROVIDERS,+ type OAuthProvider,+ getOAuthProviderAdapter,+} from '../src/oauth/providers.js'const REDIRECT = 'https://control.example.com/api/v1/oauth-callback/salesforce'+/** The provider list is derived from the adapter registry — never hardcoded. */+const ALL_PROVIDERS: OAuthProvider[] = [...KNOWN_OAUTH_PROVIDERS]+function urlParams(url: string): URLSearchParams {return new URL(url).searchParams}describe('getOAuthProviderAdapter (O2.1)', () => {it('returns the right adapter for every supported provider', () => {- const all: OAuthProvider[] = ['salesforce', 'slack', 'notion', 'microsoft-graph', 'google']- for (const p of all) {+ for (const p of ALL_PROVIDERS) {const a = getOAuthProviderAdapter(p)expect(a.provider).toBe(p)expect(typeof a.buildAuthorizeUrl).toBe('function')expect(typeof a.buildTokenRequest).toBe('function')+ expect(typeof a.buildRefreshRequest).toBe('function')expect(typeof a.parseTokenResponse).toBe('function')}})++ // T5 invariant: every registry key resolves and exposes all four methods.+ it('every KNOWN_OAUTH_PROVIDERS key resolves via getOAuthProviderAdapter', () => {+ expect(ALL_PROVIDERS.length).toBeGreaterThanOrEqual(8)+ for (const p of ALL_PROVIDERS) {+ const a = getOAuthProviderAdapter(p)+ expect(a.provider).toBe(p)+ }+ })})describe('Salesforce adapter (O2.1)', () => {@@ -201,3 +217,237 @@ describe('Google adapter (O2.1)', () => {expect(p.get('prompt')).toBe('consent')})})++// ─── U2: monday / clickup / vercel ──────────────────────────────────────++describe('monday adapter (U2, PKCE)', () => {+ const a = getOAuthProviderAdapter('monday')++ it('declares usesPkce', () => {+ expect(a.usesPkce).toBe(true)+ })++ it('builds the authorize URL with code_challenge + code_challenge_method=S256 and space-separated scopes', () => {+ const url = a.buildAuthorizeUrl({+ clientId: 'cid',+ redirectUri: REDIRECT,+ state: 'signed-state',+ scopes: ['boards:read', 'me:read'],+ codeChallenge: 'CHALLENGE',+ })+ expect(url.startsWith('https://auth.monday.com/oauth2/authorize?')).toBe(true)+ const p = urlParams(url)+ expect(p.get('client_id')).toBe('cid')+ expect(p.get('response_type')).toBe('code')+ expect(p.get('state')).toBe('signed-state')+ expect(p.get('scope')).toBe('boards:read me:read')+ expect(p.get('code_challenge')).toBe('CHALLENGE')+ expect(p.get('code_challenge_method')).toBe('S256')+ })++ it('builds the token POST as JSON to the OAuth 2.1 endpoint, carrying code_verifier', () => {+ const req = a.buildTokenRequest({+ code: 'thecode',+ clientId: 'cid',+ clientSecret: 'csec',+ redirectUri: REDIRECT,+ codeVerifier: 'VERIFIER',+ })+ expect(req.url).toBe('https://auth.monday.com/oauth_ms/oauth/token')+ expect(req.headers['content-type']).toBe('application/json')+ const body = JSON.parse(req.body)+ expect(body.grant_type).toBe('authorization_code')+ expect(body.client_id).toBe('cid')+ expect(body.client_secret).toBe('csec') // confidential client+ expect(body.code).toBe('thecode')+ expect(body.redirect_uri).toBe(REDIRECT)+ expect(body.code_verifier).toBe('VERIFIER')+ })++ it('builds a refresh request that carries NO code_verifier', () => {+ const req = a.buildRefreshRequest({ refreshToken: 'RT', clientId: 'cid', clientSecret: 'csec' })+ expect(req.url).toBe('https://auth.monday.com/oauth_ms/oauth/token')+ const body = JSON.parse(req.body)+ expect(body.grant_type).toBe('refresh_token')+ expect(body.refresh_token).toBe('RT')+ expect(body.code_verifier).toBeUndefined()+ })++ it('parses a standard token response', () => {+ const parsed = a.parseTokenResponse({+ access_token: 'AT',+ refresh_token: 'RT',+ expires_in: 3600,+ token_type: 'Bearer',+ })+ expect(parsed.accessToken).toBe('AT')+ expect(parsed.refreshToken).toBe('RT')+ expect(parsed.expiresIn).toBe(3600)+ })+})++describe('clickup adapter (U2, no PKCE, no refresh)', () => {+ const a = getOAuthProviderAdapter('clickup')++ it('does NOT declare usesPkce', () => {+ expect(a.usesPkce).toBeFalsy()+ })++ it('builds an authorize URL carrying state but NO code_challenge/method/scope', () => {+ const url = a.buildAuthorizeUrl({+ clientId: 'cid',+ redirectUri: REDIRECT,+ state: 'signed-state',+ scopes: ['ignored'],+ })+ expect(url.startsWith('https://app.clickup.com/api?')).toBe(true)+ const p = urlParams(url)+ expect(p.get('client_id')).toBe('cid')+ expect(p.get('redirect_uri')).toBe(REDIRECT)+ expect(p.get('state')).toBe('signed-state')+ expect(p.has('code_challenge')).toBe(false)+ expect(p.has('code_challenge_method')).toBe(false)+ expect(p.has('scope')).toBe(false)+ })++ it('builds a bespoke token POST: form body, no grant_type, no redirect_uri', () => {+ const req = a.buildTokenRequest({+ code: 'thecode',+ clientId: 'cid',+ clientSecret: 'csec',+ redirectUri: REDIRECT,+ })+ expect(req.url).toBe('https://api.clickup.com/api/v2/oauth/token')+ expect(req.headers['content-type']).toBe('application/x-www-form-urlencoded')+ const p = new URLSearchParams(req.body)+ expect(p.get('client_id')).toBe('cid')+ expect(p.get('client_secret')).toBe('csec')+ expect(p.get('code')).toBe('thecode')+ expect(p.has('grant_type')).toBe(false)+ expect(p.has('redirect_uri')).toBe(false)+ })++ it('throws on refresh — ClickUp tokens do not expire', () => {+ expect(() =>+ a.buildRefreshRequest({ refreshToken: 'r', clientId: 'c', clientSecret: 's' })+ ).toThrow(/does not support refresh tokens/)+ })++ it('parses a response with only access_token (no refresh/expiry)', () => {+ const parsed = a.parseTokenResponse({ access_token: 'AT' })+ expect(parsed.accessToken).toBe('AT')+ expect(parsed.refreshToken).toBeUndefined()+ expect(parsed.expiresIn).toBeUndefined()+ expect(parsed.tokenType).toBe('Bearer')+ })+})++describe('vercel adapter (U2, PKCE)', () => {+ const a = getOAuthProviderAdapter('vercel')++ it('declares usesPkce', () => {+ expect(a.usesPkce).toBe(true)+ })++ it('builds the authorize URL with code_challenge + S256 and offline_access default scope', () => {+ const url = a.buildAuthorizeUrl({+ clientId: 'cid',+ redirectUri: REDIRECT,+ state: 'signed-state',+ scopes: [],+ codeChallenge: 'CHALLENGE',+ })+ expect(url.startsWith('https://vercel.com/oauth/authorize?')).toBe(true)+ const p = urlParams(url)+ expect(p.get('response_type')).toBe('code')+ expect(p.get('code_challenge')).toBe('CHALLENGE')+ expect(p.get('code_challenge_method')).toBe('S256')+ expect(p.get('scope')?.split(' ')).toContain('offline_access')+ })++ it('uses recipe-supplied scopes when present', () => {+ const url = a.buildAuthorizeUrl({+ clientId: 'cid',+ redirectUri: REDIRECT,+ state: 's',+ scopes: ['openid'],+ codeChallenge: 'C',+ })+ expect(urlParams(url).get('scope')).toBe('openid')+ })++ it('builds a standard form token POST carrying code_verifier to the vercel token endpoint', () => {+ const req = a.buildTokenRequest({+ code: 'thecode',+ clientId: 'cid',+ clientSecret: 'csec',+ redirectUri: REDIRECT,+ codeVerifier: 'VERIFIER',+ })+ expect(req.url).toBe('https://api.vercel.com/login/oauth/token')+ expect(req.headers['content-type']).toBe('application/x-www-form-urlencoded')+ expect(req.body).toContain('grant_type=authorization_code')+ expect(req.body).toContain('client_secret=csec') // confidential client accepted+ expect(req.body).toContain('code_verifier=VERIFIER')+ })++ it('refresh uses the refresh_token grant and carries NO code_verifier', () => {+ const req = a.buildRefreshRequest({ refreshToken: 'RT', clientId: 'cid', clientSecret: 'csec' })+ expect(req.url).toBe('https://api.vercel.com/login/oauth/token')+ expect(req.body).toContain('grant_type=refresh_token')+ expect(req.body).not.toContain('code_verifier')+ })+})++// ─── T1: byte-identical golden for the 5 pre-existing (non-PKCE) adapters ─+//+// Snapshots the authorize URL + token request bytes for the recipe-path adapters,+// called EXACTLY as the recipe flow calls them (no PKCE inputs — the caller gates+// PKCE fields on adapter.usesPkce, which is false here). Asserts NO PKCE parameter+// appears. Guards that adding PKCE to the registry did not alter the recipe flow.+//+// The golden values below are the literal bytes emitted before U2; a diff here+// means the recipe path changed.+describe('T1 byte-identical golden — pre-existing adapters carry no PKCE', () => {+ const LEGACY: OAuthProvider[] = ['salesforce', 'slack', 'notion', 'microsoft-graph', 'google']++ const GOLDEN_AUTHORIZE: Record<string, string> = {+ salesforce:+ 'https://login.salesforce.com/services/oauth2/authorize?response_type=code&client_id=cid&redirect_uri=https%3A%2F%2Fcontrol.example.com%2Fapi%2Fv1%2Foauth-callback%2Fsalesforce&state=signed-state&scope=scope-a',+ slack:+ 'https://slack.com/oauth/v2/authorize?client_id=cid&redirect_uri=https%3A%2F%2Fcontrol.example.com%2Fapi%2Fv1%2Foauth-callback%2Fsalesforce&state=signed-state&scope=scope-a',+ notion:+ 'https://api.notion.com/v1/oauth/authorize?client_id=cid&redirect_uri=https%3A%2F%2Fcontrol.example.com%2Fapi%2Fv1%2Foauth-callback%2Fsalesforce&response_type=code&owner=user&state=signed-state',+ 'microsoft-graph':+ 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=cid&redirect_uri=https%3A%2F%2Fcontrol.example.com%2Fapi%2Fv1%2Foauth-callback%2Fsalesforce&response_type=code&response_mode=query&scope=scope-a&state=signed-state',+ google:+ 'https://accounts.google.com/o/oauth2/v2/auth?client_id=cid&redirect_uri=https%3A%2F%2Fcontrol.example.com%2Fapi%2Fv1%2Foauth-callback%2Fsalesforce&response_type=code&access_type=offline&prompt=consent&state=signed-state&scope=scope-a',+ }++ for (const provider of LEGACY) {+ it(`${provider} authorize URL + token request are byte-identical and PKCE-free`, () => {+ const a = getOAuthProviderAdapter(provider)+ expect(a.usesPkce).toBeFalsy()++ // Called exactly as the recipe path calls it: no codeChallenge.+ const authorizeUrl = a.buildAuthorizeUrl({+ clientId: 'cid',+ redirectUri: REDIRECT,+ state: 'signed-state',+ scopes: ['scope-a'],+ })+ expect(authorizeUrl).toBe(GOLDEN_AUTHORIZE[provider])+ expect(authorizeUrl).not.toContain('code_challenge')++ // No codeVerifier — the recipe path never supplies one for a non-PKCE adapter.+ const tokenReq = a.buildTokenRequest({+ code: 'c',+ clientId: 'cid',+ clientSecret: 'csec',+ redirectUri: REDIRECT,+ })+ expect(tokenReq.body).not.toContain('code_verifier')+ expect(tokenReq.body).not.toContain('code_challenge')+ })+ }+})diff --git a/control-api/test/utils.log.redact.test.ts b/control-api/test/utils.log.redact.test.tsindex 6fbcd69c8..c6e2a3252 100644--- a/control-api/test/utils.log.redact.test.ts+++ b/control-api/test/utils.log.redact.test.ts@@ -32,4 +32,11 @@ describe('token-leak redaction', () => {expect(REQUIRED_REDACT_PATHS).toContain(p)}})++ it('redacts the PKCE code_verifier (U2) in both snake and camel case', () => {+ for (const p of ['code_verifier', 'codeVerifier']) {+ expect(TOKEN_LEAK_REDACT_PATHS).toContain(p)+ expect(REQUIRED_REDACT_PATHS).toContain(p)+ }+ })})diff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.jsonindex 427d02206..f5dc2c0a1 100644--- a/workflow-recipes/package-lock.json+++ b/workflow-recipes/package-lock.json@@ -1,6 +1,6 @@{"name": "workload-recipes-controller",- "version": "0.1.280",+ "version": "0.1.281","lockfileVersion": 3,"requires": true,"packages": {@@ -34,7 +34,7 @@"engines": {"node": ">=24"},- "version": "0.1.280"+ "version": "0.1.281"},"../packages/image-policy": {"name": "@clerum/image-policy",diff --git a/workflow-recipes/package.json b/workflow-recipes/package.jsonindex 06f686096..52775d099 100644--- a/workflow-recipes/package.json+++ b/workflow-recipes/package.json@@ -1,6 +1,6 @@{"name": "workload-recipes-controller",- "version": "0.1.280",+ "version": "0.1.281","description": "Workload Recipes Controller (WRC) - WorkloadRecipe lifecycle management and MCP server interface","main": "dist/main.js","engines": {diff --git a/workflow-recipes/src/types.test.ts b/workflow-recipes/src/types.test.tsindex d15ab04e8..c2ae5479f 100644--- a/workflow-recipes/src/types.test.ts+++ b/workflow-recipes/src/types.test.ts@@ -503,12 +503,15 @@ describe('WorkflowRecipePolicySpec nested structure (Risk 1.2)', () => {})describe('isOAuthProvider (O1.1)', () => {- it('accepts the five known-shape providers', () => {+ it('accepts the eight known-shape providers', () => {expect(isOAuthProvider('salesforce')).toBe(true)expect(isOAuthProvider('slack')).toBe(true)expect(isOAuthProvider('notion')).toBe(true)expect(isOAuthProvider('microsoft-graph')).toBe(true)expect(isOAuthProvider('google')).toBe(true)+ expect(isOAuthProvider('monday')).toBe(true)+ expect(isOAuthProvider('clickup')).toBe(true)+ expect(isOAuthProvider('vercel')).toBe(true)})it('rejects misspellings, casing, and unknown providers', () => {@@ -517,10 +520,21 @@ describe('isOAuthProvider (O1.1)', () => {expect(isOAuthProvider('github')).toBe(false)expect(isOAuthProvider('google-workspace')).toBe(false)expect(isOAuthProvider('microsoft')).toBe(false)+ expect(isOAuthProvider('Monday')).toBe(false)+ expect(isOAuthProvider('click-up')).toBe(false)})it('covers every OAuthProvider branch (exhaustiveness)', () => {- const all: OAuthProvider[] = ['salesforce', 'slack', 'notion', 'microsoft-graph', 'google']+ const all: OAuthProvider[] = [+ 'salesforce',+ 'slack',+ 'notion',+ 'microsoft-graph',+ 'google',+ 'monday',+ 'clickup',+ 'vercel',+ ]for (const p of all) {expect(isOAuthProvider(p)).toBe(true)}diff --git a/workflow-recipes/src/types.ts b/workflow-recipes/src/types.tsindex 0e26a2edb..f8bb32664 100644--- a/workflow-recipes/src/types.ts+++ b/workflow-recipes/src/types.ts@@ -430,10 +430,27 @@ export interface SandboxUiSpec {* provider is a control-api change — recipes cannot speak OAuth to* arbitrary endpoints. Spec §9.9 / Decision 20.*/-export type OAuthProvider = 'salesforce' | 'slack' | 'notion' | 'microsoft-graph' | 'google'+export type OAuthProvider =+ | 'salesforce'+ | 'slack'+ | 'notion'+ | 'microsoft-graph'+ | 'google'+ | 'monday'+ | 'clickup'+ | 'vercel'export function isOAuthProvider(value: string): value is OAuthProvider {- return ['salesforce', 'slack', 'notion', 'microsoft-graph', 'google'].includes(value)+ return [+ 'salesforce',+ 'slack',+ 'notion',+ 'microsoft-graph',+ 'google',+ 'monday',+ 'clickup',+ 'vercel',+ ].includes(value)}/** Reference to a Secret in the recipe's sandbox-recipes namespace. */