Repository navigation
Show editable default fields on connect secret - #110
Conversation
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>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughExtracts a reusable SecretEditorFields UI, adds normalization utilities for allowed hosts/capabilities, updates client routes to manage description and editable host/capability lists, and extends the connect-secret server handler and tests to persist and validate the richer secret metadata. Changes
Sequence DiagramsequenceDiagram
participant User as User
participant Client as Client (SecretEditorFields)
participant Handler as Handler (/connect/secret)
participant Service as SecretsService
participant Storage as Persistence
User->>Client: Enter description, value, hosts, capabilities
Client->>Client: normalizeAllowedHosts/capabilities
Client->>Handler: POST /connect/secret.json {value, description, allowedHosts, allowedCapabilities}
Handler->>Handler: normalize & validate capabilities
alt value provided & non-empty
Handler->>Service: saveSecret(storageContext, metadata)
Service->>Storage: persist secret value & metadata
Handler->>Service: setSecretAllowedHosts(context, hosts)
Service->>Storage: persist allowed hosts
Handler->>Service: setSecretAllowedCapabilities(context, capabilities)
Service->>Storage: persist allowed capabilities
else value blank
Handler-->>Client: 400 Bad Request
end
Handler-->>Client: success response
Client-->>User: show confirmation
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes 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 docstrings
🧪 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 |
|
🔎 Preview deployed: https://kody-pr-110.kentcdodds.workers.dev Worker: Mocks:
|
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (3)
packages/worker/client/routes/connect-secret.tsx (1)
765-788: Normalization called multiple times in render.
normalizeAllowedHostsandnormalizeAllowedCapabilitiesare called twice each here (once for the length check, once for the.map()). While functionally correct and unlikely to cause issues with small arrays, computing the normalized values once would be cleaner.♻️ Compute normalized values once
+ const normalizedHosts = normalizeAllowedHosts(state.allowedHosts) + const normalizedCaps = normalizeAllowedCapabilities(state.allowedCapabilities) <div> <div css={labelCss}>Hosts to approve</div> <ul css={listCss}> - {normalizeAllowedHosts(state.allowedHosts).length > 0 ? ( - normalizeAllowedHosts(state.allowedHosts).map((host) => ( + {normalizedHosts.length > 0 ? ( + normalizedHosts.map((host) => ( <li key={host}>{host}</li> )) ) : ( <li>None (approval required later).</li> )} </ul> </div> <div> <div css={labelCss}>Capabilities to allow</div> <ul css={listCss}> - {normalizeAllowedCapabilities(state.allowedCapabilities) - .length > 0 ? ( - normalizeAllowedCapabilities( - state.allowedCapabilities, - ).map((capability) => ( + {normalizedCaps.length > 0 ? ( + normalizedCaps.map((capability) => ( <li key={capability}>{capability}</li> )) ) : ( <li>No restrictions requested.</li> )} </ul> </div>🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/worker/client/routes/connect-secret.tsx` around lines 765 - 788, The render calls normalizeAllowedHosts(state.allowedHosts) and normalizeAllowedCapabilities(state.allowedCapabilities) twice each; compute each normalized array once (e.g., const normalizedHosts = normalizeAllowedHosts(state.allowedHosts) and const normalizedCapabilities = normalizeAllowedCapabilities(state.allowedCapabilities)) and use those variables for the length checks and the .map() calls (replace both inline calls in the JSX), ensuring keys and fallback <li> branches remain the same.packages/worker/client/routes/secret-editor-fields.tsx (2)
51-85: Consider consolidating the duplicate input elements.The text and password inputs are nearly identical except for the
typeattribute. This could be simplified to a single input with a dynamic type.♻️ Optional refactor to reduce duplication
- {props.showSecretValue ? ( - <input - type="text" - required - autoComplete="new-password" - value={props.value} - placeholder={props.valuePlaceholder ?? 'Enter the secret value'} - on={{ - input: (event) => { - props.onValueChange(event.currentTarget.value) - }, - }} - css={{ - ...inputCss, - paddingRight: '3rem', - }} - /> - ) : ( - <input - type="password" - required - autoComplete="new-password" - value={props.value} - placeholder={props.valuePlaceholder ?? 'Enter the secret value'} - on={{ - input: (event) => { - props.onValueChange(event.currentTarget.value) - }, - }} - css={{ - ...inputCss, - paddingRight: '3rem', - }} - /> - )} + <input + type={props.showSecretValue ? 'text' : 'password'} + required + autoComplete="new-password" + value={props.value} + placeholder={props.valuePlaceholder ?? 'Enter the secret value'} + on={{ + input: (event) => { + props.onValueChange(event.currentTarget.value) + }, + }} + css={{ + ...inputCss, + paddingRight: '3rem', + }} + />🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/worker/client/routes/secret-editor-fields.tsx` around lines 51 - 85, The two nearly identical input elements inside the conditional should be consolidated into a single input: replace the conditional JSX around props.showSecretValue with one <input> whose type is set dynamically (e.g., type={props.showSecretValue ? 'text' : 'password'}) and keep all existing attributes and handlers (required, autoComplete="new-password", value={props.value}, placeholder={props.valuePlaceholder ?? 'Enter the secret value'}, the on.input callback calling props.onValueChange, and the css spread including inputCss and paddingRight). This removes duplication while preserving behavior tied to props.showSecretValue, props.onValueChange, inputCss and placeholder logic.
146-167: Defensive type checks are unnecessary given the prop types.Lines 150 and 196 check
typeof host === 'string'andtypeof capabilityName === 'string', butallowedHostsandallowedCapabilitiesare already typed asArray<string>. These guards suggest either distrust of the caller or a previous bug. If intentional for runtime safety, a comment explaining why would help.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/worker/client/routes/secret-editor-fields.tsx` around lines 146 - 167, The runtime typeof checks (e.g., "typeof host === 'string'" and "typeof capabilityName === 'string'") are redundant because props.allowedHosts and props.allowedCapabilities are typed as Array<string>; remove those guards and use the values directly in the JSX and event handlers (references: props.allowedHosts, props.onUpdateAllowedHost, props.onRemoveAllowedHost, props.allowedCapabilities, props.onUpdateAllowedCapability, props.onRemoveAllowedCapability, capabilityName). If you intentionally want runtime safety, replace the guard with a short explanatory comment above the block stating why a runtime check is required; otherwise delete the typeof conditions to simplify the code.
🤖 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/handlers/connect-secret.ts`:
- Around line 194-230: The current sequence (saveSecret followed by
setSecretAllowedHosts and setSecretAllowedCapabilities) is non-atomic so partial
failures leave a secret with stale permissions; either make these three
operations transactional in the persistence layer or add compensating rollback
logic. Fix by updating the service API so saveSecret accepts allowedHosts and
allowedCapabilities and persists them in a single DB transaction (or implement a
new saveSecretWithPermissions that wraps saveSecret + setSecretAllowedHosts +
setSecretAllowedCapabilities inside one transaction), or if a transaction is not
possible, perform cleanup by deleting the newly created secret when either
setSecretAllowedHosts or setSecretAllowedCapabilities fails (use saveSecret,
setSecretAllowedHosts, setSecretAllowedCapabilities, or a new wrapper function
to coordinate and rollback).
---
Nitpick comments:
In `@packages/worker/client/routes/connect-secret.tsx`:
- Around line 765-788: The render calls
normalizeAllowedHosts(state.allowedHosts) and
normalizeAllowedCapabilities(state.allowedCapabilities) twice each; compute each
normalized array once (e.g., const normalizedHosts =
normalizeAllowedHosts(state.allowedHosts) and const normalizedCapabilities =
normalizeAllowedCapabilities(state.allowedCapabilities)) and use those variables
for the length checks and the .map() calls (replace both inline calls in the
JSX), ensuring keys and fallback <li> branches remain the same.
In `@packages/worker/client/routes/secret-editor-fields.tsx`:
- Around line 51-85: The two nearly identical input elements inside the
conditional should be consolidated into a single input: replace the conditional
JSX around props.showSecretValue with one <input> whose type is set dynamically
(e.g., type={props.showSecretValue ? 'text' : 'password'}) and keep all existing
attributes and handlers (required, autoComplete="new-password",
value={props.value}, placeholder={props.valuePlaceholder ?? 'Enter the secret
value'}, the on.input callback calling props.onValueChange, and the css spread
including inputCss and paddingRight). This removes duplication while preserving
behavior tied to props.showSecretValue, props.onValueChange, inputCss and
placeholder logic.
- Around line 146-167: The runtime typeof checks (e.g., "typeof host ===
'string'" and "typeof capabilityName === 'string'") are redundant because
props.allowedHosts and props.allowedCapabilities are typed as Array<string>;
remove those guards and use the values directly in the JSX and event handlers
(references: props.allowedHosts, props.onUpdateAllowedHost,
props.onRemoveAllowedHost, props.allowedCapabilities,
props.onUpdateAllowedCapability, props.onRemoveAllowedCapability,
capabilityName). If you intentionally want runtime safety, replace the guard
with a short explanatory comment above the block stating why a runtime check is
required; otherwise delete the typeof conditions to simplify the code.
🪄 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: ab10df84-5e1c-4ffb-9326-40142f6e777b
📒 Files selected for processing (6)
packages/worker/client/routes/account-secrets.tsxpackages/worker/client/routes/connect-secret.tsxpackages/worker/client/routes/secret-editor-fields.tsxpackages/worker/client/routes/secret-normalization.tspackages/worker/src/app/handlers/connect-secret.node.test.tspackages/worker/src/app/handlers/connect-secret.ts
| if (typeof value === 'string') { | ||
| if (!value.trim()) { | ||
| return jsonResponse( | ||
| { ok: false, error: 'Secret value is required.' }, | ||
| 400, | ||
| ) | ||
| } | ||
| await saveSecret({ | ||
| env, | ||
| userId: user.mcpUser.userId, | ||
| name, | ||
| value, | ||
| scope, | ||
| description, | ||
| storageContext, | ||
| sessionExpiresAt: | ||
| scope === 'session' | ||
| ? new Date(session.exp).toISOString() | ||
| : null, | ||
| }) | ||
| await setSecretAllowedHosts({ | ||
| env, | ||
| userId: user.mcpUser.userId, | ||
| name, | ||
| scope, | ||
| allowedHosts: normalizedAllowedHosts, | ||
| storageContext, | ||
| }) | ||
| await setSecretAllowedCapabilities({ | ||
| env, | ||
| userId: user.mcpUser.userId, | ||
| name, | ||
| scope, | ||
| allowedCapabilities: normalizedAllowedCapabilities, | ||
| storageContext, | ||
| }) | ||
| } |
There was a problem hiding this comment.
Non-atomic persistence: partial failure leaves secret with stale permissions.
The three sequential operations (saveSecret, setSecretAllowedHosts, setSecretAllowedCapabilities) are not transactional. If setSecretAllowedHosts or setSecretAllowedCapabilities fails after saveSecret succeeds, the secret will exist but with its previous (or empty) permissions rather than the requested ones.
This is recoverable since the user receives an error and can retry, but worth noting. The service layer preserves existing permissions during saveSecret (per context snippet 1, lines 109-110), so re-submitting with the same payload should eventually succeed.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/worker/src/app/handlers/connect-secret.ts` around lines 194 - 230,
The current sequence (saveSecret followed by setSecretAllowedHosts and
setSecretAllowedCapabilities) is non-atomic so partial failures leave a secret
with stale permissions; either make these three operations transactional in the
persistence layer or add compensating rollback logic. Fix by updating the
service API so saveSecret accepts allowedHosts and allowedCapabilities and
persists them in a single DB transaction (or implement a new
saveSecretWithPermissions that wraps saveSecret + setSecretAllowedHosts +
setSecretAllowedCapabilities inside one transaction), or if a transaction is not
possible, perform cleanup by deleting the newly created secret when either
setSecretAllowedHosts or setSecretAllowedCapabilities fails (use saveSecret,
setSecretAllowedHosts, setSecretAllowedCapabilities, or a new wrapper function
to coordinate and rollback).
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
Bugbot Autofix prepared a fix for the issue found in the latest run.
- ✅ Fixed: Redundant normalization calls in review render path
- Stored normalized hosts and capabilities in local variables and reused them in the review render path to avoid redundant calls.
Preview (b880a5d72f)
diff --git a/packages/worker/client/routes/account-secrets.tsx b/packages/worker/client/routes/account-secrets.tsx
--- a/packages/worker/client/routes/account-secrets.tsx
+++ b/packages/worker/client/routes/account-secrets.tsx
@@ -25,6 +25,11 @@
transitions,
typography,
} from '#client/styles/tokens.ts'
+import { SecretEditorFields } from './secret-editor-fields.tsx'
+import {
+ normalizeAllowedCapabilities,
+ normalizeAllowedHosts,
+} from './secret-normalization.ts'
type SecretScope = 'app' | 'user'
@@ -118,30 +123,6 @@
return list.filter((item): item is string => typeof item === 'string')
}
-/** Matches server `normalizeAllowedHosts` in `#mcp/secrets/allowed-hosts.ts`. */
-function clientNormalizeAllowedHosts(hosts: Array<string>): Array<string> {
- return Array.from(
- new Set(
- hosts
- .map((host) => host.trim().toLowerCase())
- .filter((host) => host.length > 0),
- ),
- ).sort()
-}
-
-/** Matches server `normalizeAllowedCapabilities` in `#mcp/secrets/allowed-capabilities.ts`. */
-function clientNormalizeAllowedCapabilities(
- capabilities: Array<string>,
-): Array<string> {
- return Array.from(
- new Set(
- capabilities
- .map((value) => value.trim())
- .filter((value) => value.length > 0),
- ),
- ).sort((left, right) => left.localeCompare(right))
-}
-
function collectRepeatedTextRows(
form: HTMLFormElement,
listName: 'allowed-hosts' | 'allowed-capabilities',
@@ -564,10 +545,10 @@
handle.update()
try {
- const allowedHosts = clientNormalizeAllowedHosts(
+ const allowedHosts = normalizeAllowedHosts(
collectRepeatedTextRows(form, 'allowed-hosts'),
)
- const allowedCapabilities = clientNormalizeAllowedCapabilities(
+ const allowedCapabilities = normalizeAllowedCapabilities(
collectRepeatedTextRows(form, 'allowed-capabilities'),
)
const response = await fetch(accountSecretsApiPath, {
@@ -1205,272 +1186,40 @@
})
: null}
- <label css={fieldCss}>
- <span css={fieldLabelCss}>Description</span>
- <textarea
- value={editorState.description}
- rows={3}
- placeholder="What this secret is used for"
- on={{
- input: (event) => {
- editorState = {
- ...editorState,
- description: event.currentTarget.value,
- }
- handle.update()
- },
- }}
- css={textareaCss}
- />
- </label>
+ <SecretEditorFields
+ description={editorState.description}
+ onDescriptionChange={(description) => {
+ editorState = {
+ ...editorState,
+ description,
+ }
+ handle.update()
+ }}
+ value={editorState.value}
+ onValueChange={(value) => {
+ editorState = {
+ ...editorState,
+ value,
+ }
+ handle.update()
+ }}
+ showSecretValue={showSecretValue}
+ onToggleShowSecretValue={() => {
+ showSecretValue = !showSecretValue
+ handle.update()
+ }}
+ allowedHosts={editorState.allowedHosts}
+ onUpdateAllowedHost={updateAllowedHost}
+ onAddAllowedHost={addAllowedHost}
+ onRemoveAllowedHost={removeAllowedHost}
+ allowedCapabilities={editorState.allowedCapabilities}
+ onUpdateAllowedCapability={updateAllowedCapability}
+ onAddAllowedCapability={addAllowedCapability}
+ onRemoveAllowedCapability={removeAllowedCapability}
+ allowedHostsListName="allowed-hosts"
+ allowedCapabilitiesListName="allowed-capabilities"
+ />
- <label css={fieldCss}>
- <span css={fieldLabelCss}>Secret value</span>
- <div
- css={{
- position: 'relative',
- display: 'flex',
- alignItems: 'center',
- }}
- >
- {showSecretValue ? (
- <input
- type="text"
- required
- autoComplete="new-password"
- value={editorState.value}
- placeholder="Enter the secret value"
- on={{
- input: (event) => {
- editorState = {
- ...editorState,
- value: event.currentTarget.value,
- }
- handle.update()
- },
- }}
- css={{
- ...inputCss,
- paddingRight: '3rem',
- }}
- />
- ) : (
- <input
- type="password"
- required
- autoComplete="new-password"
- value={editorState.value}
- placeholder="Enter the secret value"
- on={{
- input: (event) => {
- editorState = {
- ...editorState,
- value: event.currentTarget.value,
- }
- handle.update()
- },
- }}
- css={{
- ...inputCss,
- paddingRight: '3rem',
- }}
- />
- )}
- <button
- type="button"
- aria-label={
- showSecretValue
- ? 'Hide secret value'
- : 'Show secret value'
- }
- title={
- showSecretValue
- ? 'Hide secret value'
- : 'Show secret value'
- }
- on={{
- click: () => {
- showSecretValue = !showSecretValue
- handle.update()
- },
- }}
- css={{
- position: 'absolute',
- right: spacing.sm,
- background: 'none',
- border: 'none',
- padding: 0,
- color: colors.textMuted,
- cursor: 'pointer',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- '&:hover': {
- color: colors.text,
- },
- }}
- >
- {showSecretValue ? (
- <svg
- xmlns="http://www.w3.org/2000/svg"
- width="20"
- height="20"
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- stroke-width="2"
- stroke-linecap="round"
- stroke-linejoin="round"
- >
- <path d="M9.88 9.88a3 3 0 1 0 4.24 4.24" />
- <path d="M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68" />
- <path d="M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61" />
- <line x1="2" x2="22" y1="2" y2="22" />
- </svg>
- ) : (
- <svg
- xmlns="http://www.w3.org/2000/svg"
- width="20"
- height="20"
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- stroke-width="2"
- stroke-linecap="round"
- stroke-linejoin="round"
- >
- <path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z" />
- <circle cx="12" cy="12" r="3" />
- </svg>
- )}
- </button>
- </div>
- </label>
-
- <div css={{ display: 'grid', gap: spacing.sm }}>
- <div css={{ display: 'grid', gap: spacing.xs }}>
- <span css={fieldLabelCss}>Allowed hosts</span>
- <p css={{ margin: 0, color: colors.textMuted }}>
- Leave this empty to require explicit host approval before
- a secret can be used.
- </p>
- </div>
- <div
- css={{ display: 'grid', gap: spacing.sm }}
- data-repeat-list="allowed-hosts"
- >
- {editorState.allowedHosts.map((host, index) => (
- <div
- key={index}
- css={{
- display: 'grid',
- gridTemplateColumns: 'minmax(0, 1fr) auto',
- gap: spacing.sm,
- [mq.mobile]: {
- gridTemplateColumns: '1fr',
- },
- }}
- >
- <input
- type="text"
- value={typeof host === 'string' ? host : ''}
- placeholder="api.example.com"
- on={{
- input: (event) =>
- updateAllowedHost(
- index,
- event.currentTarget.value,
- ),
- }}
- css={inputCss}
- />
- <button
- type="button"
- on={{ click: () => removeAllowedHost(index) }}
- css={secondaryButtonCss}
- >
- Remove
- </button>
- </div>
- ))}
- </div>
- <div>
- <button
- type="button"
- on={{ click: addAllowedHost }}
- css={secondaryButtonCss}
- >
- Add host
- </button>
- </div>
- </div>
-
- <div css={{ display: 'grid', gap: spacing.sm }}>
- <div css={{ display: 'grid', gap: spacing.xs }}>
- <span css={fieldLabelCss}>Allowed capabilities</span>
- <p css={{ margin: 0, color: colors.textMuted }}>
- Only capabilities listed here can resolve this secret when
- used with an
- <code> x-kody-secret </code>
- input.
- </p>
- </div>
- <div
- css={{ display: 'grid', gap: spacing.sm }}
- data-repeat-list="allowed-capabilities"
- >
- {editorState.allowedCapabilities.map(
- (capabilityName, index) => (
- <div
- key={index}
- css={{
- display: 'grid',
- gridTemplateColumns: 'minmax(0, 1fr) auto',
- gap: spacing.sm,
- [mq.mobile]: {
- gridTemplateColumns: '1fr',
- },
- }}
- >
- <input
- type="text"
- value={
- typeof capabilityName === 'string'
- ? capabilityName
- : ''
- }
- placeholder="home_lutron_set_credentials"
- on={{
- input: (event) =>
- updateAllowedCapability(
- index,
- event.currentTarget.value,
- ),
- }}
- css={inputCss}
- />
- <button
- type="button"
- on={{ click: () => removeAllowedCapability(index) }}
- css={secondaryButtonCss}
- >
- Remove
- </button>
- </div>
- ),
- )}
- </div>
- <div>
- <button
- type="button"
- on={{ click: addAllowedCapability }}
- css={secondaryButtonCss}
- >
- Add capability
- </button>
- </div>
- </div>
-
{selectedSecret ? (
<div
css={{
@@ -1601,12 +1350,6 @@
boxSizing: 'border-box' as const,
}
-const textareaCss = {
- ...inputCss,
- resize: 'vertical' as const,
- minHeight: '7rem',
-}
-
const comboboxListCss = {
position: 'absolute' as const,
top: '100%',
diff --git a/packages/worker/client/routes/connect-secret.tsx b/packages/worker/client/routes/connect-secret.tsx
--- a/packages/worker/client/routes/connect-secret.tsx
+++ b/packages/worker/client/routes/connect-secret.tsx
@@ -7,6 +7,11 @@
spacing,
typography,
} from '#client/styles/tokens.ts'
+import { SecretEditorFields } from './secret-editor-fields.tsx'
+import {
+ normalizeAllowedCapabilities,
+ normalizeAllowedHosts,
+} from './secret-normalization.ts'
import { formatConnectorConfigFailureMessage } from './connect-secret-errors.ts'
type StorageScope = 'app' | 'session' | 'user'
@@ -45,9 +50,12 @@
type ConnectSecretState = {
step: ViewStep
error: string
+ description: string
secretValue: string
+ allowedHosts: Array<string>
+ allowedCapabilities: Array<string>
+ showSecretValue: boolean
existingSecret: SecretMetadata | null
- updateConfirmed: boolean
confirmedReview: boolean
}
@@ -64,9 +72,12 @@
const defaultState: ConnectSecretState = {
step: 'loading',
error: '',
+ description: '',
secretValue: '',
+ allowedHosts: [''],
+ allowedCapabilities: [''],
+ showSecretValue: false,
existingSecret: null,
- updateConfirmed: false,
confirmedReview: false,
}
@@ -120,6 +131,22 @@
}
}
+function toEditableRows(values: Array<string> | null | undefined) {
+ if (!Array.isArray(values) || values.length === 0) return ['']
+ return [...values]
+}
+
+function createInitialConnectSecretState(
+ params: ConnectSecretParams,
+): ConnectSecretState {
+ return {
+ ...defaultState,
+ description: params.description,
+ allowedHosts: toEditableRows(params.allowedHosts),
+ allowedCapabilities: toEditableRows(params.allowedCapabilities),
+ }
+}
+
function scopeLabel(scope: StorageScope) {
if (scope === 'session') return 'Session (expires when this session ends)'
if (scope === 'app') return 'App'
@@ -203,22 +230,28 @@
async function saveSecretValue(
params: ConnectSecretParams,
session: ConnectSecretSession,
- value: string,
+ input: {
+ value: string
+ description: string
+ allowedHosts: Array<string>
+ allowedCapabilities: Array<string>
+ },
) {
- const response = await fetch(session.endpoints.secrets, {
+ const response = await fetch('/connect/secret.json', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
- Authorization: `Bearer ${session.token}`,
},
- credentials: 'omit',
+ credentials: 'include',
body: JSON.stringify({
- action: 'save',
name: params.name,
- value,
- description: params.description,
scope: params.scope,
+ sessionToken: session.token,
+ value: input.value,
+ description: input.description,
+ allowedHosts: input.allowedHosts,
+ allowedCapabilities: input.allowedCapabilities,
}),
})
const payload = (await response.json().catch(() => null)) as {
@@ -233,6 +266,10 @@
async function updateConnectorConfig(
params: ConnectSecretParams,
session: ConnectSecretSession,
+ input: {
+ allowedHosts: Array<string>
+ allowedCapabilities: Array<string>
+ },
) {
if (!params.connector) return
const response = await fetch('/connect/secret.json', {
@@ -247,8 +284,8 @@
scope: params.scope,
sessionToken: session.token,
connector: params.connector,
- allowedHosts: params.allowedHosts,
- allowedCapabilities: params.allowedCapabilities,
+ allowedHosts: input.allowedHosts,
+ allowedCapabilities: input.allowedCapabilities,
}),
})
const payload = (await response.json().catch(() => null)) as {
@@ -323,12 +360,19 @@
if (version !== initVersion) return
if (existing) {
setState({
+ ...createInitialConnectSecretState(params),
step: 'update-confirm',
existingSecret: existing,
+ description: existing.description,
+ allowedHosts: toEditableRows(existing.allowed_hosts),
+ allowedCapabilities: toEditableRows(existing.allowed_capabilities),
})
return
}
- setState({ step: 'input' })
+ setState({
+ ...createInitialConnectSecretState(params),
+ step: 'input',
+ })
} catch (error) {
if (version !== initVersion) return
if (isSessionRefreshError(error)) {
@@ -353,6 +397,10 @@
return
}
const params = parseConnectSecretParams()
+ const normalizedAllowedHosts = normalizeAllowedHosts(state.allowedHosts)
+ const normalizedAllowedCapabilities = normalizeAllowedCapabilities(
+ state.allowedCapabilities,
+ )
if (!state.secretValue.trim()) {
setState({
step: 'error',
@@ -362,7 +410,12 @@
}
setState({ step: 'saving', error: '' })
try {
- await saveSecretValue(params, session, state.secretValue)
+ await saveSecretValue(params, session, {
+ value: state.secretValue,
+ description: state.description,
+ allowedHosts: normalizedAllowedHosts,
+ allowedCapabilities: normalizedAllowedCapabilities,
+ })
} catch (error) {
if (isSessionRefreshError(error)) {
startInitialization()
@@ -376,7 +429,10 @@
return
}
try {
- await updateConnectorConfig(params, session)
+ await updateConnectorConfig(params, session, {
+ allowedHosts: normalizedAllowedHosts,
+ allowedCapabilities: normalizedAllowedCapabilities,
+ })
setState({ step: 'success' })
} catch (error) {
const secretWasNewlyCreated = state.existingSecret == null
@@ -419,17 +475,72 @@
setState({ step: 'input', error: '' })
}
+ function updateAllowedHost(index: number, value: string) {
+ setState({
+ allowedHosts: state.allowedHosts.map((host, hostIndex) =>
+ hostIndex === index ? value : host,
+ ),
+ })
+ }
+
+ function addAllowedHost() {
+ setState({
+ allowedHosts: [...state.allowedHosts, ''],
+ })
+ }
+
+ function removeAllowedHost(index: number) {
+ const nextHosts = state.allowedHosts.filter(
+ (_host, hostIndex) => hostIndex !== index,
+ )
+ setState({
+ allowedHosts: nextHosts.length > 0 ? nextHosts : [''],
+ })
+ }
+
+ function updateAllowedCapability(index: number, value: string) {
+ setState({
+ allowedCapabilities: state.allowedCapabilities.map(
+ (capability, capabilityIndex) =>
+ capabilityIndex === index ? value : capability,
+ ),
+ })
+ }
+
+ function addAllowedCapability() {
+ setState({
+ allowedCapabilities: [...state.allowedCapabilities, ''],
+ })
+ }
+
+ function removeAllowedCapability(index: number) {
+ const nextCapabilities = state.allowedCapabilities.filter(
+ (_capability, capabilityIndex) => capabilityIndex !== index,
+ )
+ setState({
+ allowedCapabilities: nextCapabilities.length > 0 ? nextCapabilities : [''],
+ })
+ }
+
return () => {
const currentSearch =
typeof window === 'undefined' ? '' : window.location.search
if (currentSearch !== lastSearch) {
lastSearch = currentSearch
- startInitialization()
+ // Defer: startInitialization calls handle.update(), which must not run during
+ // render (Remix component runtime throws "scheduleUpdate not implemented").
+ handle.queueTask(() => {
+ startInitialization()
+ })
}
const params = parseConnectSecretParams()
const hasInstructions = Boolean(params.instructions || params.dashboardUrl)
const showReview = state.step === 'review' || state.step === 'saving'
+ const normalizedAllowedHosts = normalizeAllowedHosts(state.allowedHosts)
+ const normalizedAllowedCapabilities = normalizeAllowedCapabilities(
+ state.allowedCapabilities,
+ )
return (
<section
@@ -516,8 +627,7 @@
type="button"
css={primaryButtonCss}
on={{
- click: () =>
- setState({ step: 'input', updateConfirmed: true }),
+ click: () => setState({ step: 'input' }),
}}
>
Update secret
@@ -600,20 +710,25 @@
<section css={cardCss}>
<h2 css={cardTitleCss}>Enter secret</h2>
- <label css={{ display: 'grid', gap: spacing.xs }}>
- <span css={labelCss}>Secret value</span>
- <input
- type="password"
- autoComplete="new-password"
- value={state.secretValue}
- placeholder="Paste the secret value"
- on={{
- input: (event) =>
- setState({ secretValue: event.currentTarget.value }),
- }}
- css={inputCss}
- />
- </label>
+ <SecretEditorFields
+ description={state.description}
+ onDescriptionChange={(description) => setState({ description })}
+ value={state.secretValue}
+ onValueChange={(secretValue) => setState({ secretValue })}
+ showSecretValue={state.showSecretValue}
+ onToggleShowSecretValue={() =>
+ setState({ showSecretValue: !state.showSecretValue })
+ }
+ allowedHosts={state.allowedHosts}
+ onUpdateAllowedHost={updateAllowedHost}
+ onAddAllowedHost={addAllowedHost}
+ onRemoveAllowedHost={removeAllowedHost}
+ allowedCapabilities={state.allowedCapabilities}
+ onUpdateAllowedCapability={updateAllowedCapability}
+ onAddAllowedCapability={addAllowedCapability}
+ onRemoveAllowedCapability={removeAllowedCapability}
+ valuePlaceholder="Paste the secret value"
+ />
</section>
{showReview ? (
@@ -634,10 +749,10 @@
<div css={labelCss}>Scope</div>
<div>{scopeLabel(params.scope)}</div>
</div>
- {params.description ? (
+ {state.description ? (
<div css={{ gridColumn: '1 / -1' }}>
<div css={labelCss}>Description</div>
- <div>{params.description}</div>
+ <div>{state.description}</div>
</div>
) : null}
</div>
@@ -651,8 +766,8 @@
<div>
<div css={labelCss}>Hosts to approve</div>
<ul css={listCss}>
- {params.allowedHosts.length > 0 ? (
- params.allowedHosts.map((host) => (
+ {normalizedAllowedHosts.length > 0 ? (
+ normalizedAllowedHosts.map((host) => (
<li key={host}>{host}</li>
))
) : (
@@ -663,8 +778,8 @@
<div>
<div css={labelCss}>Capabilities to allow</div>
<ul css={listCss}>
- {params.allowedCapabilities.length > 0 ? (
- params.allowedCapabilities.map((capability) => (
+ {normalizedAllowedCapabilities.length > 0 ? (
+ normalizedAllowedCapabilities.map((capability) => (
<li key={capability}>{capability}</li>
))
) : (
@@ -790,16 +905,6 @@
color: colors.text,
}
-const inputCss = {
- padding: spacing.sm,
- borderRadius: radius.md,
- border: `1px solid ${colors.border}`,
- backgroundColor: colors.background,
- color: colors.text,
- fontFamily: typography.fontFamily,
- fontSize: typography.fontSize.base,
-}
-
const primaryButtonCss = {
padding: `${spacing.sm} ${spacing.lg}`,
borderRadius: radius.full,
diff --git a/packages/worker/client/routes/secret-editor-fields.tsx b/packages/worker/client/routes/secret-editor-fields.tsx
new file mode 100644
--- /dev/null
+++ b/packages/worker/client/routes/secret-editor-fields.tsx
@@ -1,0 +1,294 @@
+import { type Handle } from 'remix/component'
+import { colors, mq, radius, spacing, typography } from '#client/styles/tokens.ts'
+
+type SecretEditorFieldsProps = {
+ description: string
+ onDescriptionChange: (value: string) => void
+ value: string
+ onValueChange: (value: string) => void
+ showSecretValue: boolean
+ onToggleShowSecretValue: () => void
+ allowedHosts: Array<string>
+ onUpdateAllowedHost: (index: number, value: string) => void
+ onAddAllowedHost: () => void
+ onRemoveAllowedHost: (index: number) => void
+ allowedCapabilities: Array<string>
+ onUpdateAllowedCapability: (index: number, value: string) => void
+ onAddAllowedCapability: () => void
+ onRemoveAllowedCapability: (index: number) => void
+ valuePlaceholder?: string
+ allowedHostsListName?: string
+ allowedCapabilitiesListName?: string
+}
+
+export function SecretEditorFields(_handle: Handle) {
+ return (props: SecretEditorFieldsProps) => (
+ <>
+ <label css={fieldCss}>
+ <span css={fieldLabelCss}>Description</span>
+ <textarea
+ value={props.description}
+ rows={3}
+ placeholder="What this secret is used for"
+ on={{
+ input: (event) => {
+ props.onDescriptionChange(event.currentTarget.value)
+ },
+ }}
+ css={textareaCss}
+ />
+ </label>
+
+ <label css={fieldCss}>
+ <span css={fieldLabelCss}>Secret value</span>
+ <div
+ css={{
+ position: 'relative',
+ display: 'flex',
+ alignItems: 'center',
+ }}
+ >
+ {props.showSecretValue ? (
+ <input
+ type="text"
+ required
+ autoComplete="new-password"
+ value={props.value}
+ placeholder={props.valuePlaceholder ?? 'Enter the secret value'}
... diff truncated: showing 800 of 1265 linesYou can send follow-ups to this agent here.
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
There was a problem hiding this comment.
🧹 Nitpick comments (1)
packages/worker/client/routes/connect-secret.tsx (1)
400-403: Consider extracting normalization into one helper to reduce drift risk.Normalization is currently repeated in save and render paths; a shared helper would make future normalization rule changes safer.
♻️ Optional refactor sketch
+function getNormalizedReviewState(state: ConnectSecretState) { + return { + normalizedAllowedHosts: normalizeAllowedHosts(state.allowedHosts), + normalizedAllowedCapabilities: normalizeAllowedCapabilities( + state.allowedCapabilities, + ), + } +} ... -const normalizedAllowedHosts = normalizeAllowedHosts(state.allowedHosts) -const normalizedAllowedCapabilities = normalizeAllowedCapabilities( - state.allowedCapabilities, -) +const { normalizedAllowedHosts, normalizedAllowedCapabilities } = + getNormalizedReviewState(state) ... -const normalizedAllowedHosts = normalizeAllowedHosts(state.allowedHosts) -const normalizedAllowedCapabilities = normalizeAllowedCapabilities( - state.allowedCapabilities, -) +const { normalizedAllowedHosts, normalizedAllowedCapabilities } = + getNormalizedReviewState(state)Also applies to: 540-543
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/worker/client/routes/connect-secret.tsx` around lines 400 - 403, Extract the repeated normalization logic into a single helper (e.g., normalizeAllowedEntries or normalizeAllowedForState) that accepts the component state (or the two fields state.allowedHosts and state.allowedCapabilities) and returns normalizedAllowedHosts and normalizedAllowedCapabilities; replace direct calls to normalizeAllowedHosts(...) and normalizeAllowedCapabilities(...) in both the render path and the save path with this helper to ensure a single source of truth for normalization and avoid drift across normalizeAllowedHosts and normalizeAllowedCapabilities usage.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@packages/worker/client/routes/connect-secret.tsx`:
- Around line 400-403: Extract the repeated normalization logic into a single
helper (e.g., normalizeAllowedEntries or normalizeAllowedForState) that accepts
the component state (or the two fields state.allowedHosts and
state.allowedCapabilities) and returns normalizedAllowedHosts and
normalizedAllowedCapabilities; replace direct calls to
normalizeAllowedHosts(...) and normalizeAllowedCapabilities(...) in both the
render path and the save path with this helper to ensure a single source of
truth for normalization and avoid drift across normalizeAllowedHosts and
normalizeAllowedCapabilities usage.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: e68a5444-69fd-4bdd-93ea-49bb374cfade
📒 Files selected for processing (1)
packages/worker/client/routes/connect-secret.tsx
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
|
@cursoragent please address the CI failures on this PR |
|
Walkthrough Summary
Testing
|
…-query-defaults-b946 Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>




Summary
/connect/secret.jsonso stored policy matches what the user sees in the form and connector bindingmainchanges and fix account-secrets merge regressions so typecheck and E2E pass togetherTesting
http://localhost:3742/connect/secret?...confirming editable defaults and normalized review state/account/secrets/user/manual-secret-checkrenders the selected secret detail pane after the merge fixconnect-secret-query-defaults-demo.mp4
Connect secret editable defaults
Connect secret review state
Account secrets selected secret detail pane
Summary by CodeRabbit
New Features
Bug Fixes
Tests