Repository navigation
Add connect OAuth page and connector registry - #87
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds a multi-step OAuth connector flow: a new client route at /connect/oauth, MCP capabilities for connector CRUD, shared connector validation utilities, and account-secrets API handlers to persist connector configs and OAuth secrets. Changes
Sequence DiagramsequenceDiagram
actor User
participant Client as Client<br/>/connect/oauth
participant API as Account Secrets<br/>API Handler
participant Store as Value/Secret<br/>Store
participant Provider as OAuth<br/>Provider
User->>Client: Open /connect/oauth with config
Client->>Client: Normalize & persist client metadata (sessionStorage / value_set)
Client->>Provider: Redirect to authorize (state, PKCE if used)
Provider->>Client: Callback (code, state)
Client->>Client: Validate state
Client->>Provider: POST token URL (code + verifier or client secret)
Provider-->>Client: Token response (access/refresh)
Client->>API: POST /account/secrets.json action: connect_oauth (token payload)
API->>Store: Save access token secret (with allowed hosts)
API->>Store: Save refresh token secret (if present)
API->>Store: Save connector config value
Store-->>API: Saved
API-->>Client: Success with metadata
Client->>User: Render success/details
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related issues
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
@cursoragent let's just make this a regular remix route rather than trying to reuse the Kody utils and execute. Because this is official integration code we can make it simpler that way. I don't mind having a bit of duplication with the Kody utils. Should simplify things considerably |
|
🔎 Preview deployed: https://kody-pr-87.kentcdodds.workers.dev Worker: Mocks:
|
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (6)
packages/worker/src/mcp/capabilities/values/connector-get.ts (1)
58-64: Consider extracting the duplicatedparseConnectorJsonhelper.This helper function is duplicated in
connector-get.ts,connector-list.ts, andconnector-save.ts. Consider moving it toconnector-shared.tsfor DRY.♻️ Proposed refactor
In
connector-shared.ts, add:export function parseConnectorJson(raw: string): unknown { try { return JSON.parse(raw) } catch { return null } }Then import and use it in all three files.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/worker/src/mcp/capabilities/values/connector-get.ts` around lines 58 - 64, Duplicate parseConnectorJson implementation should be extracted into a single exported helper and reused: create an exported function parseConnectorJson(raw: string): unknown in a shared module (connector-shared) that returns JSON.parse(raw) or null on parse errors, then replace the local parseConnectorJson definitions in connector-get.ts, connector-list.ts, and connector-save.ts with an import from that shared module and remove the duplicated code; ensure the imported symbol name matches parseConnectorJson and update any local references to call the shared helper.packages/worker/src/mcp/capabilities/values/connector-save.ts (1)
80-86: Re-parsing after save is defensive but adds overhead.The handler serializes a normalized config, saves it, then re-parses the saved value. Since
saveValuereturns the exact value that was stored, this re-parse is redundant unless you're validating storage integrity. The fallbackparsed ?? connectorensures correctness regardless.This pattern is safe but consider returning
connectordirectly if storage integrity isn't a concern:♻️ Simplified return
- const parsed = parseConnectorConfig( - parseConnectorJson(value.value), - connector.name, - ) - return { - connector: parsed ?? connector, - } + return { connector }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/worker/src/mcp/capabilities/values/connector-save.ts` around lines 80 - 86, The handler currently re-parses the saved connector config using parseConnectorJson and parseConnectorConfig and returns connector: parsed ?? connector; remove the redundant re-parse and simply return the original connector after save (i.e., replace the parsed logic and the connector: parsed ?? connector return with a direct return of connector). Update the code paths around parseConnectorJson, parseConnectorConfig and the return that references parsed so the saved value isn't re-parsed unnecessarily.packages/worker/src/app/connect-oauth-page.ts (3)
106-115:coerceStringArrayis defined but never used.This function appears to be dead code. Consider removing it to reduce bundle size.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/worker/src/app/connect-oauth-page.ts` around lines 106 - 115, The function coerceStringArray is defined but unused; remove the dead code by deleting the coerceStringArray function declaration (and any related unused imports/refs) so it no longer appears in the module, or if it was intended to be used, replace/remove its callers to use an existing utility; search for the identifier "coerceStringArray" and either delete the function or wire its correct usage where needed (e.g., replace with the project’s canonical string-array coercion helper).
13-27: Type inconsistency forrefreshTokenSecretName.The type declares
refreshTokenSecretName: string(always defined), but:
- The
connector_savecapability schema (per context snippet) defines it asz.string().nullable()- The inline script treats it as potentially falsy at lines 151 and 344
Since the handler always sets this to
${providerKey}RefreshToken, the fallback logic in the UI is dead code. Consider either:
- Making the type
string | nullif you want to support not saving refresh tokens- Removing the fallback handling in the script if it's always required
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/worker/src/app/connect-oauth-page.ts` around lines 13 - 27, The ConnectOauthPageConfig type declares refreshTokenSecretName as always string but elsewhere (connector_save z.schema and the inline script logic around refresh token handling) treat it as nullable/falsy; update the ConnectOauthPageConfig declaration to make refreshTokenSecretName: string | null to match the connector_save schema and existing script logic, and audit usages of refreshTokenSecretName (e.g., anywhere that checks truthiness in the inline script or functions that read this property) to ensure they correctly handle null values; alternatively, if you prefer refresh tokens to be mandatory, remove the nullable handling in the schema and the fallback code in the script, but keep types and runtime logic consistent (refer to ConnectOauthPageConfig and the inline script checks around refreshTokenSecretName).
261-267: PKCE verifier using UUID may not meet RFC 7636 recommendations.
crypto.randomUUID()produces a 36-character hyphenated string. RFC 7636 recommends a verifier of 43-128 unreserved characters (generated from 32+ octets of random data). While this may work with most providers, some strict implementations could reject it.🔐 Recommended: Generate a proper PKCE verifier
- const verifier = crypto.randomUUID() + const randomBytes = new Uint8Array(32) + crypto.getRandomValues(randomBytes) + const verifier = base64UrlEncode(randomBytes)This produces a 43-character base64url string meeting the RFC 7636 specification.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/worker/src/app/connect-oauth-page.ts` around lines 261 - 267, The PKCE verifier generation using crypto.randomUUID() (in the params.flow === 'pkce' branch where you set pkceVerifierKey and call createCodeChallenge) does not conform to RFC 7636; replace it with a verifier produced from 32+ bytes of cryptographically random data, base64url-encoded (no padding) to yield a 43+ character unreserved string, store that value with storage.setItem(pkceVerifierKey, verifier), then pass it to createCodeChallenge unchanged; ensure the encoding removes '+' '/' and '=' (i.e., base64url) and that you use a secure RNG (crypto.randomBytes in Node or crypto.getRandomValues in browsers).packages/worker/src/app/handlers/connect-oauth.ts (1)
130-138: Consider consolidating identical helper functions.
readRequiredParamandreadOptionalParamhave identical implementations. While keeping them separate documents intent, you could DRY this up with a single helper.♻️ Optional: Consolidate helpers
-function readRequiredParam(url: URL, key: string) { - const value = url.searchParams.get(key) - return value && value.trim() ? value.trim() : null -} - -function readOptionalParam(url: URL, key: string) { - const value = url.searchParams.get(key) - return value && value.trim() ? value.trim() : null -} +function readParam(url: URL, key: string) { + const value = url.searchParams.get(key) + return value && value.trim() ? value.trim() : null +}Then use
readParamthroughout, relying on the validation logic to enforce required vs optional semantics.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/worker/src/app/handlers/connect-oauth.ts` around lines 130 - 138, readRequiredParam and readOptionalParam are identical; replace them with a single helper (e.g., readParam) and update call sites to use it, keeping required-versus-optional semantics enforced where those helpers are consumed (e.g., validate presence in the code paths that previously relied on readRequiredParam). Specifically, remove readRequiredParam and readOptionalParam, add readParam(url: URL, key: string) that returns trimmed string or null, and adjust functions/logic that need a required param to explicitly check for null and throw/return an error while optional usages simply accept the null.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/worker/src/app/connect-oauth-page.ts`:
- Line 502: The template interpolates user-controlled input.config.provider
directly into HTML (e.g., in the page title and other template spots), creating
an XSS vector; add an HTML-escaping helper (e.g., escapeHtml(str: string)) and
replace all raw uses of input.config.provider with
escapeHtml(input.config.provider) in the connect-oauth-page template and any
other occurrences (lines referencing the provider interpolation such as the
title and the two other spots) so that &, <, >, " and ' are replaced with their
HTML entities before rendering.
- Around line 481-494: The code calls hasCallback() from init() but that
function is missing, causing a ReferenceError at runtime; add a new
hasCallback() function (used by init(), handleCallback(), and showStep()) that
inspects the current window.location (query params or hash) for the expected
callback marker (e.g., a specific query key like "code" or "oauth_callback") and
returns a boolean, then place it above init() so renderProviderDetails(),
renderRequiredHosts(), wireEvents(), init(), handleCallback(), showStep(), and
showSetupOrConnect() can call it reliably.
In `@packages/worker/src/app/handlers/connect-oauth.ts`:
- Around line 24-27: The TS narrowing fails because parseConnectOauthConfig
lacks an explicit discriminated-union return type; update
parseConnectOauthConfig to return a typed union like { ok: true; config:
ConnectOauthPageConfig } | { ok: false; error: string } so checks on
configResult.ok let TypeScript narrow to configResult.error (string) and
configResult.config (ConnectOauthPageConfig); ensure any callers (e.g., the
usage in connect-oauth handler that calls parseConnectOauthConfig and
renderConnectOauthError) treat the result according to the new discriminant.
---
Nitpick comments:
In `@packages/worker/src/app/connect-oauth-page.ts`:
- Around line 106-115: The function coerceStringArray is defined but unused;
remove the dead code by deleting the coerceStringArray function declaration (and
any related unused imports/refs) so it no longer appears in the module, or if it
was intended to be used, replace/remove its callers to use an existing utility;
search for the identifier "coerceStringArray" and either delete the function or
wire its correct usage where needed (e.g., replace with the project’s canonical
string-array coercion helper).
- Around line 13-27: The ConnectOauthPageConfig type declares
refreshTokenSecretName as always string but elsewhere (connector_save z.schema
and the inline script logic around refresh token handling) treat it as
nullable/falsy; update the ConnectOauthPageConfig declaration to make
refreshTokenSecretName: string | null to match the connector_save schema and
existing script logic, and audit usages of refreshTokenSecretName (e.g.,
anywhere that checks truthiness in the inline script or functions that read this
property) to ensure they correctly handle null values; alternatively, if you
prefer refresh tokens to be mandatory, remove the nullable handling in the
schema and the fallback code in the script, but keep types and runtime logic
consistent (refer to ConnectOauthPageConfig and the inline script checks around
refreshTokenSecretName).
- Around line 261-267: The PKCE verifier generation using crypto.randomUUID()
(in the params.flow === 'pkce' branch where you set pkceVerifierKey and call
createCodeChallenge) does not conform to RFC 7636; replace it with a verifier
produced from 32+ bytes of cryptographically random data, base64url-encoded (no
padding) to yield a 43+ character unreserved string, store that value with
storage.setItem(pkceVerifierKey, verifier), then pass it to createCodeChallenge
unchanged; ensure the encoding removes '+' '/' and '=' (i.e., base64url) and
that you use a secure RNG (crypto.randomBytes in Node or crypto.getRandomValues
in browsers).
In `@packages/worker/src/app/handlers/connect-oauth.ts`:
- Around line 130-138: readRequiredParam and readOptionalParam are identical;
replace them with a single helper (e.g., readParam) and update call sites to use
it, keeping required-versus-optional semantics enforced where those helpers are
consumed (e.g., validate presence in the code paths that previously relied on
readRequiredParam). Specifically, remove readRequiredParam and
readOptionalParam, add readParam(url: URL, key: string) that returns trimmed
string or null, and adjust functions/logic that need a required param to
explicitly check for null and throw/return an error while optional usages simply
accept the null.
In `@packages/worker/src/mcp/capabilities/values/connector-get.ts`:
- Around line 58-64: Duplicate parseConnectorJson implementation should be
extracted into a single exported helper and reused: create an exported function
parseConnectorJson(raw: string): unknown in a shared module (connector-shared)
that returns JSON.parse(raw) or null on parse errors, then replace the local
parseConnectorJson definitions in connector-get.ts, connector-list.ts, and
connector-save.ts with an import from that shared module and remove the
duplicated code; ensure the imported symbol name matches parseConnectorJson and
update any local references to call the shared helper.
In `@packages/worker/src/mcp/capabilities/values/connector-save.ts`:
- Around line 80-86: The handler currently re-parses the saved connector config
using parseConnectorJson and parseConnectorConfig and returns connector: parsed
?? connector; remove the redundant re-parse and simply return the original
connector after save (i.e., replace the parsed logic and the connector: parsed
?? connector return with a direct return of connector). Update the code paths
around parseConnectorJson, parseConnectorConfig and the return that references
parsed so the saved value isn't re-parsed unnecessarily.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: c6f00c5a-cbef-4ef5-b722-41fa78c0fbb5
📒 Files selected for processing (10)
packages/worker/src/app/connect-oauth-page.tspackages/worker/src/app/handlers/connect-oauth.tspackages/worker/src/app/router.tspackages/worker/src/app/routes.tspackages/worker/src/mcp/capabilities/values/connector-delete.tspackages/worker/src/mcp/capabilities/values/connector-get.tspackages/worker/src/mcp/capabilities/values/connector-list.tspackages/worker/src/mcp/capabilities/values/connector-save.tspackages/worker/src/mcp/capabilities/values/connector-shared.tspackages/worker/src/mcp/capabilities/values/domain.ts
|
@cursoragent please check CI on this PR and fix any issues. Also address any valid feedback on this PR |
This comment has been minimized.
This comment has been minimized.
|
@cursoragent please address any valid feedback on this PR |
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
Actionable comments posted: 4
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/worker/src/app/connect-oauth-page.ts`:
- Around line 185-224: The current Promise.all on tasks can persist the client
ID even if saving the client secret fails; change the flow in the connect logic
so that for confidential connectors you perform the secret save first (await
kodyWidget.saveSecret in connect-oauth-page.ts inside the confidential branch)
and only proceed to save the client ID (kodyWidget.saveValue) if the secret save
succeeded, then handle errors immediately (updateStatus/sendMessage/return)
before any client ID persists; likewise update the other occurrence mentioned
(lines ~445-452) to the same sequential, failure-safe ordering so
showSetupOrConnect cannot see a saved client ID without its secret.
- Around line 429-443: The callback handler (handleCallback) reads the OAuth
callback via kodyWidget.readOAuthCallback and exchanges the code with
exchangeCode, but it never clears the one-time callback query params, causing
re-entry on refresh; after successfully reading a callback (both in
handleCallback and any other block that calls kodyWidget.readOAuthCallback),
remove the code/state query params from the browser URL (e.g., via
history.replaceState or equivalent) so the page no longer re-enters callback
mode on refresh or history navigation while keeping the rest of the flow (only
perform the URL cleanup after callback.kind === 'success' or after handling the
callback).
- Around line 332-337: The current flow routes partial failures into the success
UI: when result?.kind === 'host_approval_required' (and similarly where
connectorSaved is false) the code calls updateStatus, renderApprovalDetails,
saveConnectorConfig and then showStep('success'); change this so that you do NOT
call showStep('success') for blocked/partial cases — instead introduce and call
a new step like showStep('blocked') or showStep('partial_success') (and add
corresponding UI handling), or only call showStep('success') after
saveConnectorConfig confirms persistence and token exchange completed; update
the logic in the blocks that use result?.kind, saveConnectorConfig,
updateStatus, renderApprovalDetails and any other similar sections (including
the other occurrences mentioned) to use the new blocked/partial-success step
when token exchange is pending or connectorSaved is false.
- Around line 260-279: When applying params.extraAuthorizeParams in
connect-oauth-page.ts, skip any keys that would override core OAuth values by
filtering out a reserved set (at minimum: response_type, client_id,
redirect_uri, scope, state, code_challenge, code_challenge_method); update the
loop that iterates params.extraAuthorizeParams to ignore these reserved names
before calling url.searchParams.set so generated values from
createOAuthState/stateKey, getRedirectUri, PKCE (createCodeVerifier,
createCodeChallenge, pkceVerifierKey) and scope handling are never overwritten;
keep using isValidParamName for additional validation and convert keys
consistently (e.g., exact match) when checking against the reserved set.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: bca3ff3c-a5f2-471b-84cc-70050b5be895
📒 Files selected for processing (1)
packages/worker/src/app/connect-oauth-page.ts
| const tasks = [ | ||
| kodyWidget.saveValue({ | ||
| name: params.clientIdValueName, | ||
| value: clientId, | ||
| description: \`\${params.provider} OAuth client ID\`, | ||
| scope: 'user', | ||
| }), | ||
| ] | ||
| if (params.flow === 'confidential') { | ||
| if (!params.clientSecretSecretName) { | ||
| updateStatus('Missing client secret name for confidential flow.', 'error') | ||
| kodyWidget.sendMessage( | ||
| 'Missing client secret name for confidential flow. Check the connector setup parameters.', | ||
| ) | ||
| return | ||
| } | ||
| if (!clientSecret) { | ||
| updateStatus('Client secret is required for confidential flow.', 'error') | ||
| kodyWidget.sendMessage( | ||
| 'Client secret is required for confidential flow before connecting.', | ||
| ) | ||
| return | ||
| } | ||
| tasks.push( | ||
| kodyWidget.saveSecret({ | ||
| name: params.clientSecretSecretName, | ||
| value: clientSecret, | ||
| description: \`\${params.provider} OAuth client secret\`, | ||
| scope: 'user', | ||
| }), | ||
| ) | ||
| } | ||
| setVisibility('[data-secret-row]', params.flow === 'confidential') | ||
| const results = await Promise.all(tasks) | ||
| const failed = results.find((result) => !result.ok) | ||
| if (failed) { | ||
| updateStatus('Unable to save OAuth client configuration.', 'error') | ||
| kodyWidget.sendMessage('Unable to save OAuth client configuration.') | ||
| return | ||
| } |
There was a problem hiding this comment.
Make confidential setup writes failure-safe.
Promise.all() can persist the client ID even when saveSecret() fails. showSetupOrConnect() later keys readiness off the client ID alone, so a confidential connector can reopen straight into a broken “Connect” state with no usable secret behind it.
💡 Safer ordering
- const tasks = [
- kodyWidget.saveValue({
- name: params.clientIdValueName,
- value: clientId,
- description: `${params.provider} OAuth client ID`,
- scope: 'user',
- }),
- ]
if (params.flow === 'confidential') {
if (!params.clientSecretSecretName) {
updateStatus('Missing client secret name for confidential flow.', 'error')
kodyWidget.sendMessage(
'Missing client secret name for confidential flow. Check the connector setup parameters.',
@@
if (!clientSecret) {
updateStatus('Client secret is required for confidential flow.', 'error')
kodyWidget.sendMessage(
'Client secret is required for confidential flow before connecting.',
)
return
}
- tasks.push(
- kodyWidget.saveSecret({
- name: params.clientSecretSecretName,
- value: clientSecret,
- description: `${params.provider} OAuth client secret`,
- scope: 'user',
- }),
- )
+ const secretResult = await kodyWidget.saveSecret({
+ name: params.clientSecretSecretName,
+ value: clientSecret,
+ description: `${params.provider} OAuth client secret`,
+ scope: 'user',
+ })
+ if (!secretResult.ok) {
+ updateStatus('Unable to save OAuth client configuration.', 'error')
+ kodyWidget.sendMessage('Unable to save OAuth client configuration.')
+ return
+ }
}
setVisibility('[data-secret-row]', params.flow === 'confidential')
- const results = await Promise.all(tasks)
- const failed = results.find((result) => !result.ok)
- if (failed) {
+ const clientIdResult = await kodyWidget.saveValue({
+ name: params.clientIdValueName,
+ value: clientId,
+ description: `${params.provider} OAuth client ID`,
+ scope: 'user',
+ })
+ if (!clientIdResult.ok) {
updateStatus('Unable to save OAuth client configuration.', 'error')
kodyWidget.sendMessage('Unable to save OAuth client configuration.')
return
}Also applies to: 445-452
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/worker/src/app/connect-oauth-page.ts` around lines 185 - 224, The
current Promise.all on tasks can persist the client ID even if saving the client
secret fails; change the flow in the connect logic so that for confidential
connectors you perform the secret save first (await kodyWidget.saveSecret in
connect-oauth-page.ts inside the confidential branch) and only proceed to save
the client ID (kodyWidget.saveValue) if the secret save succeeded, then handle
errors immediately (updateStatus/sendMessage/return) before any client ID
persists; likewise update the other occurrence mentioned (lines ~445-452) to the
same sequential, failure-safe ordering so showSetupOrConnect cannot see a saved
client ID without its secret.
| url.searchParams.set('response_type', 'code') | ||
| url.searchParams.set('client_id', clientId) | ||
| url.searchParams.set('redirect_uri', getRedirectUri()) | ||
| if (params.scopes.length > 0) { | ||
| url.searchParams.set('scope', params.scopes.join(params.scopeSeparator)) | ||
| } | ||
| const state = kodyWidget.createOAuthState(stateKey) | ||
| url.searchParams.set('state', state) | ||
| if (params.flow === 'pkce') { | ||
| const verifier = createCodeVerifier() | ||
| storage.setItem(pkceVerifierKey, verifier) | ||
| const challenge = await createCodeChallenge(verifier) | ||
| url.searchParams.set('code_challenge_method', 'S256') | ||
| url.searchParams.set('code_challenge', challenge) | ||
| } | ||
| for (const [key, value] of Object.entries(params.extraAuthorizeParams)) { | ||
| if (isValidParamName(key)) { | ||
| url.searchParams.set(key, String(value)) | ||
| } | ||
| } |
There was a problem hiding this comment.
Reserve the core authorize params.
extraAuthorizeParams are applied last, so entries like state, redirect_uri, client_id, scope, or PKCE fields silently override the generated values. That can break CSRF/PKCE guarantees or send the callback to the wrong place.
🛡️ Filter out reserved keys
+ const reservedAuthorizeParams = new Set([
+ 'client_id',
+ 'code_challenge',
+ 'code_challenge_method',
+ 'redirect_uri',
+ 'response_type',
+ 'scope',
+ 'state',
+ ])
for (const [key, value] of Object.entries(params.extraAuthorizeParams)) {
- if (isValidParamName(key)) {
+ if (isValidParamName(key) && !reservedAuthorizeParams.has(key.toLowerCase())) {
url.searchParams.set(key, String(value))
}
}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/worker/src/app/connect-oauth-page.ts` around lines 260 - 279, When
applying params.extraAuthorizeParams in connect-oauth-page.ts, skip any keys
that would override core OAuth values by filtering out a reserved set (at
minimum: response_type, client_id, redirect_uri, scope, state, code_challenge,
code_challenge_method); update the loop that iterates
params.extraAuthorizeParams to ignore these reserved names before calling
url.searchParams.set so generated values from createOAuthState/stateKey,
getRedirectUri, PKCE (createCodeVerifier, createCodeChallenge, pkceVerifierKey)
and scope handling are never overwritten; keep using isValidParamName for
additional validation and convert keys consistently (e.g., exact match) when
checking against the reserved set.
| if (result?.kind === 'host_approval_required') { | ||
| updateStatus('Token exchange requires host approval. Approve the host and retry.', 'error') | ||
| renderApprovalDetails(result) | ||
| await saveConnectorConfig() | ||
| showStep('success') | ||
| return |
There was a problem hiding this comment.
Don't route partial failures through the success card.
Both host_approval_required and !connectorSaved still transition to the success step, but that UI says “Success” and “Saved connector” even when token exchange is blocked or the registry entry never persisted. This needs a separate blocked/partial-success state, or the success transition should wait for full completion.
Also applies to: 362-365, 681-709
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/worker/src/app/connect-oauth-page.ts` around lines 332 - 337, The
current flow routes partial failures into the success UI: when result?.kind ===
'host_approval_required' (and similarly where connectorSaved is false) the code
calls updateStatus, renderApprovalDetails, saveConnectorConfig and then
showStep('success'); change this so that you do NOT call showStep('success') for
blocked/partial cases — instead introduce and call a new step like
showStep('blocked') or showStep('partial_success') (and add corresponding UI
handling), or only call showStep('success') after saveConnectorConfig confirms
persistence and token exchange completed; update the logic in the blocks that
use result?.kind, saveConnectorConfig, updateStatus, renderApprovalDetails and
any other similar sections (including the other occurrences mentioned) to use
the new blocked/partial-success step when token exchange is pending or
connectorSaved is false.
| async function handleCallback() { | ||
| const callback = kodyWidget.readOAuthCallback({ expectedStateKey: stateKey }) | ||
| if (callback.kind === 'error') { | ||
| updateStatus( | ||
| callback.errorDescription | ||
| ? \`\${callback.error}: \${callback.errorDescription}\` | ||
| : \`OAuth error: \${callback.error}\`, | ||
| 'error', | ||
| ) | ||
| return | ||
| } | ||
| if (callback.kind === 'success') { | ||
| await exchangeCode(callback.code, callback.state) | ||
| } | ||
| } |
There was a problem hiding this comment.
Drop the callback query params after reading them.
The runtime removes the stored OAuth state on the first successful validation. Because the URL keeps code/state, a refresh or reopening browser history re-enters callback mode and predictably lands on State mismatch or reused-code errors, with no path back from step 3.
↩️ Clear the one-time callback parameters
async function handleCallback() {
const callback = kodyWidget.readOAuthCallback({ expectedStateKey: stateKey })
+ if (callback.kind !== 'none') {
+ window.history.replaceState(null, '', getRedirectUri())
+ }
if (callback.kind === 'error') {
updateStatus(
callback.errorDescription
? `${callback.error}: ${callback.errorDescription}`
: `OAuth error: ${callback.error}`,Also applies to: 492-500
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/worker/src/app/connect-oauth-page.ts` around lines 429 - 443, The
callback handler (handleCallback) reads the OAuth callback via
kodyWidget.readOAuthCallback and exchanges the code with exchangeCode, but it
never clears the one-time callback query params, causing re-entry on refresh;
after successfully reading a callback (both in handleCallback and any other
block that calls kodyWidget.readOAuthCallback), remove the code/state query
params from the browser URL (e.g., via history.replaceState or equivalent) so
the page no longer re-enters callback mode on refresh or history navigation
while keeping the rest of the flow (only perform the URL cleanup after
callback.kind === 'success' or after handling the callback).
|
@cursoragent please check CI on this PR and fix any issues. Also address any valid feedback on this PR |
There was a problem hiding this comment.
Actionable comments posted: 6
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/worker/client/routes/connect-oauth.tsx`:
- Around line 418-439: The handleCallback function sets setStep('callback') but
the UI never renders a callback view, leaving users stuck on errors; update
handleCallback to reset to a recoverable UI state (e.g., call
setStep('connect')) when encountering recoverable failures (callback.kind ===
'error', invalid validateState(getStateKey(config.providerKey), ...), and failed
exchangeOAuthCode(...) where exchange.ok is false) so the user sees the
retry/connect UI and can restart the flow, or alternatively implement a visible
'callback' rendering branch that shows the error and retry actions; locate
handleCallback, the setStep calls, readCallback(), validateState(...), and
exchangeOAuthCode(...) to apply the fix.
- Around line 56-59: The TypeScript errors come from setStatus accepting only
one argument while callers pass a severity, missing imports for
SaveValueResult/SaveSecretResult, and assigning an unknown-typed error into
OAuthExchangeResult.error; fix by updating setStatus signature to
setStatus(message: string, severity?: 'info' | 'warn' | 'error') and update all
call sites to pass the optional severity, add explicit imports for
SaveValueResult and SaveSecretResult from
packages/worker/client/mcp-apps/generated-ui-widget-runtime.ts, and in the
exchangeOAuthCode failure branch (and similar spots) coerce the unknown error to
string (e.g., const errStr = typeof data?.error_description === 'string' ?
data.error_description : typeof data?.error === 'string' ? data.error :
JSON.stringify(data?.error) and assign that to OAuthExchangeResult.error) so the
types line up.
- Around line 211-216: Remove usage of nextConfig.extraAuthorizeParams when
building the token exchange request so authorization-only parameters aren't
replayed to the token endpoint; only apply nextConfig.extraAuthorizeParams when
constructing the initial authorization URL (where you already set
url.searchParams.set in the authorization request code), and do not loop over or
call url.searchParams.set (or include those keys) in the token exchange logic
(the block that constructs the token request/URL around the token exchange
function). Also update the second occurrence (the similar loop at the later
location) to the same behavior so extraAuthorizeParams is never added to token
endpoint requests.
- Around line 310-317: The client currently reads the confidential client secret
from sessionStorage (nextConfig.clientSecretSecretName) and posts it directly to
the provider during token exchange in connect-oauth.tsx; move this exchange
server-side by adding a server endpoint (e.g., performTokenExchange or
/api/oauth/token) that reads the stored secret from the server-side secret
store/config and performs the POST to the provider, then returns the token
response to the browser; update the client code in connect-oauth.tsx to call
that new endpoint (remove any use of sessionStorage for client_secret and stop
setting params.set('client_secret', ...)), and ensure the server endpoint
validates the incoming request (CSRF/auth) and forwards provider responses and
errors; apply the same change to the other token-exchange site referenced around
lines 372-390.
- Around line 613-616: The current rendering of the "Open provider dashboard"
link uses config.dashboardUrl (parsed via parseOptionalUrl()) which may accept
non-http(s) schemes like javascript:; update the rendering logic in the
connect-oauth component to only render the anchor when the parsed URL's protocol
is exactly "http:" or "https:". Locate the JSX that checks config.dashboardUrl
and the parseOptionalUrl usage, perform a protocol check on the URL object (or
re-parse and validate) and only output the <a> link when protocol === "http:" ||
protocol === "https:" (keep rel="noreferrer" and add rel="noopener" if needed).
In `@packages/worker/src/app/handlers/account-secrets.ts`:
- Around line 335-345: The saved token secret names are being recomputed from
the provider when calling saveConnectorConfig (leading to mismatches); update
the calls in handleConnectOauthAction so you pass the actual
accessTokenSecretName and refreshTokenSecretName that were used to store tokens
(instead of relying on provider-based recompute), and modify saveConnectorConfig
to accept and prefer those secret name parameters when present; apply the same
change to the other saveConnectorConfig call in this file (the second occurrence
around the OAuth flow handling).
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: aec60e33-6b83-418d-8388-b7c3d6fb7c45
📒 Files selected for processing (3)
packages/worker/client/routes/connect-oauth.tsxpackages/worker/client/routes/index.tsxpackages/worker/src/app/handlers/account-secrets.ts
✅ Files skipped from review due to trivial changes (1)
- packages/worker/client/routes/index.tsx
|
@cursoragent please pull the latest changes then rebase on main. I just merged a pretty significant addition that might be related. It may not; you may want to check the pull request for details. I want you to make adjustments and of course angle merge conflicts once you've verified everything is working and validation passes locally and you've made the adjustments for the changes that have been made to make it a cohesive experience. Please force push with lease. Also double check feedback on this PR and make sure that anything that is valid is addressed. |
|
Bugbot Autofix prepared fixes for all 3 issues found in the latest run.
Preview (f3a40d8e66)diff --git a/packages/worker/client/routes/connect-oauth.tsx b/packages/worker/client/routes/connect-oauth.tsx
new file mode 100644
--- /dev/null
+++ b/packages/worker/client/routes/connect-oauth.tsx
@@ -1,0 +1,904 @@
+import { type Handle } from 'remix/component'
+import { colors, radius, shadows, spacing } from '#client/styles/tokens.ts'
+
+type OAuthFlow = 'pkce' | 'confidential'
+
+type ConnectOauthConfig = {
+ provider: string
+ providerKey: string
+ authorizeHost: string
+ tokenHost: string
+ authorizeUrl: string
+ tokenUrl: string
+ scopes: Array<string>
+ flow: OAuthFlow
+ scopeSeparator: string
+ extraAuthorizeParams: Record<string, string>
+ providerSetupInstructions: string | null
+ dashboardUrl: string | null
+ clientIdValueName: string
+ clientSecretSecretName: string | null
+ accessTokenSecretName: string
+ refreshTokenSecretName: string
+ allowedHosts: Array<string>
+}
+
+type OAuthExchangeResult =
+ | { ok: true; data: Record<string, unknown>; status: number }
+ | { ok: false; status: number; error: string }
+
+type SaveValueResult =
+ | { ok: true; value: { value: string } }
+ | { ok: false; error: string }
+
+type SaveSecretResult = { ok: true } | { ok: false; error: string }
+
+type OAuthCallback =
+ | { kind: 'none' }
+ | { kind: 'error'; error: string; description: string | null }
+ | { kind: 'success'; code: string; state: string | null }
+
+export function ConnectOauthRoute(handle: Handle) {
+ const normalizeHosts = (hosts: Array<string>) =>
+ Array.from(
+ new Set(
+ hosts
+ .map((host) => host.trim().toLowerCase())
+ .filter((host) => host.length > 0),
+ ),
+ ).sort()
+ let statusMessage = 'Ready to connect.'
+ let currentStep: 'setup' | 'connect' | 'callback' | 'success' = 'setup'
+ let config: ConnectOauthConfig | null = null
+ let accessTokenSaved = false
+ let refreshTokenSaved = false
+ let hasConfigError = false
+ let connectOauthHandled = false
+ let approvalDetails: { host: string; secrets: Array<string> } | null = null
+ let submitting = false
+
+ const update = () => handle.update()
+
+ const setStatus = (message: string) => {
+ statusMessage = message
+ update()
+ }
+
+ const setStep = (step: typeof currentStep) => {
+ currentStep = step
+ update()
+ }
+
+ const setApprovalDetails = (host: string, secrets: Array<string>): void => {
+ approvalDetails = { host, secrets }
+ update()
+ }
+
+ const readQueryConfig = (): ConnectOauthConfig | null => {
+ hasConfigError = false
+ if (typeof window === 'undefined') return null
+ const url = new URL(window.location.href)
+ const readRequired = (key: string) => {
+ const value = url.searchParams.get(key)
+ return value && value.trim() ? value.trim() : null
+ }
+ const readOptional = (key: string) => {
+ const value = url.searchParams.get(key)
+ return value && value.trim() ? value.trim() : null
+ }
+ const provider = readRequired('provider')
+ const authorizeUrl = readRequired('authorizeUrl')
+ const tokenUrl = readRequired('tokenUrl')
+ if (!provider || !authorizeUrl || !tokenUrl) {
+ hasConfigError = true
+ setStatus('Missing required OAuth configuration parameters.')
+ return null
+ }
+ const authorizeHost = safeParseHost(authorizeUrl)
+ const tokenHost = safeParseHost(tokenUrl)
+ if (!authorizeHost || !tokenHost) {
+ hasConfigError = true
+ setStatus('Authorize and token URLs must be valid.')
+ return null
+ }
+ let flow = (readOptional('flow') ?? 'pkce').toLowerCase()
+ if (flow !== 'pkce' && flow !== 'confidential') flow = 'pkce'
+ const scopes = parseScopes(readOptional('scopes'))
+ const scopeSeparator = readOptional('scopeSeparator') ?? ' '
+ const extraAuthorizeParams = parseExtraParams(
+ readOptional('extraAuthorizeParams'),
+ )
+ const dashboardUrl = parseOptionalUrl(readOptional('dashboardUrl'))
+ const providerKey = normalizeProviderKey(provider)
+ if (!providerKey) {
+ hasConfigError = true
+ setStatus('Provider must contain letters or numbers.')
+ return null
+ }
+ const providerSetupInstructions = parseProviderSetupInstructions(
+ readOptional('providerSetupInstructions'),
+ )
+ const allowedHosts = normalizeHosts([
+ ...(tokenHost ? [tokenHost] : []),
+ ...parseAllowedHosts(readOptional('allowedHosts')),
+ ])
+ if (allowedHosts.length === 0) {
+ hasConfigError = true
+ setStatus('Allowed hosts are required to continue.')
+ return null
+ }
+ return {
+ provider,
+ providerKey,
+ authorizeHost,
+ tokenHost,
+ authorizeUrl,
+ tokenUrl,
+ scopes,
+ flow: flow as OAuthFlow,
+ scopeSeparator,
+ extraAuthorizeParams,
+ providerSetupInstructions,
+ dashboardUrl,
+ clientIdValueName: `${providerKey}-client-id`,
+ clientSecretSecretName:
+ flow === 'confidential' ? `${providerKey}ClientSecret` : null,
+ accessTokenSecretName: `${providerKey}AccessToken`,
+ refreshTokenSecretName: `${providerKey}RefreshToken`,
+ allowedHosts,
+ }
+ }
+
+ const readCallback = (): OAuthCallback => {
+ if (typeof window === 'undefined') return { kind: 'none' }
+ const params = new URLSearchParams(window.location.search)
+ const error = params.get('error')
+ const description = params.get('error_description')
+ if (error) {
+ return { kind: 'error', error, description }
+ }
+ const code = params.get('code')
+ if (!code) return { kind: 'none' }
+ return { kind: 'success', code, state: params.get('state') }
+ }
+
+ const getRedirectUri = (): string => {
+ if (typeof window === 'undefined') return ''
+ return `${window.location.origin}${window.location.pathname}`
+ }
+
+ const getStateKey = (providerKey: string) => `connect-oauth:${providerKey}`
+
+ const getPkceKey = (providerKey: string) =>
+ `connect-oauth:${providerKey}:pkce`
+
+ const configStorageKey = 'connect-oauth:config'
+
+ const isConnectOauthConfig = (
+ value: unknown,
+ ): value is ConnectOauthConfig => {
+ if (!value || typeof value !== 'object') return false
+ const record = value as Record<string, unknown>
+ return (
+ typeof record.provider === 'string' &&
+ typeof record.providerKey === 'string' &&
+ typeof record.authorizeUrl === 'string' &&
+ typeof record.tokenUrl === 'string' &&
+ typeof record.authorizeHost === 'string' &&
+ typeof record.tokenHost === 'string' &&
+ typeof record.flow === 'string' &&
+ typeof record.scopeSeparator === 'string' &&
+ typeof record.clientIdValueName === 'string' &&
+ typeof record.accessTokenSecretName === 'string' &&
+ Array.isArray(record.scopes) &&
+ Array.isArray(record.allowedHosts) &&
+ record.scopes.every((value) => typeof value === 'string') &&
+ record.allowedHosts.every((value) => typeof value === 'string')
+ )
+ }
+
+ const persistConfig = (nextConfig: ConnectOauthConfig) => {
+ try {
+ sessionStorage.setItem(configStorageKey, JSON.stringify(nextConfig))
+ } catch {}
+ }
+
+ const readStoredConfig = (): ConnectOauthConfig | null => {
+ if (typeof window === 'undefined') return null
+ const raw = sessionStorage.getItem(configStorageKey)
+ if (!raw) return null
+ try {
+ const parsed = JSON.parse(raw)
+ return isConnectOauthConfig(parsed) ? parsed : null
+ } catch {
+ return null
+ }
+ }
+
+ const createState = (key: string) => {
+ const value = crypto.randomUUID()
+ sessionStorage.setItem(key, value)
+ return value
+ }
+
+ const validateState = (key: string, returned: string | null) => {
+ const expected = sessionStorage.getItem(key)
+ return Boolean(expected && returned && expected === returned)
+ }
+
+ const reservedAuthorizeParams = new Set([
+ 'client_id',
+ 'code_challenge',
+ 'code_challenge_method',
+ 'redirect_uri',
+ 'response_type',
+ 'scope',
+ 'state',
+ ])
+
+ const buildAuthorizeUrl = async (nextConfig: ConnectOauthConfig) => {
+ if (hasConfigError) {
+ throw new Error('Unable to start OAuth with invalid configuration.')
+ }
+ persistConfig(nextConfig)
+ const url = new URL(nextConfig.authorizeUrl)
+ url.searchParams.set('response_type', 'code')
+ const clientId = await readValue(nextConfig.clientIdValueName)
+ if (!clientId) {
+ throw new Error('Missing client ID. Save it before connecting.')
+ }
+ url.searchParams.set('client_id', clientId)
+ url.searchParams.set('redirect_uri', getRedirectUri())
+ if (nextConfig.scopes.length > 0) {
+ url.searchParams.set(
+ 'scope',
+ nextConfig.scopes.join(nextConfig.scopeSeparator),
+ )
+ }
+ const state = createState(getStateKey(nextConfig.providerKey))
+ url.searchParams.set('state', state)
+ if (nextConfig.flow === 'pkce') {
+ const verifier = createCodeVerifier()
+ sessionStorage.setItem(getPkceKey(nextConfig.providerKey), verifier)
+ const challenge = await createCodeChallenge(verifier)
+ url.searchParams.set('code_challenge_method', 'S256')
+ url.searchParams.set('code_challenge', challenge)
+ }
+ for (const [key, value] of Object.entries(
+ nextConfig.extraAuthorizeParams,
+ )) {
+ if (!key) continue
+ if (reservedAuthorizeParams.has(key.toLowerCase())) continue
+ url.searchParams.set(key, value)
+ }
+ return url.toString()
+ }
+
+ const readValue = async (name: string) => {
+ const response = await fetch('/account/secrets.json', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ Accept: 'application/json',
+ },
+ credentials: 'include',
+ body: JSON.stringify({ action: 'value_get', name }),
+ })
+ const payload = await response.json().catch(() => null)
+ if (!response.ok || payload?.ok !== true) return null
+ return typeof payload.value?.value === 'string' ? payload.value.value : null
+ }
+
+ const saveValue = async (
+ name: string,
+ value: string,
+ description: string,
+ ): Promise<SaveValueResult> => {
+ const response = await fetch('/account/secrets.json', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ Accept: 'application/json',
+ },
+ credentials: 'include',
+ body: JSON.stringify({
+ action: 'value_set',
+ name,
+ value,
+ description,
+ }),
+ })
+ const payload = await response.json().catch(() => null)
+ if (!response.ok || payload?.ok !== true || !payload.value?.value) {
+ return { ok: false, error: payload?.error || 'Unable to save value.' }
+ }
+ return { ok: true, value: { value: String(payload.value.value) } }
+ }
+
+ const saveSecret = async (
+ name: string,
+ value: string,
+ description: string,
+ allowedHosts: Array<string>,
+ ): Promise<SaveSecretResult> => {
+ const response = await fetch('/account/secrets.json', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ Accept: 'application/json',
+ },
+ credentials: 'include',
+ body: JSON.stringify({
+ action: 'save',
+ name,
+ value,
+ scope: 'user',
+ description,
+ allowedHosts,
+ allowedCapabilities: [],
+ }),
+ })
+ const payload = await response.json().catch(() => null)
+ if (!response.ok || payload?.ok !== true) {
+ return { ok: false, error: payload?.error || 'Unable to save secret.' }
+ }
+ return { ok: true }
+ }
+
+ const exchangeOAuthCode = async (
+ nextConfig: ConnectOauthConfig,
+ code: string,
+ ): Promise<OAuthExchangeResult> => {
+ const params = new URLSearchParams()
+ params.set('grant_type', 'authorization_code')
+ const clientId = await readValue(nextConfig.clientIdValueName)
+ if (!clientId) {
+ return { ok: false, status: 0, error: 'Missing client ID.' }
+ }
+ params.set('client_id', clientId)
+ params.set('code', code)
+ params.set('redirect_uri', getRedirectUri())
+ if (nextConfig.flow === 'pkce') {
+ const verifier = sessionStorage.getItem(
+ getPkceKey(nextConfig.providerKey),
+ )
+ if (!verifier) {
+ return { ok: false, status: 0, error: 'Missing PKCE verifier.' }
+ }
+ params.set('code_verifier', verifier)
+ } else if (nextConfig.clientSecretSecretName) {
+ const secret = sessionStorage.getItem(
+ `${nextConfig.providerKey}-client-secret`,
+ )
+ if (!secret) {
+ return { ok: false, status: 0, error: 'Missing client secret.' }
+ }
+ params.set('client_secret', secret)
+ }
+ const response = await fetch(nextConfig.tokenUrl, {
+ method: 'POST',
+ headers: {
+ Accept: 'application/json',
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ },
+ body: params.toString(),
+ })
+ const text = await response.text()
+ let data: Record<string, unknown> | null = null
+ try {
+ data = JSON.parse(text)
+ } catch {
+ data = null
+ }
+ if (!response.ok || !data) {
+ return {
+ ok: false,
+ status: response.status,
+ error:
+ (typeof data?.error_description === 'string' &&
+ data.error_description) ||
+ (typeof data?.error === 'string' && data.error) ||
+ 'Token exchange failed.',
+ }
+ }
+ return { ok: true, data, status: response.status }
+ }
+
+ const handleSetupSubmit = async (event: Event) => {
+ event.preventDefault()
+ if (!config || submitting) return
+ submitting = true
+ update()
+ try {
+ const form = event.currentTarget as HTMLFormElement
+ const formData = new FormData(form)
+ const clientId = String(formData.get('clientId') ?? '').trim()
+ const clientSecret = String(formData.get('clientSecret') ?? '').trim()
+ if (!clientId) {
+ setStatus('Client ID is required.')
+ return
+ }
+ if (config.flow === 'confidential') {
+ if (!clientSecret) {
+ setStatus('Client secret is required for confidential flow.')
+ return
+ }
+ const secretResult = await saveSecret(
+ config.clientSecretSecretName ?? '',
+ clientSecret,
+ `${config.provider} OAuth client secret`,
+ config.allowedHosts,
+ )
+ if (!secretResult.ok) {
+ setStatus(secretResult.error)
+ return
+ }
+ sessionStorage.setItem(
+ `${config.providerKey}-client-secret`,
+ clientSecret,
+ )
+ }
+ const clientIdResult = await saveValue(
+ config.clientIdValueName,
+ clientId,
+ `${config.provider} OAuth client ID`,
+ )
+ if (!clientIdResult.ok) {
+ setStatus(clientIdResult.error)
+ return
+ }
+ setStatus('Saved OAuth client configuration.')
+ setStep('connect')
+ } finally {
+ submitting = false
+ update()
+ }
+ }
+
+ const handleConnect = async () => {
+ if (!config || submitting) return
+ submitting = true
+ update()
+ try {
+ const url = await buildAuthorizeUrl(config)
+ window.location.assign(url)
+ } catch (error) {
+ setStatus(
+ error instanceof Error ? error.message : 'Unable to start OAuth.',
+ )
+ } finally {
+ submitting = false
+ update()
+ }
+ }
+
+ const handleCallback = async () => {
+ if (!config) return
+ setStep('callback')
+ const callback = readCallback()
+ if (callback.kind !== 'none') {
+ window.history.replaceState(null, '', getRedirectUri())
+ }
+ if (callback.kind === 'error') {
+ setStatus(callback.description || `OAuth error: ${callback.error}`)
+ return
+ }
+ if (callback.kind !== 'success') return
+ const valid = validateState(getStateKey(config.providerKey), callback.state)
+ if (!valid) {
+ setStatus('State mismatch. Restart the OAuth flow.')
+ return
+ }
+ const exchange = await exchangeOAuthCode(config, callback.code)
+ if (!exchange.ok) {
+ setStatus(exchange.error)
+ return
+ }
+ const callbackUrl = window.location.href
+ const response = await fetch('/account/secrets.json', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ Accept: 'application/json',
+ },
+ credentials: 'include',
+ body: JSON.stringify({
+ action: 'connect_oauth',
+ provider: config.provider,
+ callbackUrl,
+ tokenUrl: config.tokenUrl,
+ flow: config.flow,
+ clientIdValueName: config.clientIdValueName,
+ clientSecretSecretName: config.clientSecretSecretName,
+ allowedHosts: config.allowedHosts,
+ accessTokenSecretName: config.accessTokenSecretName,
+ refreshTokenSecretName: config.refreshTokenSecretName,
+ tokenPayload: exchange.data,
+ }),
+ })
+ const payload = await response.json().catch(() => null)
+ if (!response.ok || payload?.ok !== true) {
+ setStatus(payload?.error || 'Unable to save OAuth tokens.')
+ return
+ }
+ accessTokenSaved = payload.accessTokenSaved === true
+ refreshTokenSaved = payload.refreshTokenSaved === true
+ const approvalHosts = Array.isArray(payload.allowedHosts)
+ ? payload.allowedHosts
+ : config.allowedHosts
+ if (approvalHosts.length > 0) {
+ setApprovalDetails(approvalHosts[0] ?? 'unknown host', [
+ config.accessTokenSecretName,
+ ...(config.refreshTokenSecretName
+ ? [config.refreshTokenSecretName]
+ : []),
+ ])
+ }
+ setStatus('OAuth tokens saved.')
+ setStep('success')
+ return
+ }
+
+ const renderProviderInstructions = () => {
+ if (!config) return null
+ const instructions = config.providerSetupInstructions
+ if (instructions && instructions.trim()) {
+ return (
+ <p
+ css={{
+ whiteSpace: 'pre-wrap',
+ backgroundColor: colors.surface,
+ border: `1px solid ${colors.border}`,
+ padding: spacing.md,
+ borderRadius: radius.md,
+ color: colors.textMuted,
+ }}
+ >
+ {instructions}
+ </p>
+ )
+ }
+ return (
+ <p css={{ color: colors.textMuted }}>
+ Create an OAuth app with your provider and enter the Client ID below.
+ </p>
+ )
+ }
+
+ const renderAllowedHosts = () => {
+ if (!config) return null
+ return (
+ <section
+ css={{
+ padding: spacing.md,
+ borderRadius: radius.md,
+ border: `1px solid ${colors.border}`,
+ backgroundColor: colors.surface,
+ display: 'grid',
+ gap: spacing.xs,
+ }}
+ >
+ <h3 css={{ margin: 0 }}>Allowed hosts</h3>
+ <p css={{ margin: 0, color: colors.textMuted }}>
+ These hosts will be approved for the saved secrets. Host approvals are
+ never automatic.
+ </p>
+ <ul css={{ margin: 0, paddingLeft: spacing.lg }}>
+ {config.allowedHosts.map((host) => (
+ <li key={host}>{host}</li>
+ ))}
+ </ul>
+ </section>
+ )
+ }
+
+ handle.queueTask(async () => {
+ const callback = readCallback()
+ if (callback.kind === 'success' || callback.kind === 'error') {
+ const storedConfig = readStoredConfig()
+ const nextConfig = storedConfig ?? readQueryConfig()
+ if (!nextConfig) {
+ setStatus('Missing required OAuth configuration parameters.')
+ return
+ }
+ config = nextConfig
+ if (!connectOauthHandled) {
+ connectOauthHandled = true
+ await handleCallback()
+ }
+ return
+ }
+ const nextConfig = readQueryConfig()
+ if (!nextConfig) {
+ setStatus('Missing required OAuth configuration parameters.')
+ return
+ }
+ config = nextConfig
+ setStep('setup')
+ })
+
+ return () => {
+ if (!config) {
+ return (
+ <section css={{ padding: spacing.lg }}>
+ <h1 css={{ margin: 0 }}>Connect OAuth</h1>
+ <p css={{ color: colors.textMuted }}>{statusMessage}</p>
+ </section>
+ )
+ }
+ return (
+ <section
+ css={{
+ maxWidth: '60rem',
+ margin: '0 auto',
+ display: 'grid',
+ gap: spacing.lg,
+ }}
+ >
+ <header>
+ <h1 css={{ margin: 0 }}>Connect {config.provider}</h1>
+ <p css={{ color: colors.textMuted }}>
+ Follow the steps below to connect your account using OAuth.
+ </p>
+ </header>
+ <section
+ css={{
+ padding: spacing.md,
+ borderRadius: radius.md,
+ border: `1px solid ${colors.border}`,
+ backgroundColor: colors.surface,
+ boxShadow: shadows.sm,
+ }}
+ >
+ <strong>status</strong>
+ <p css={{ margin: `${spacing.xs} 0 0`, color: colors.textMuted }}>
+ {statusMessage}
+ </p>
+ </section>
+ <section
+ css={{
+ padding: spacing.md,
+ borderRadius: radius.md,
+ border: `1px solid ${colors.border}`,
+ backgroundColor: colors.surface,
+ display: 'grid',
+ gap: spacing.sm,
+ }}
+ >
+ <h2 css={{ margin: 0 }}>Provider details</h2>
+ <p css={{ margin: 0 }}>
+ Authorize URL: <code>{config.authorizeUrl}</code>
+ </p>
+ <p css={{ margin: 0 }}>
+ Token URL: <code>{config.tokenUrl}</code>
+ </p>
+ <p css={{ margin: 0 }}>Flow: {config.flow}</p>
+ <p css={{ margin: 0 }}>
+ Scope: {config.scopes.length ? config.scopes.join(' ') : 'None'}
+ </p>
+ {config.dashboardUrl ? (
+ <a href={config.dashboardUrl} target="_blank" rel="noreferrer">
+ Open provider dashboard
+ </a>
+ ) : null}
+ </section>
+ {currentStep === 'setup' ? (
+ <section
+ css={{
+ padding: spacing.md,
+ borderRadius: radius.md,
+ border: `1px solid ${colors.border}`,
+ backgroundColor: colors.surface,
+ display: 'grid',
+ gap: spacing.md,
+ }}
+ >
+ <h2 css={{ margin: 0 }}>1. Save OAuth client configuration</h2>
+ {renderProviderInstructions()}
+ {renderAllowedHosts()}
+ <form
+ on={{ submit: handleSetupSubmit }}
+ css={{ display: 'grid', gap: spacing.md }}
+ >
+ <label>
+ <span>Client ID</span>
+ <input name="clientId" required />
+ </label>
+ {config.flow === 'confidential' ? (
+ <label>
+ <span>Client Secret</span>
+ <input name="clientSecret" type="password" required />
+ </label>
+ ) : null}
+ <button type="submit" disabled={submitting}>
+ Save configuration
+ </button>
+ </form>
+ </section>
+ ) : null}
+ {currentStep === 'connect' ? (
+ <section
+ css={{
+ padding: spacing.md,
+ borderRadius: radius.md,
+ border: `1px solid ${colors.border}`,
+ backgroundColor: colors.surface,
+ display: 'grid',
+ gap: spacing.sm,
+ }}
+ >
+ <h2 css={{ margin: 0 }}>2. Connect</h2>
+ <p css={{ margin: 0 }}>
+ Start the OAuth flow. You will be redirected to the provider.
+ </p>
+ <button
+ type="button"
+ on={{ click: () => void handleConnect() }}
+ disabled={submitting}
+ >
+ Connect {config.provider}
+ </button>
+ </section>
+ ) : null}
+ {currentStep === 'success' ? (
+ <section
+ css={{
+ padding: spacing.md,
+ borderRadius: radius.md,
+ border: `1px solid ${colors.border}`,
+ backgroundColor: colors.surface,
+ display: 'grid',
+ gap: spacing.sm,
+ }}
+ >
+ <h2 css={{ margin: 0 }}>4. Success</h2>
+ <p css={{ margin: 0 }}>
+ Access token saved:{' '}
+ <strong>{accessTokenSaved ? 'Yes' : 'No'}</strong>
+ </p>
+ <p css={{ margin: 0 }}>
+ Refresh token saved:{' '}
+ <strong>{refreshTokenSaved ? 'Yes' : 'No'}</strong>
+ </p>
+ <h3 css={{ margin: `${spacing.sm} 0 0` }}>Host approvals</h3>
+ <p css={{ margin: 0 }}>
+ Hosts are never auto-approved. Review these allowed hosts in your
+ account secrets.
+ </p>
+ <ul>
+ {config.allowedHosts.map((host) => (
+ <li key={host}>{host}</li>
+ ))}
+ </ul>
+ {approvalDetails ? (
+ <p css={{ margin: 0, color: colors.textMuted }}>
+ Secrets pending approval: {approvalDetails.secrets.join(', ')}
+ </p>
+ ) : null}
+ <a href="/account/secrets" target="_blank" rel="noreferrer">
+ Open account secrets
+ </a>
+ </section>
+ ) : null}
+ </section>
+ )
+ }
+}
+
+function parseScopes(raw: string | null) {
+ if (!raw) return []
+ const trimmed = raw.trim()
+ if (!trimmed) return []
+ if (trimmed.startsWith('[')) {
+ try {
+ const parsed = JSON.parse(trimmed)
+ if (Array.isArray(parsed)) {
... diff truncated: showing 800 of 1580 lines |
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (3)
packages/worker/client/routes/connect-oauth.tsx (3)
827-841:⚠️ Potential issue | 🔴 CriticalAllow-list protocols for every external URL parsed here.
These helpers currently accept any scheme that
new URL()can parse. That meansdashboardUrl=javascript:...still becomes a clickable link, and endpoint values likejavascript://provider.example/%0A...can also pass the hostname check and later reachwindow.location.assign()/fetch(). Onlyhttp:andhttps:should survive parsing here.🔒 Proposed fix
+function parseHttpUrl(raw: string | null) { + if (!raw) return null + try { + const url = new URL(raw) + return url.protocol === 'https:' || url.protocol === 'http:' + ? url + : null + } catch { + return null + } +} + function parseOptionalUrl(raw: string | null) { - if (!raw) return null - try { - return new URL(raw).toString() - } catch { - return null - } + return parseHttpUrl(raw)?.toString() ?? null } function safeParseHost(raw: string) { - try { - return new URL(raw).hostname - } catch { - return null - } + return parseHttpUrl(raw)?.hostname ?? null }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/worker/client/routes/connect-oauth.tsx` around lines 827 - 841, The helpers parseOptionalUrl and safeParseHost currently accept any URL scheme; update both to only accept http and https by parsing with new URL(raw) and then checking url.protocol is exactly "http:" or "https:"—if not, return null; if allowed, return url.toString() in parseOptionalUrl and url.hostname in safeParseHost. Ensure the check occurs inside the try/catch so malformed URLs still return null.
421-439:⚠️ Potential issue | 🔴 CriticalDon't re-store the confidential secret in
sessionStorage.Line 426 already persists the secret via
saveSecret(). Copying it back into browser storage re-exposes it to any XSS/extension and is only needed becauseexchangeOAuthCode()performs the confidential-client exchange from the browser. Keep the secret server-side and exchange the code there instead.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/worker/client/routes/connect-oauth.tsx` around lines 421 - 439, The code currently saves the confidential client secret via saveSecret(...) but then writes it back into sessionStorage using sessionStorage.setItem(...), re-exposing the secret; remove the sessionStorage.setItem(...) call and any client-side storage of clientSecret in connect-oauth.tsx, and instead perform the confidential-client token exchange on the server: modify the client flow that calls exchangeOAuthCode(...) so it calls a server endpoint (e.g., POST /oauth/exchange) which reads the stored secret server-side (from the same store saveSecret wrote to) and performs the exchange, returning only non-secret tokens or session info to the browser; keep references to saveSecret, clientSecret, sessionStorage.setItem, and exchangeOAuthCode to locate and update the code paths.
475-495:⚠️ Potential issue | 🟠 MajorRecoverable callback failures still land on a hidden step.
handleCallback()switches to'callback', but the render tree only handles'setup','connect', and'success'. Provider errors, state mismatches, and failed exchanges all return from that non-rendered state, so the user loses any retry path. Reset to a visible step or render an explicit callback/error section.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/worker/client/routes/connect-oauth.tsx` around lines 475 - 495, The handler sets setStep('callback') but the UI only renders 'setup', 'connect', and 'success', so recoverable failures (provider errors, state mismatch, exchange failure) leave the UI in an invisible state; update handleCallback (referencing readCallback, setStep, validateState, exchangeOAuthCode) to move back to a visible step on recoverable errors (e.g., setStep('connect') or setStep('setup') depending on whether the user can retry or reconfigure) before returning, or alternatively add rendering for the 'callback' step and show explicit error/retry UI there so users have a clear retry path. Ensure every early-return path after checking callback.kind, validateState, and checking exchange.ok sets a visible step and status.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/worker/client/routes/connect-oauth.tsx`:
- Around line 595-603: The code overwrites detailed validation errors set by
readQueryConfig() with a generic message; in the handle.queueTask callback
(around readCallback(), readStoredConfig(), readQueryConfig()), stop replacing
those messages—either remove the unconditional setStatus('Missing required OAuth
configuration parameters.') or only set it when no prior status exists;
specifically update the block that computes storedConfig and nextConfig
(functions: readStoredConfig, readQueryConfig) to return early without calling
setStatus if readQueryConfig already produced an error, or check current status
before calling setStatus so you don't overwrite the more specific errors from
readQueryConfig.
- Around line 292-315: The saveValue function currently lets fetch/json
exceptions bubble up instead of returning the typed { ok: false, error } union;
wrap the network+parsing logic in a try/catch (or handle Promise rejections)
inside saveValue so any fetch or response.json() failure returns { ok: false,
error: <message> } and preserve the existing response.ok/payload checks for
success; apply the identical pattern to saveSecret and keep handleSetupSubmit’s
existing consumer behavior by returning the union on transport or parse errors.
---
Duplicate comments:
In `@packages/worker/client/routes/connect-oauth.tsx`:
- Around line 827-841: The helpers parseOptionalUrl and safeParseHost currently
accept any URL scheme; update both to only accept http and https by parsing with
new URL(raw) and then checking url.protocol is exactly "http:" or "https:"—if
not, return null; if allowed, return url.toString() in parseOptionalUrl and
url.hostname in safeParseHost. Ensure the check occurs inside the try/catch so
malformed URLs still return null.
- Around line 421-439: The code currently saves the confidential client secret
via saveSecret(...) but then writes it back into sessionStorage using
sessionStorage.setItem(...), re-exposing the secret; remove the
sessionStorage.setItem(...) call and any client-side storage of clientSecret in
connect-oauth.tsx, and instead perform the confidential-client token exchange on
the server: modify the client flow that calls exchangeOAuthCode(...) so it calls
a server endpoint (e.g., POST /oauth/exchange) which reads the stored secret
server-side (from the same store saveSecret wrote to) and performs the exchange,
returning only non-secret tokens or session info to the browser; keep references
to saveSecret, clientSecret, sessionStorage.setItem, and exchangeOAuthCode to
locate and update the code paths.
- Around line 475-495: The handler sets setStep('callback') but the UI only
renders 'setup', 'connect', and 'success', so recoverable failures (provider
errors, state mismatch, exchange failure) leave the UI in an invisible state;
update handleCallback (referencing readCallback, setStep, validateState,
exchangeOAuthCode) to move back to a visible step on recoverable errors (e.g.,
setStep('connect') or setStep('setup') depending on whether the user can retry
or reconfigure) before returning, or alternatively add rendering for the
'callback' step and show explicit error/retry UI there so users have a clear
retry path. Ensure every early-return path after checking callback.kind,
validateState, and checking exchange.ok sets a visible step and status.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: de741a0a-8166-418b-9977-0a7cb0f99ba7
📒 Files selected for processing (2)
packages/worker/client/routes/connect-oauth.tsxpackages/worker/src/app/handlers/account-secrets.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/worker/src/app/handlers/account-secrets.ts
| const saveValue = async ( | ||
| name: string, | ||
| value: string, | ||
| description: string, | ||
| ): Promise<SaveValueResult> => { | ||
| const response = await fetch('/account/secrets.json', { | ||
| method: 'POST', | ||
| headers: { | ||
| 'Content-Type': 'application/json', | ||
| Accept: 'application/json', | ||
| }, | ||
| credentials: 'include', | ||
| body: JSON.stringify({ | ||
| action: 'value_set', | ||
| name, | ||
| value, | ||
| description, | ||
| }), | ||
| }) | ||
| const payload = await response.json().catch(() => null) | ||
| if (!response.ok || payload?.ok !== true || !payload.value?.value) { | ||
| return { ok: false, error: payload?.error || 'Unable to save value.' } | ||
| } | ||
| return { ok: true, value: { value: String(payload.value.value) } } |
There was a problem hiding this comment.
Honor the result-union contract on transport failures.
These helpers are typed to return { ok: ... }, but a rejected fetch() still escapes as an exception. handleSetupSubmit() then misses the normal !result.ok path and never gets a user-facing status. Catch transport/parsing failures here and convert them into { ok: false, error: ... }.
🛠️ Proposed pattern
const saveValue = async (
name: string,
value: string,
description: string,
): Promise<SaveValueResult> => {
- const response = await fetch('/account/secrets.json', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- Accept: 'application/json',
- },
- credentials: 'include',
- body: JSON.stringify({
- action: 'value_set',
- name,
- value,
- description,
- }),
- })
- const payload = await response.json().catch(() => null)
- if (!response.ok || payload?.ok !== true || !payload.value?.value) {
- return { ok: false, error: payload?.error || 'Unable to save value.' }
- }
- return { ok: true, value: { value: String(payload.value.value) } }
+ try {
+ const response = await fetch('/account/secrets.json', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ Accept: 'application/json',
+ },
+ credentials: 'include',
+ body: JSON.stringify({
+ action: 'value_set',
+ name,
+ value,
+ description,
+ }),
+ })
+ const payload = await response.json().catch(() => null)
+ if (!response.ok || payload?.ok !== true || !payload.value?.value) {
+ return { ok: false, error: payload?.error || 'Unable to save value.' }
+ }
+ return { ok: true, value: { value: String(payload.value.value) } }
+ } catch (error) {
+ return {
+ ok: false,
+ error: error instanceof Error ? error.message : 'Unable to save value.',
+ }
+ }
}Apply the same pattern to saveSecret().
Also applies to: 318-345
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/worker/client/routes/connect-oauth.tsx` around lines 292 - 315, The
saveValue function currently lets fetch/json exceptions bubble up instead of
returning the typed { ok: false, error } union; wrap the network+parsing logic
in a try/catch (or handle Promise rejections) inside saveValue so any fetch or
response.json() failure returns { ok: false, error: <message> } and preserve the
existing response.ok/payload checks for success; apply the identical pattern to
saveSecret and keep handleSetupSubmit’s existing consumer behavior by returning
the union on transport or parse errors.
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
| } catch { | ||
| return null | ||
| } | ||
| } |
There was a problem hiding this comment.
Client/server safeParseHost returns different values
Medium Severity
The client-side safeParseHost uses new URL(raw).hostname (no port), while the server-side version uses new URL(raw).host (includes port for non-standard ports). For a token URL like https://api.example.com:8080/token, the client computes allowedHosts containing "api.example.com", but the server adds "api.example.com:8080". This causes the UI to display different allowed hosts than what the server actually stores, and resolveSecretForHost uses exact string matching against stored hosts — so the inconsistency can cause host approval mismatches.
Additional Locations (1)
| const readOptional = (key: string) => { | ||
| const value = url.searchParams.get(key) | ||
| return value && value.trim() ? value.trim() : null | ||
| } |
There was a problem hiding this comment.
Identical readRequired and readOptional helper functions
Low Severity
readRequired and readOptional inside readQueryConfig have identical implementations — both return null for missing/empty values without any actual "required" enforcement. The naming distinction is misleading and could cause a future maintainer to assume readRequired validates presence, leading to skipped null checks.
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
c1f2842 to
66a9ce6
Compare
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
| { ok: false, error: 'Token host is not in allowed hosts.' }, | ||
| 400, | ||
| ) | ||
| } |
There was a problem hiding this comment.
SSRF: host validation bypassed with empty allowedHosts
High Severity
In handleOAuthExchangeAction, the token host validation is only performed when allowedHosts is non-empty (allowedHosts.length > 0 && ...). A caller can send an empty allowedHosts array to bypass the check entirely, causing the server to fetch any arbitrary tokenUrl. In the confidential flow, this also forwards the user's resolved client_secret to that URL. The sibling handleConnectOauthAction correctly rejects empty allowedHosts with an early return, but handleOAuthExchangeAction lacks this guard.
Additional Locations (1)
| const readOptional = (key: string) => { | ||
| const value = url.searchParams.get(key) | ||
| return value && value.trim() ? value.trim() : null | ||
| } |
There was a problem hiding this comment.
Identical readRequired and readOptional function bodies
Low Severity
readRequired and readOptional inside readQueryConfig have identical implementations — both return null for missing or empty values. The naming distinction implies readRequired enforces a constraint, but it does not. This is redundant and misleading; one function would suffice.





Summary
/connect/oauth/account/secrets.jsonso the page stays authenticated without MCP tool callsTesting
npm run lintIssues
Summary by CodeRabbit