Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(control-ui): wire the generic OAuth install wizard, prefill, and immutables (S3-B4b)
Diego Zacarias5cd6fd5b7f52
diff --git a/control-ui/app/constants/oauthProviders.ts b/control-ui/app/constants/oauthProviders.tsindex 83e279345..ca7fc7346 100644--- a/control-ui/app/constants/oauthProviders.ts+++ b/control-ui/app/constants/oauthProviders.ts@@ -1,8 +1,9 @@-// Display metadata for the 8 baked OAuth providers (Slice 1). The provider id is-// the frozen enum control-api serves via isKnownOAuthProvider; these are only-// labels and the provider's own "where to register the redirect URI" docs shown-// beside the redirect URI in the install wizard (D-B4). The generic sentinel is-// Slice 3 and intentionally absent.+// Display metadata for the 8 baked OAuth providers (Slice 1) plus the `generic`+// sentinel (Slice 3, S3-B4). The baked provider ids are the frozen enum control-api+// serves via isKnownOAuthProvider; `generic` is NOT a baked provider — it is the+// self-hosted `source:'generic'` carril and carries only a label (no provider docs+// URL, since there is no single provider). These are the labels and the provider's own+// "where to register the redirect URI" docs shown beside the redirect URI (D-B4).export const OAUTH_PROVIDER_LABELS: Record<string, string> = {google: 'Google',@@ -13,6 +14,7 @@ export const OAUTH_PROVIDER_LABELS: Record<string, string> = {monday: 'monday.com',clickup: 'ClickUp',vercel: 'Vercel',+ generic: 'Custom OAuth 2.0 provider',}// Where the operator registers the OAuth app + redirect URI for each provider.diff --git a/control-ui/app/globals.css b/control-ui/app/globals.cssindex a68ab7bd6..0ec8aa734 100644--- a/control-ui/app/globals.css+++ b/control-ui/app/globals.css@@ -14275,3 +14275,43 @@ button.cu-gfs-tree__button:focus-visible,.cu-llm-policy__actions {display: flex;}++/* ── Generic OAuth carril install wizard (S3-B4) ──────────────────────────── */+.cu-generic-field-row {+ display: flex;+ align-items: center;+ gap: var(--cu-space-2);+}++.cu-generic-field-row > :first-child {+ flex: 1;+ min-width: 0;+}++.cu-generic-origin {+ flex: none;+ white-space: nowrap;+}++.cu-generic-toggles {+ display: flex;+ flex-direction: column;+ gap: var(--cu-space-2);+}++.cu-generic-params {+ display: flex;+ flex-direction: column;+ gap: var(--cu-space-2);+}++.cu-generic-param-row {+ display: flex;+ align-items: center;+ gap: var(--cu-space-2);+}++.cu-generic-param-row > input {+ flex: 1;+ min-width: 0;+}diff --git a/control-ui/components/OAuthImmutableFields/index.tsx b/control-ui/components/OAuthImmutableFields/index.tsxindex ab5c8e139..f4623f261 100644--- a/control-ui/components/OAuthImmutableFields/index.tsx+++ b/control-ui/components/OAuthImmutableFields/index.tsx@@ -3,6 +3,7 @@import React from 'react'import { Field, TextInput } from '@components/ui'import { oauthProviderLabel } from '@constants/oauthProviders'+import type { GenericImmutableView } from '@lib/oauthGeneric.types'import type { OAuthImmutableFieldsProps } from './types'const GRANT_SCOPE_LABELS: Record<string, string> = {@@ -62,6 +63,131 @@ export function OAuthImmutableFields({ oauth, credentialSecretName }: OAuthImmutdisabled/></Field>++ {oauth.generic ? <GenericImmutableFields generic={oauth.generic} /> : null}</section>)}++const YES_NO = (value: boolean): string => (value ? 'Yes' : 'No')++/**+ * The generic carril's endpoints and wire knobs, read-only. Every field is create-only+ * (GENERIC-IMM / GENERIC-SECRET-IMM): changing one means delete + recreate.+ */+function GenericImmutableFields({ generic }: { generic: GenericImmutableView }) {+ return (+ <>+ <Field htmlFor="oauth-immutable-client-mode" label="Client type">+ <TextInput+ id="oauth-immutable-client-mode"+ value={generic.clientMode === 'confidential' ? 'Confidential' : 'Public'}+ readOnly+ disabled+ />+ </Field>++ <Field htmlFor="oauth-immutable-auth-endpoint" label="Authorization endpoint">+ <TextInput+ id="oauth-immutable-auth-endpoint"+ value={generic.authorizationEndpoint || '-'}+ readOnly+ disabled+ monospace+ />+ </Field>++ <Field htmlFor="oauth-immutable-token-endpoint" label="Token endpoint">+ <TextInput+ id="oauth-immutable-token-endpoint"+ value={generic.tokenEndpoint || '-'}+ readOnly+ disabled+ monospace+ />+ </Field>++ {generic.refreshEndpoint ? (+ <Field htmlFor="oauth-immutable-refresh-endpoint" label="Refresh endpoint">+ <TextInput+ id="oauth-immutable-refresh-endpoint"+ value={generic.refreshEndpoint}+ readOnly+ disabled+ monospace+ />+ </Field>+ ) : null}++ {generic.resource ? (+ <Field htmlFor="oauth-immutable-resource" label="Resource">+ <TextInput+ id="oauth-immutable-resource"+ value={generic.resource}+ readOnly+ disabled+ monospace+ />+ </Field>+ ) : null}++ <Field htmlFor="oauth-immutable-token-format" label="Token request format">+ <TextInput+ id="oauth-immutable-token-format"+ value={generic.tokenRequestFormat || '-'}+ readOnly+ disabled+ />+ </Field>++ <Field htmlFor="oauth-immutable-auth-method" label="Client authentication method">+ <TextInput+ id="oauth-immutable-auth-method"+ value={generic.tokenAuthMethod || '-'}+ readOnly+ disabled+ />+ </Field>++ <Field htmlFor="oauth-immutable-scope-sep" label="Scope separator">+ <TextInput+ id="oauth-immutable-scope-sep"+ value={generic.scopeSeparator || '-'}+ readOnly+ disabled+ />+ </Field>++ <Field htmlFor="oauth-immutable-pkce" label="Use PKCE (S256)">+ <TextInput id="oauth-immutable-pkce" value={YES_NO(generic.usePkce)} readOnly disabled />+ </Field>++ <Field htmlFor="oauth-immutable-send-scope" label="Send scope">+ <TextInput+ id="oauth-immutable-send-scope"+ value={YES_NO(generic.sendScope)}+ readOnly+ disabled+ />+ </Field>++ <Field htmlFor="oauth-immutable-response-type" label="Include response_type">+ <TextInput+ id="oauth-immutable-response-type"+ value={YES_NO(generic.includeResponseType)}+ readOnly+ disabled+ />+ </Field>++ <Field htmlFor="oauth-immutable-supports-refresh" label="Issues refresh tokens">+ <TextInput+ id="oauth-immutable-supports-refresh"+ value={YES_NO(generic.supportsRefresh)}+ readOnly+ disabled+ />+ </Field>+ </>+ )+}diff --git a/control-ui/components/OAuthInstallForm/GenericEndpointsStep.tsx b/control-ui/components/OAuthInstallForm/GenericEndpointsStep.tsxnew file mode 100644index 000000000..585b695e8--- /dev/null+++ b/control-ui/components/OAuthInstallForm/GenericEndpointsStep.tsx@@ -0,0 +1,379 @@+'use client'++import React, { useState } from 'react'+import { Button, CheckboxField, Field, SelectInput, TextInput } from '@components/ui'+import { discoverGenericOAuth } from '@lib/api'+import { newExtraParamRow } from '@lib/oauthGeneric'+import type { GenericFieldOrigin, GenericTouchKey } from '@lib/oauthGeneric.types'+import { mapRemoteDiscoverError } from '@lib/remoteMcp'+import type { GenericEndpointsStepProps } from './types'++const ORIGIN_LABELS: Record<Exclude<GenericFieldOrigin, 'default'>, string> = {+ catalog: 'From catalog',+ detected: 'Detected',+ edited: 'Edited',+}++// A small provenance badge so the operator can audit where a value came from (S-4).+function OriginBadge({ origin }: { origin: GenericFieldOrigin }) {+ if (origin === 'default') return null+ return <span className="cu-chip cu-generic-origin">{ORIGIN_LABELS[origin]}</span>+}++/**+ * Endpoints + wire-knob step of the generic install wizard (S3-B4). Lives in its own+ * component so the baked path in OAuthInstallForm stays byte-identical (F1). Owns only+ * the local Detect input; every persistent value lives in the parent's form state.+ * Detect never mutates the form — it stores the result and the operator clicks Apply+ * (invariant 8).+ */+export function GenericEndpointsStep({+ state,+ issues,+ onEditString,+ onEditEnum,+ onEditBool,+ onExtraParamsChange,+ onDetected,+ onApply,+}: GenericEndpointsStepProps) {+ const [detectUrl, setDetectUrl] = useState('')+ const [detecting, setDetecting] = useState(false)+ const [detectError, setDetectError] = useState('')++ const origin = (field: GenericTouchKey): GenericFieldOrigin => state.origin[field]++ async function handleDetect() {+ const url = detectUrl.trim()+ if (!url || detecting) return+ setDetecting(true)+ setDetectError('')+ try {+ const prefill = await discoverGenericOAuth(url)+ onDetected(prefill)+ } catch (error) {+ setDetectError(mapRemoteDiscoverError(error))+ } finally {+ setDetecting(false)+ }+ }++ function updateParam(id: string, patch: { key?: string; value?: string }) {+ onExtraParamsChange(+ state.extraAuthorizeParams.map(row => (row.id === id ? { ...row, ...patch } : row))+ )+ }+ function removeParam(id: string) {+ onExtraParamsChange(state.extraAuthorizeParams.filter(row => row.id !== id))+ }+ function addParam() {+ // newExtraParamRow() ids are a monotonic counter + randomUUID, collision-free even+ // for remove-then-add within one millisecond (a bare Date.now() id would not be).+ onExtraParamsChange([...state.extraAuthorizeParams, newExtraParamRow()])+ }++ const detected = state.detected++ return (+ <div className="cu-form-section">+ <div className="cu-form-section__header">+ <h3 className="cu-form-section__title">Authorization server endpoints</h3>+ <p className="cu-form-section__description">+ Point the broker at your OAuth 2.0 authorization server. Detect can read a public+ discovery document to suggest values — nothing is applied until you click Apply.+ </p>+ </div>++ {/* Detect (discovery-as-prefill). Never auto-applies (S-4, invariant 8). */}+ <Field+ htmlFor="oauth-generic-detect"+ label="Detect from issuer (optional)"+ description="An OAuth issuer or discovery URL (RFC 8414 / OpenID). We read its metadata over a validated, IP-pinned request."+ >+ <div className="cu-table-actions">+ <TextInput+ id="oauth-generic-detect"+ value={detectUrl}+ onChange={event => setDetectUrl(event.target.value)}+ placeholder="https://idp.example.com"+ monospace+ aria-label="Issuer or discovery URL"+ />+ <Button+ type="button"+ variant="secondary"+ size="sm"+ onClick={handleDetect}+ disabled={detecting || detectUrl.trim().length === 0}+ >+ {detecting ? 'Detecting…' : 'Detect'}+ </Button>+ </div>+ </Field>++ {detectError ? (+ <div className="cu-banner cu-banner--error" role="alert">+ {detectError}+ </div>+ ) : null}++ {detected ? (+ <div className="cu-banner cu-banner--info" role="status">+ <p>+ Detected authorization server <strong>{detected.issuer}</strong>. Review the suggested+ values, then apply them. Fields you have already edited are kept.+ </p>+ <section className="cu-summary-list" aria-label="Detected authorization server metadata">+ <div className="cu-summary-list__row">+ <span>Authorization endpoint</span>+ <strong>{detected.endpoints.authorization}</strong>+ </div>+ <div className="cu-summary-list__row">+ <span>Token endpoint</span>+ <strong>{detected.endpoints.token}</strong>+ </div>+ {detected.resource ? (+ <div className="cu-summary-list__row">+ <span>Resource</span>+ <strong>{detected.resource}</strong>+ </div>+ ) : null}+ <div className="cu-summary-list__row">+ <span>PKCE (S256)</span>+ <strong>+ {detected.capabilities.codeChallengeMethods.length > 0+ ? detected.suggested.usePkce+ ? 'Supported'+ : 'Not advertised'+ : 'No data'}+ </strong>+ </div>+ <div className="cu-summary-list__row">+ <span>Client auth method</span>+ <strong>+ {detected.capabilities.tokenEndpointAuthMethods.length > 0+ ? detected.suggested.tokenAuthMethod+ : 'No data'}+ </strong>+ </div>+ <div className="cu-summary-list__row">+ <span>Scopes</span>+ <strong>+ {detected.scopesSupported.length > 0 ? detected.scopesSupported.join(', ') : '—'}+ </strong>+ </div>+ </section>+ <div className="cu-table-actions">+ <Button type="button" variant="primary" size="sm" onClick={onApply}>+ Apply detected values+ </Button>+ </div>+ </div>+ ) : null}++ <Field+ htmlFor="oauth-generic-auth-endpoint"+ label="Authorization endpoint"+ description="The /authorize URL the browser is redirected to."+ required+ error={issues.authorizationEndpoint}+ >+ <div className="cu-generic-field-row">+ <TextInput+ id="oauth-generic-auth-endpoint"+ value={state.authorizationEndpoint}+ onChange={event => onEditString('authorizationEndpoint', event.target.value)}+ placeholder="https://idp.example.com/authorize"+ monospace+ />+ <OriginBadge origin={origin('authorizationEndpoint')} />+ </div>+ </Field>++ <Field+ htmlFor="oauth-generic-token-endpoint"+ label="Token endpoint"+ description="The /token URL the broker exchanges the code at."+ required+ error={issues.tokenEndpoint}+ >+ <div className="cu-generic-field-row">+ <TextInput+ id="oauth-generic-token-endpoint"+ value={state.tokenEndpoint}+ onChange={event => onEditString('tokenEndpoint', event.target.value)}+ placeholder="https://idp.example.com/token"+ monospace+ />+ <OriginBadge origin={origin('tokenEndpoint')} />+ </div>+ </Field>++ <Field+ htmlFor="oauth-generic-refresh-endpoint"+ label="Refresh endpoint (optional)"+ description="Leave blank to refresh at the token endpoint."+ error={issues.refreshEndpoint}+ >+ <div className="cu-generic-field-row">+ <TextInput+ id="oauth-generic-refresh-endpoint"+ value={state.refreshEndpoint}+ onChange={event => onEditString('refreshEndpoint', event.target.value)}+ placeholder="https://idp.example.com/token"+ monospace+ />+ <OriginBadge origin={origin('refreshEndpoint')} />+ </div>+ </Field>++ <Field+ htmlFor="oauth-generic-resource"+ label="Resource (optional, RFC 8707)"+ description="An absolute resource indicator, when your AS requires one."+ error={issues.resource}+ >+ <div className="cu-generic-field-row">+ <TextInput+ id="oauth-generic-resource"+ value={state.resource}+ onChange={event => onEditString('resource', event.target.value)}+ placeholder="https://api.example.com"+ monospace+ />+ <OriginBadge origin={origin('resource')} />+ </div>+ </Field>++ <Field+ htmlFor="oauth-generic-token-format"+ label="Token request format"+ description="How the token request body is encoded."+ >+ <div className="cu-generic-field-row">+ <SelectInput+ id="oauth-generic-token-format"+ value={state.tokenRequestFormat}+ onChange={event => onEditEnum('tokenRequestFormat', event.target.value)}+ >+ <option value="form">Form-encoded</option>+ <option value="json">JSON</option>+ </SelectInput>+ <OriginBadge origin={origin('tokenRequestFormat')} />+ </div>+ </Field>++ <Field+ htmlFor="oauth-generic-auth-method"+ label="Client authentication method"+ description="Basic requires a confidential client with a client secret."+ error={issues.tokenAuthMethod}+ >+ <div className="cu-generic-field-row">+ <SelectInput+ id="oauth-generic-auth-method"+ value={state.tokenAuthMethod}+ onChange={event => onEditEnum('tokenAuthMethod', event.target.value)}+ >+ <option value="body">Client secret in body (post)</option>+ <option value="basic">HTTP Basic (basic)</option>+ </SelectInput>+ <OriginBadge origin={origin('tokenAuthMethod')} />+ </div>+ </Field>++ <Field+ htmlFor="oauth-generic-scope-sep"+ label="Scope separator"+ description="How multiple scopes are joined in the authorize request."+ >+ <div className="cu-generic-field-row">+ <SelectInput+ id="oauth-generic-scope-sep"+ value={state.scopeSeparator}+ onChange={event => onEditEnum('scopeSeparator', event.target.value)}+ >+ <option value="space">Space</option>+ <option value="comma">Comma</option>+ </SelectInput>+ <OriginBadge origin={origin('scopeSeparator')} />+ </div>+ </Field>++ <div className="cu-generic-toggles">+ <CheckboxField+ id="oauth-generic-send-scope"+ checked={state.sendScope}+ onChange={event => onEditBool('sendScope', event.target.checked)}+ label="Send scope in the authorize request"+ description="Turn off only for an AS that rejects a scope parameter."+ />+ <CheckboxField+ id="oauth-generic-use-pkce"+ checked={state.usePkce}+ onChange={event => onEditBool('usePkce', event.target.checked)}+ label="Use PKCE (S256)"+ description="Recommended. Disable only for an AS that does not support PKCE."+ />+ <CheckboxField+ id="oauth-generic-response-type"+ checked={state.includeResponseType}+ onChange={event => onEditBool('includeResponseType', event.target.checked)}+ label="Include response_type=code"+ />+ <CheckboxField+ id="oauth-generic-supports-refresh"+ checked={state.supportsRefresh}+ onChange={event => onEditBool('supportsRefresh', event.target.checked)}+ label="Authorization server issues refresh tokens"+ description="When off, users re-consent as tokens expire."+ />+ </div>++ <Field+ label="Extra authorize parameters (optional)"+ description="Additional query params added to the authorize request. Up to 16."+ error={issues.extraAuthorizeParams}+ >+ <div className="cu-generic-params">+ {state.extraAuthorizeParams.map(row => (+ <div className="cu-generic-param-row" key={row.id}>+ <TextInput+ value={row.key}+ onChange={event => updateParam(row.id, { key: event.target.value })}+ placeholder="parameter"+ aria-label="Extra authorize parameter name"+ monospace+ />+ <TextInput+ value={row.value}+ onChange={event => updateParam(row.id, { value: event.target.value })}+ placeholder="value"+ aria-label="Extra authorize parameter value"+ monospace+ />+ <Button+ type="button"+ variant="ghost"+ size="sm"+ onClick={() => removeParam(row.id)}+ aria-label="Remove extra authorize parameter"+ >+ Remove+ </Button>+ </div>+ ))}+ <Button+ type="button"+ variant="ghost"+ size="sm"+ onClick={addParam}+ disabled={state.extraAuthorizeParams.length >= 16}+ >+ Add parameter+ </Button>+ </div>+ </Field>+ </div>+ )+}diff --git a/control-ui/components/OAuthInstallForm/index.tsx b/control-ui/components/OAuthInstallForm/index.tsxindex e62ddb471..62f30c008 100644--- a/control-ui/components/OAuthInstallForm/index.tsx+++ b/control-ui/components/OAuthInstallForm/index.tsx@@ -9,6 +9,18 @@ import { OAUTH_PROVIDER_DOC_URLS, oauthProviderLabel } from '@constants/oauthProimport { getOAuthCredentialManifest, installFromRegistry, listMcpSecrets } from '@lib/api'import { copyTextToClipboard } from '@lib/clipboard'import { isValidK8sName, toK8sName } from '@lib/k8sValidation'+import {+ GENERIC_WIZARD_DEFAULTS,+ applyDiscoveryPrefill,+ buildGenericSubmit,+ editEnumKnob,+ effectiveClientMode,+ genericFormIssues,+ genericFormOk,+ markEdited,+ seedFromCatalog,+} from '@lib/oauthGeneric'+import type { GenericFormState } from '@lib/oauthGeneric.types'import {buildOAuthRedirectUri,deriveOAuthClientIdPreview,@@ -22,12 +34,16 @@ import type {McpSecretSummary,OAuthCredentialField,OAuthGrantScope,+ OAuthInstallSubmit,OAuthSecretInput,} from '@lib/oauthInstall.types'import { createPrivateContext } from '@lib/privateContext'+import { GenericEndpointsStep } from './GenericEndpointsStep'import type { OAuthInstallFormProps } from './types'const STEPS = ['Provider', 'Credentials', 'Install'] as const+// The generic carril inserts an Endpoints step (S3-B4); baked stays 3 steps (F1).+const GENERIC_STEPS = ['Provider', 'Endpoints', 'Credentials', 'Install'] as constconst STEP_DETAILS = [{@@ -47,6 +63,31 @@ const STEP_DETAILS = [},] as const+const GENERIC_STEP_DETAILS = [+ {+ description: 'Register the redirect URI',+ title: 'Provider setup',+ subtitle:+ 'Register this redirect URI (and, for a public client, the client id) in your authorization server before you continue.',+ },+ {+ description: 'Authorization server',+ title: 'Endpoints & configuration',+ subtitle: 'Point the broker at your OAuth 2.0 authorization server and set its wire behaviour.',+ },+ {+ description: 'Client credentials',+ title: 'Client credentials',+ subtitle:+ 'Choose a public or confidential client. A confidential client needs a client secret.',+ },+ {+ description: 'Scopes and install',+ title: 'Scopes and install',+ subtitle: 'Set the grant type and scopes, then install the connector.',+ },+] as const+// Canonical field names in every baked provider's credential manifest. control-api// keys the managed Secret by these exact names (OAUTH_CLIENT_ID_KEY /// OAUTH_CLIENT_SECRET_KEY in routes/admin/registry.ts), so the manifest field, the@@ -63,9 +104,13 @@ export function OAuthInstallForm({}: OAuthInstallFormProps) {const { showToast } = useToast()const provider = catalogOAuth.provider+ const isGeneric = provider === 'generic'const providerLabel = oauthProviderLabel(provider)const docUrl = OAUTH_PROVIDER_DOC_URLS[provider]+ const steps = isGeneric ? GENERIC_STEPS : STEPS+ const stepDetails = isGeneric ? GENERIC_STEP_DETAILS : STEP_DETAILS+const [step, setStep] = useState(0)const [serverName, setServerName] = useState(toK8sName(entry.name))const [secretMode, setSecretMode] = useState<'managed' | 'reference'>('managed')@@ -78,6 +123,12 @@ export function OAuthInstallForm({const [grantScope, setGrantScope] = useState<OAuthGrantScope>(catalogOAuth.grantScope ?? 'user')const [scopesText, setScopesText] = useState(formatScopesForInput(catalogOAuth.scopes ?? []))+ // Generic-carril form state (S3-B4). Seeded once from the catalog suggestion; unused on+ // the baked path (seed with no suggestion is cheap and keeps hook order unconditional).+ const [genericState, setGenericState] = useState<GenericFormState>(() =>+ seedFromCatalog(GENERIC_WIZARD_DEFAULTS, catalogOAuth.genericConfig, catalogOAuth.scopes)+ )+const [manifest, setManifest] = useState<OAuthCredentialField[]>([])const [secrets, setSecrets] = useState<McpSecretSummary[]>([])const [loading, setLoading] = useState(true)@@ -87,10 +138,18 @@ export function OAuthInstallForm({const [installed, setInstalled] = useState(false)const installInFlightRef = useRef(false)+ const genericMode = isGeneric ? effectiveClientMode(genericState) : 'confidential'+ const genericPublic = isGeneric && genericMode === 'public'+ const forcedConfidential = isGeneric && genericState.tokenAuthMethod === 'basic'+useEffect(() => {let cancelled = falsesetLoading(true)setLoadError('')+ // A public generic client asks for no credentials (DA-1), so its manifest is empty+ // and never fetched; every other case loads the provider's credential manifest.+ const needManifest = !isGeneric || genericMode === 'confidential'+ const manifestProvider = isGeneric ? 'generic' : provider;(async () => {try {// The reference-Secret list is best-effort for managed mode: a failure only@@ -98,7 +157,9 @@ export function OAuthInstallForm({// install (referenceSecretIssue can't verify a Secret it can't see) — that// is acceptable fail-closed degradation.const [manifestResult, secretsResult] = await Promise.allSettled([- getOAuthCredentialManifest(provider),+ needManifest+ ? getOAuthCredentialManifest(manifestProvider)+ : Promise.resolve({ provider: manifestProvider, fields: [] as OAuthCredentialField[] }),listMcpSecrets(),])if (cancelled) return@@ -119,7 +180,7 @@ export function OAuthInstallForm({return () => {cancelled = true}- }, [provider])+ }, [provider, isGeneric, genericMode])const derivedId = useMemo(() => deriveOAuthClientIdPreview(serverName), [serverName])const callbackBase = oauthCallbackBaseUrl()@@ -131,7 +192,10 @@ export function OAuthInstallForm({const nameValid = isValidK8sName(serverName)const scopes = useMemo(() => parseScopesInput(scopesText), [scopesText])- const scopesOk = scopesAreSatisfied(scopes)+ const genericIssues = useMemo(() => genericFormIssues(genericState), [genericState])+ // Baked: at least one scope (GAP-6). Generic: gated on sendScope (DA-4), so `scopesOk`+ // for generic folds into the whole-form check below.+ const scopesOk = isGeneric ? !genericIssues.scopes : scopesAreSatisfied(scopes)const requiredFields = useMemo(() => manifest.filter(field => field.required), [manifest])// A missing/failed manifest yields an empty field list; without this guard@@ -151,22 +215,63 @@ export function OAuthInstallForm({secrets): null- const credentialsComplete = secretMode === 'managed' ? managedComplete : referenceIssue === null-- const canInstall =- callbackConfigured &&- nameValid &&- Boolean(derivedId) &&- credentialsComplete &&- scopesOk &&- !installing+ // A public generic client carries no credentials, so the credential gate is satisfied.+ const credentialsComplete = genericPublic+ ? true+ : secretMode === 'managed'+ ? managedComplete+ : referenceIssue === null++ // Generic endpoints/knobs are ready to advance when no client-side URL/param issue+ // remains (the basic⇒confidential and scope gates are resolved in later steps and+ // folded into `canInstall`).+ const endpointsReady =+ !genericIssues.authorizationEndpoint &&+ !genericIssues.tokenEndpoint &&+ !genericIssues.refreshEndpoint &&+ !genericIssues.resource &&+ !genericIssues.extraAuthorizeParams++ const canInstall = isGeneric+ ? callbackConfigured &&+ nameValid &&+ Boolean(derivedId) &&+ genericFormOk(genericState) &&+ credentialsComplete &&+ !installing+ : callbackConfigured &&+ nameValid &&+ Boolean(derivedId) &&+ credentialsComplete &&+ scopesOk &&+ !installing+const step0Ready = nameValid && Boolean(derivedId)- const canContinue = step === 0 ? step0Ready : step === 1 ? credentialsComplete : canInstall+ const isLastStep = step === steps.length - 1+ const currentKey = steps[step]++ function stepReadyAt(index: number): boolean {+ switch (steps[index]) {+ case 'Provider':+ return step0Ready+ case 'Endpoints':+ return endpointsReady+ case 'Credentials':+ return credentialsComplete+ default:+ return true+ }+ }++ // Advancing from a step needs that step ready; the last step installs instead.+ const canContinue = isLastStep ? canInstall : stepReadyAt(step)function canSelectStep(target: number) {if (target <= step) return true- if (target === 1) return step0Ready- return step0Ready && credentialsComplete+ for (let i = 0; i < target; i += 1) {+ if (!stepReadyAt(i)) return false+ }+ return true}async function handleCopyRedirectUri() {@@ -177,6 +282,20 @@ export function OAuthInstallForm({})}+ function handleGenericScopesChange(raw: string) {+ setScopesText(raw)+ setGenericState(current => markEdited({ ...current, scopes: parseScopesInput(raw) }, 'scopes'))+ }++ function handleApplyDetected() {+ const current = genericState+ if (!current.detected) return+ const next = applyDiscoveryPrefill(current, current.detected)+ setGenericState(next)+ // Keep the raw scopes buffer in sync when Apply filled the scope list.+ if (next.scopes !== current.scopes) setScopesText(formatScopesForInput(next.scopes))+ }+function buildSecretInput(): OAuthSecretInput {if (secretMode === 'reference') {return {@@ -199,6 +318,19 @@ export function OAuthInstallForm({}}+ function buildOAuthSubmit(): OAuthInstallSubmit {+ if (isGeneric) {+ // A public client sends no secret (its client_id is oauth.id, DA-1).+ const secret = genericPublic ? undefined : buildSecretInput()+ return buildGenericSubmit(genericState, grantScope, secret)+ }+ return {+ scopes,+ grantScope,+ secret: buildSecretInput(),+ }+ }+async function handleInstall() {if (!canInstall || installInFlightRef.current) returninstallInFlightRef.current = true@@ -217,11 +349,7 @@ export function OAuthInstallForm({contextRef,registryEntryName: entry.name,registryEntryVersion: entry.version,- oauth: {- scopes,- grantScope,- secret: buildSecretInput(),- },+ oauth: buildOAuthSubmit(),})// Drop the typed client_secret from component state on success so it is// never held in the DOM after the request that consumed it (S-2).@@ -236,30 +364,32 @@ export function OAuthInstallForm({}}+ const scopesSummary = isGeneric ? genericState.scopes : scopes+return (<><CreateStepFlowariaLabel="Install OAuth connector steps"- className="cu-create-step-flow--3"+ className={isGeneric ? 'cu-create-step-flow--4' : 'cu-create-step-flow--3'}currentStep={step}onStepChange={setStep}canSelectStep={canSelectStep}- steps={STEP_DETAILS}- stepLabels={STEPS}+ steps={stepDetails}+ stepLabels={steps}titleId="oauth-install-step-title"><formclassName="cu-form-stack cu-agent-form-stack cu-agent-form-stack--wide"onSubmit={event => {event.preventDefault()- if (step < STEPS.length - 1) {- if (canContinue) setStep(current => Math.min(STEPS.length - 1, current + 1))+ if (step < steps.length - 1) {+ if (canContinue) setStep(current => Math.min(steps.length - 1, current + 1))return}void handleInstall()}}>- {step === 0 ? (+ {currentKey === 'Provider' ? (<div className="cu-form-section"><div className="cu-form-section__header"><h3 className="cu-form-section__title">Register the OAuth app</h3>@@ -331,6 +461,17 @@ export function OAuthInstallForm({)}</Field>+ {genericPublic ? (+ // DA-1: a public generic client registers a client_id equal to oauth.id+ // (the derived callback id). Surface it so the operator registers the+ // right public client at the AS.+ <div className="cu-banner cu-banner--info" role="status">+ This is a public client: register a client with client id{' '}+ <code>{derivedId || '—'}</code> at your authorization server. No client secret is+ stored.+ </div>+ ) : null}+{docUrl ? (<p className="cu-field__hint"><a href={docUrl} target="_blank" rel="noreferrer noopener">@@ -341,7 +482,30 @@ export function OAuthInstallForm({</div>) : null}- {step === 1 ? (+ {currentKey === 'Endpoints' ? (+ <GenericEndpointsStep+ state={genericState}+ issues={genericIssues}+ onEditString={(field, value) =>+ setGenericState(current => markEdited({ ...current, [field]: value }, field))+ }+ onEditEnum={(field, value) =>+ setGenericState(current => editEnumKnob(current, field, value))+ }+ onEditBool={(field, value) =>+ setGenericState(current => markEdited({ ...current, [field]: value }, field))+ }+ onExtraParamsChange={rows =>+ setGenericState(current => ({ ...current, extraAuthorizeParams: rows }))+ }+ onDetected={prefill =>+ setGenericState(current => ({ ...current, detected: prefill }))+ }+ onApply={handleApplyDetected}+ />+ ) : null}++ {currentKey === 'Credentials' ? (<div className="cu-form-section"><div className="cu-form-section__header"><h3 className="cu-form-section__title">Client credentials</h3>@@ -350,105 +514,146 @@ export function OAuthInstallForm({</p></div>- <Field- htmlFor="oauth-secret-mode"- label="Secret source"- description="Type the client credentials, or reference an existing Secret by name and keys."- >- <SelectInput- id="oauth-secret-mode"- value={secretMode}- onChange={event => setSecretMode(event.target.value as 'managed' | 'reference')}+ {isGeneric ? (+ <Field+ htmlFor="oauth-generic-client-mode"+ label="Client type"+ description="A public client stores no secret. A confidential client provides a client id and secret.">- <option value="managed">Managed — enter client id and secret</option>- <option value="reference">Reference — use an existing Secret</option>- </SelectInput>- </Field>+ <SelectInput+ id="oauth-generic-client-mode"+ value={genericMode}+ disabled={forcedConfidential}+ onChange={event =>+ setGenericState(current => ({+ ...current,+ clientMode: event.target.value === 'public' ? 'public' : 'confidential',+ }))+ }+ >+ <option value="public">Public — no client secret</option>+ <option value="confidential">Confidential — client id and secret</option>+ </SelectInput>+ </Field>+ ) : null}- {loadError ? (- <div className="cu-banner cu-banner--error" role="alert">- {loadError}+ {forcedConfidential ? (+ <div className="cu-banner cu-banner--info" role="status">+ Basic client authentication needs a client secret, so this connector must use a+ confidential client.</div>) : null}- {secretMode === 'managed'- ? manifest.map(field => (- <Field- key={field.name}- htmlFor={`oauth-cred-${field.name}`}- label={field.label}- description={field.help}- required={field.required}- >- <TextInput- id={`oauth-cred-${field.name}`}- type={field.secret ? 'password' : 'text'}- autoComplete={field.secret ? 'new-password' : 'off'}- value={credValues[field.name] ?? ''}- onChange={event =>- setCredValues(previous => ({- ...previous,- [field.name]: event.target.value,- }))- }- placeholder={field.label}- />- </Field>- ))- : null}-- {secretMode === 'reference' ? (+ {genericPublic ? (+ <div className="cu-banner cu-banner--info" role="status">+ Public client selected — no credentials are stored. The client id is{' '}+ <code>{derivedId || '—'}</code>.+ </div>+ ) : (<><Field- htmlFor="oauth-ref-secret"- label="Existing Secret"- description="An existing Secret in the MCP servers namespace."- required+ htmlFor="oauth-secret-mode"+ label="Secret source"+ description="Type the client credentials, or reference an existing Secret by name and keys."><SelectInput- id="oauth-ref-secret"- value={refSecretName}- onChange={event => setRefSecretName(event.target.value)}+ id="oauth-secret-mode"+ value={secretMode}+ onChange={event =>+ setSecretMode(event.target.value as 'managed' | 'reference')+ }>- <option value="">Select a Secret…</option>- {secrets.map(secret => (- <option key={secret.name} value={secret.name}>- {secret.name}- </option>- ))}+ <option value="managed">Managed — enter client id and secret</option>+ <option value="reference">Reference — use an existing Secret</option></SelectInput></Field>- <Field htmlFor="oauth-ref-id-key" label="Client ID key" required>- <TextInput- id="oauth-ref-id-key"- value={refClientIdKey}- onChange={event => setRefClientIdKey(event.target.value)}- monospace- />- </Field>- <Field htmlFor="oauth-ref-secret-key" label="Client Secret key" required>- <TextInput- id="oauth-ref-secret-key"- value={refClientSecretKey}- onChange={event => setRefClientSecretKey(event.target.value)}- monospace- />- </Field>- {referenceIssue ? (++ {loadError ? (<div className="cu-banner cu-banner--error" role="alert">- {referenceIssue}- </div>- ) : (- <div className="cu-banner cu-banner--info" role="status">- Secret and keys verified.+ {loadError}</div>- )}+ ) : null}++ {secretMode === 'managed'+ ? manifest.map(field => (+ <Field+ key={field.name}+ htmlFor={`oauth-cred-${field.name}`}+ label={field.label}+ description={field.help}+ required={field.required}+ >+ <TextInput+ id={`oauth-cred-${field.name}`}+ type={field.secret ? 'password' : 'text'}+ autoComplete={field.secret ? 'new-password' : 'off'}+ value={credValues[field.name] ?? ''}+ onChange={event =>+ setCredValues(previous => ({+ ...previous,+ [field.name]: event.target.value,+ }))+ }+ placeholder={field.label}+ />+ </Field>+ ))+ : null}++ {secretMode === 'reference' ? (+ <>+ <Field+ htmlFor="oauth-ref-secret"+ label="Existing Secret"+ description="An existing Secret in the MCP servers namespace."+ required+ >+ <SelectInput+ id="oauth-ref-secret"+ value={refSecretName}+ onChange={event => setRefSecretName(event.target.value)}+ >+ <option value="">Select a Secret…</option>+ {secrets.map(secret => (+ <option key={secret.name} value={secret.name}>+ {secret.name}+ </option>+ ))}+ </SelectInput>+ </Field>+ <Field htmlFor="oauth-ref-id-key" label="Client ID key" required>+ <TextInput+ id="oauth-ref-id-key"+ value={refClientIdKey}+ onChange={event => setRefClientIdKey(event.target.value)}+ monospace+ />+ </Field>+ <Field htmlFor="oauth-ref-secret-key" label="Client Secret key" required>+ <TextInput+ id="oauth-ref-secret-key"+ value={refClientSecretKey}+ onChange={event => setRefClientSecretKey(event.target.value)}+ monospace+ />+ </Field>+ {referenceIssue ? (+ <div className="cu-banner cu-banner--error" role="alert">+ {referenceIssue}+ </div>+ ) : (+ <div className="cu-banner cu-banner--info" role="status">+ Secret and keys verified.+ </div>+ )}+ </>+ ) : null}</>- ) : null}+ )}</div>) : null}- {step === 2 ? (+ {currentKey === 'Install' ? (<div className="cu-form-section"><div className="cu-form-section__header"><h3 className="cu-form-section__title">Scopes and install</h3>@@ -478,12 +683,22 @@ export function OAuthInstallForm({label="Scopes"description="One scope per line (or space/comma separated). At least one is required."required- error={!scopesOk ? 'Add at least one OAuth scope for this connector.' : undefined}+ error={+ isGeneric+ ? genericIssues.scopes+ : !scopesOk+ ? 'Add at least one OAuth scope for this connector.'+ : undefined+ }><TextAreaInputid="oauth-scopes"value={scopesText}- onChange={event => setScopesText(event.target.value)}+ onChange={event =>+ isGeneric+ ? handleGenericScopesChange(event.target.value)+ : setScopesText(event.target.value)+ }rows={4}monospaceplaceholder="offline_access"@@ -505,7 +720,7 @@ export function OAuthInstallForm({</div><div className="cu-summary-list__row"><span>Scopes</span>- <strong>{scopes.length > 0 ? scopes.join(', ') : '-'}</strong>+ <strong>{scopesSummary.length > 0 ? scopesSummary.join(', ') : '-'}</strong></div></section>@@ -534,7 +749,7 @@ export function OAuthInstallForm({>{step === 0 ? 'Cancel' : 'Back'}</Button>- {step < STEPS.length - 1 ? (+ {!isLastStep ? (<Button type="submit" variant="primary" size="sm" disabled={loading || !canContinue}>Continue</Button>diff --git a/control-ui/components/OAuthInstallForm/types.ts b/control-ui/components/OAuthInstallForm/types.tsindex 57e00fd6d..c4785b657 100644--- a/control-ui/components/OAuthInstallForm/types.ts+++ b/control-ui/components/OAuthInstallForm/types.ts@@ -1,4 +1,9 @@import type { RegistryEntry } from '@lib/api'+import type {+ GenericDiscoveryPrefill,+ GenericExtraParam,+ GenericFormState,+} from '@lib/oauthGeneric.types'import type { CatalogOAuthBlock } from '@lib/oauthInstall.types'export type OAuthInstallFormProps = {@@ -10,3 +15,30 @@ export type OAuthInstallFormProps = {onInstalled: () => voidonViewConnectors?: () => void}++// Props for the generic-carril Endpoints step (S3-B4). The parent owns the form state;+// this step renders the endpoints/knobs/Detect UI and reports edits back through typed+// callbacks. Editing any field marks it `touched` in the parent so a later Apply never+// overwrites it (invariant 8).+export type GenericEndpointsStepProps = {+ state: GenericFormState+ // Client-side form issues keyed by field (UX only; control-api's 422 is authority).+ issues: Record<string, string>+ onEditString: (+ field: 'authorizationEndpoint' | 'tokenEndpoint' | 'refreshEndpoint' | 'resource',+ value: string+ ) => void+ onEditEnum: (+ field: 'tokenRequestFormat' | 'tokenAuthMethod' | 'scopeSeparator',+ value: string+ ) => void+ onEditBool: (+ field: 'sendScope' | 'usePkce' | 'includeResponseType' | 'supportsRefresh',+ value: boolean+ ) => void+ onExtraParamsChange: (rows: GenericExtraParam[]) => void+ // Store a successful discovery result; the form does NOT change until Apply.+ onDetected: (prefill: GenericDiscoveryPrefill) => void+ // Apply the stored discovery result to the form (explicit operator action).+ onApply: () => void+}diff --git a/control-ui/components/__tests__/OAuthImmutableFields.test.tsx b/control-ui/components/__tests__/OAuthImmutableFields.test.tsxindex 331a0cedb..f223ae0d7 100644--- a/control-ui/components/__tests__/OAuthImmutableFields.test.tsx+++ b/control-ui/components/__tests__/OAuthImmutableFields.test.tsx@@ -44,4 +44,51 @@ describe('OAuthImmutableFields — immutables read-only in edit (D-B7)', () => {expect(screen.getByText(/not available yet/i)).toBeInTheDocument()expect(screen.queryByText(/nothing to rotate/i)).toBeNull()})++ it('renders the generic carril endpoints and knobs read-only (D-B7)', () => {+ render(+ <OAuthImmutableFields+ oauth={{+ id: 'idp-abc',+ provider: 'generic',+ grantScope: 'user',+ generic: {+ authorizationEndpoint: 'https://idp.example.com/authorize',+ tokenEndpoint: 'https://idp.example.com/token',+ refreshEndpoint: '',+ resource: '',+ tokenRequestFormat: 'form',+ tokenAuthMethod: 'basic',+ scopeSeparator: 'space',+ sendScope: true,+ usePkce: true,+ includeResponseType: true,+ supportsRefresh: true,+ clientMode: 'confidential',+ extraAuthorizeParams: [],+ },+ }}+ />+ )+ // The synthetic provider label plus the generic endpoints/knobs are shown…+ expect((screen.getByLabelText('Provider') as HTMLInputElement).value).toBe(+ 'Custom OAuth 2.0 provider'+ )+ const authEndpoint = screen.getByLabelText('Authorization endpoint') as HTMLInputElement+ const authMethod = screen.getByLabelText('Client authentication method') as HTMLInputElement+ const clientType = screen.getByLabelText('Client type') as HTMLInputElement+ expect(authEndpoint.value).toBe('https://idp.example.com/authorize')+ expect(authMethod.value).toBe('basic')+ expect(clientType.value).toBe('Confidential')++ // …and every one is read-only + disabled (a change means delete + recreate).+ for (const input of [authEndpoint, authMethod, clientType]) {+ expect(input).toHaveAttribute('readonly')+ expect(input).toBeDisabled()+ }++ // An empty optional endpoint is not rendered as a field.+ expect(screen.queryByLabelText('Refresh endpoint')).toBeNull()+ expect(screen.queryByLabelText('Resource')).toBeNull()+ })})diff --git a/control-ui/components/__tests__/OAuthInstallForm.test.tsx b/control-ui/components/__tests__/OAuthInstallForm.test.tsxindex be2d09cde..83d4b5fbe 100644--- a/control-ui/components/__tests__/OAuthInstallForm.test.tsx+++ b/control-ui/components/__tests__/OAuthInstallForm.test.tsx@@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { cleanup, fireEvent, render as rtlRender, screen, waitFor } from '@testing-library/react'import * as api from '../../lib/api'import type { CatalogOAuthBlock } from '../../lib/oauthInstall.types'+import { NOTION_GENERIC_PREFILL } from '../../test/fixtures/genericDiscoveryPrefill'import { OAuthInstallForm } from '../OAuthInstallForm'import { ToastProvider } from '../Toast'@@ -19,10 +20,34 @@ const MANIFEST = {],}+// The generic credential manifest fixture is the exact shape control-api's+// GET /admin/oauth/providers/generic/credential-manifest returns (confidential mode) —+// verified against GENERIC_CREDENTIAL_MANIFEST in control-api/src/oauth/providers.ts.+const GENERIC_MANIFEST = {+ provider: 'generic',+ fields: [+ {+ name: 'client_id',+ label: 'Client ID',+ secret: false,+ required: true,+ help: 'Confidential client only.',+ },+ {+ name: 'client_secret',+ label: 'Client Secret',+ secret: true,+ required: true,+ help: 'Confidential client only.',+ },+ ],+}+vi.mock('../../lib/api', () => ({apiSend: vi.fn().mockResolvedValue({}),getOAuthCredentialManifest: vi.fn(),listMcpSecrets: vi.fn(),+ discoverGenericOAuth: vi.fn(),installFromRegistry: vi.fn().mockResolvedValue({ serverName: 'acme', namespace: 'mcp-server' }),}))@@ -283,3 +308,199 @@ describe('OAuthInstallForm — client_secret confidentiality (S-2, UI side)', ()}})})++// ── Generic carril (S3-B4) ───────────────────────────────────────────────────++async function waitForContinueEnabled(): Promise<void> {+ await waitFor(() => expect(screen.getByRole('button', { name: 'Continue' })).not.toBeDisabled())+}++describe('OAuthInstallForm — baked path is byte-identical (F1 guard)', () => {+ it('renders the 3-step baked wizard with no generic-only markers', async () => {+ const { container } = renderForm({ provider: 'google', grantScope: 'user', scopes: ['a.read'] })+ await waitForContinueEnabled()++ // Baked keeps the 3-step rail and never shows an Endpoints step or generic controls.+ expect(container.querySelector('.cu-create-step-flow--3')).not.toBeNull()+ expect(container.querySelector('.cu-create-step-flow--4')).toBeNull()+ expect(screen.queryByText('Endpoints')).toBeNull()+ expect(screen.queryByText('Authorization server endpoints')).toBeNull()+ expect(container.firstChild).toMatchSnapshot()+ })+})++describe('OAuthInstallForm — generic public install (S3-B4, DA-1)', () => {+ it('submits body.oauth.generic with no secret and the derived client_id note', async () => {+ renderForm({+ provider: 'generic',+ grantScope: 'user',+ scopes: ['openid'],+ genericConfig: {+ authorizationEndpoint: 'https://idp.example.com/authorize',+ tokenEndpoint: 'https://idp.example.com/token',+ },+ })+ await waitForContinueEnabled()++ // A public generic client surfaces the client_id to register (DA-1).+ expect(screen.getByText(/register a client with client id/i)).toBeInTheDocument()++ // Provider → Endpoints → Credentials → Install (4 steps).+ fireEvent.click(screen.getByRole('button', { name: 'Continue' })) // → Endpoints+ expect(screen.getByText('Authorization server endpoints')).toBeInTheDocument()+ fireEvent.click(screen.getByRole('button', { name: 'Continue' })) // → Credentials+ // Public client: no credential fields, and the manifest is never fetched.+ expect(api.getOAuthCredentialManifest).not.toHaveBeenCalled()+ expect(screen.getByText(/Public client selected/i)).toBeInTheDocument()+ fireEvent.click(screen.getByRole('button', { name: 'Continue' })) // → Install++ fireEvent.click(screen.getByRole('button', { name: 'Install connector' }))+ await waitFor(() => expect(api.installFromRegistry).toHaveBeenCalledTimes(1))++ const req = vi.mocked(api.installFromRegistry).mock.calls[0][0]+ expect(req.oauth?.secret).toBeUndefined()+ expect(req.oauth?.scopes).toEqual(['openid'])+ expect(req.oauth?.grantScope).toBe('user')+ expect(req.oauth?.generic).toMatchObject({+ authorizationEndpoint: 'https://idp.example.com/authorize',+ tokenEndpoint: 'https://idp.example.com/token',+ tokenAuthMethod: 'body',+ usePkce: true,+ sendScope: true,+ })+ // Never carries a provider or oauth.id (control-api derives it).+ expect(req.oauth).not.toHaveProperty('id')+ expect(req.oauth?.generic).not.toHaveProperty('provider')+ })+})++describe('OAuthInstallForm — generic confidential/basic (S-2, forced confidential)', () => {+ it('forces confidential for basic auth and keeps the client_secret out of the DOM after submit', async () => {+ vi.mocked(api.getOAuthCredentialManifest).mockResolvedValue(GENERIC_MANIFEST)+ const SECRET = 'generic-secret-99'+ renderForm({+ provider: 'generic',+ grantScope: 'context',+ scopes: ['openid'],+ genericConfig: {+ authorizationEndpoint: 'https://idp.example.com/authorize',+ tokenEndpoint: 'https://idp.example.com/token',+ tokenAuthMethod: 'basic',+ },+ })+ await waitForContinueEnabled()++ fireEvent.click(screen.getByRole('button', { name: 'Continue' })) // → Endpoints+ fireEvent.click(screen.getByRole('button', { name: 'Continue' })) // → Credentials++ // Basic auth forces a confidential client: the client-type select is disabled.+ const clientType = screen.getByLabelText('Client type') as HTMLSelectElement+ expect(clientType.value).toBe('confidential')+ expect(clientType).toBeDisabled()+ expect(api.getOAuthCredentialManifest).toHaveBeenCalledWith('generic')++ fireEvent.change(screen.getByLabelText('Client ID', { exact: false }), {+ target: { value: 'cid' },+ })+ fireEvent.change(screen.getByLabelText('Client Secret', { exact: false }), {+ target: { value: SECRET },+ })+ fireEvent.click(screen.getByRole('button', { name: 'Continue' })) // → Install+ fireEvent.click(screen.getByRole('button', { name: 'Install connector' }))++ await waitFor(() => expect(api.installFromRegistry).toHaveBeenCalledTimes(1))+ const req = vi.mocked(api.installFromRegistry).mock.calls[0][0]+ expect(req.oauth?.secret).toMatchObject({ mode: 'managed', clientSecret: SECRET })+ expect(req.oauth?.generic?.tokenAuthMethod).toBe('basic')++ // S-2: the secret is gone from the DOM after the success view renders.+ await screen.findByRole('heading', { name: 'OAuth connector installed' })+ expect(screen.queryByDisplayValue(SECRET)).toBeNull()+ expect(document.body.textContent).not.toContain(SECRET)+ })+})++describe('OAuthInstallForm — manually selecting Basic auth forces confidential and stays submittable', () => {+ it('does not deadlock the install when Basic is chosen on a public/body-seeded form', async () => {+ // Regression: selecting Basic disables the client-type toggle (forced confidential);+ // if clientMode stayed 'public' the form would validate forever-false with the only+ // fix control disabled. editEnumKnob upholds basic⇒confidential so the flow proceeds.+ vi.mocked(api.getOAuthCredentialManifest).mockResolvedValue(GENERIC_MANIFEST)+ renderForm({+ provider: 'generic',+ grantScope: 'user',+ scopes: ['openid'],+ genericConfig: {+ authorizationEndpoint: 'https://idp.example.com/authorize',+ tokenEndpoint: 'https://idp.example.com/token',+ },+ })+ await waitForContinueEnabled()++ fireEvent.click(screen.getByRole('button', { name: 'Continue' })) // → Endpoints+ // Manually pick Basic auth (the form was seeded public/body). This flips the client+ // to confidential and triggers the generic manifest load, so wait for it to settle.+ fireEvent.change(screen.getByLabelText('Client authentication method', { exact: false }), {+ target: { value: 'basic' },+ })+ await waitForContinueEnabled()+ fireEvent.click(screen.getByRole('button', { name: 'Continue' })) // → Credentials++ // The client type is forced confidential and its toggle is disabled…+ const clientType = (await screen.findByLabelText('Client type')) as HTMLSelectElement+ expect(clientType.value).toBe('confidential')+ expect(clientType).toBeDisabled()++ // …and entering the confidential credentials makes Install reachable (not deadlocked).+ fireEvent.change(await screen.findByLabelText('Client ID', { exact: false }), {+ target: { value: 'cid' },+ })+ fireEvent.change(screen.getByLabelText('Client Secret', { exact: false }), {+ target: { value: 'sh' },+ })+ fireEvent.click(screen.getByRole('button', { name: 'Continue' })) // → Install+ expect(screen.getByRole('button', { name: 'Install connector' })).not.toBeDisabled()+ })+})++describe('OAuthInstallForm — generic Detect never auto-applies (invariant 8)', () => {+ it('leaves the form unchanged after Detect and keeps an edited field on Apply', async () => {+ vi.mocked(api.discoverGenericOAuth).mockResolvedValue(NOTION_GENERIC_PREFILL)+ renderForm({ provider: 'generic', grantScope: 'user', scopes: [] })+ await waitForContinueEnabled()++ fireEvent.click(screen.getByRole('button', { name: 'Continue' })) // → Endpoints++ const authInput = screen.getByLabelText('Authorization endpoint', {+ exact: false,+ }) as HTMLInputElement+ const tokenInput = screen.getByLabelText('Token endpoint', { exact: false }) as HTMLInputElement+ expect(authInput.value).toBe('')++ // Detect stores a result…+ fireEvent.change(screen.getByLabelText('Issuer or discovery URL'), {+ target: { value: 'https://mcp.notion.com' },+ })+ fireEvent.click(screen.getByRole('button', { name: 'Detect' }))+ await waitFor(() =>+ expect(screen.getByRole('button', { name: /Apply detected values/i })).toBeInTheDocument()+ )+ // …but the form has NOT changed (invariant 8).+ expect(authInput.value).toBe('')+ expect(tokenInput.value).toBe('')++ // The operator edits the authorization endpoint (marks it touched)…+ fireEvent.change(authInput, { target: { value: 'https://manual.example.com/authorize' } })+ // …then applies the detected values.+ fireEvent.click(screen.getByRole('button', { name: /Apply detected values/i }))++ // Manual wins: the edited field is kept; the un-edited token endpoint takes the+ // detected value (T4: assert the input values, not internal state).+ expect(+ (screen.getByLabelText('Authorization endpoint', { exact: false }) as HTMLInputElement).value+ ).toBe('https://manual.example.com/authorize')+ expect(+ (screen.getByLabelText('Token endpoint', { exact: false }) as HTMLInputElement).value+ ).toBe('https://mcp.notion.com/token')+ })+})diff --git a/control-ui/components/__tests__/__snapshots__/OAuthInstallForm.test.tsx.snap b/control-ui/components/__tests__/__snapshots__/OAuthInstallForm.test.tsx.snapnew file mode 100644index 000000000..33a5fee1b--- /dev/null+++ b/control-ui/components/__tests__/__snapshots__/OAuthInstallForm.test.tsx.snap@@ -0,0 +1,258 @@+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html++exports[`OAuthInstallForm — baked path is byte-identical (F1 guard) > renders the 3-step baked wizard with no generic-only markers 1`] = `+<div+ class="cu-agent-create-wizard cu-create-step-flow--3"+>+ <aside+ aria-label="Install OAuth connector steps"+ class="cu-agent-step-rail"+ >+ <button+ class="cu-agent-step-rail__item"+ data-state="current"+ type="button"+ >+ <span+ class="cu-agent-step-rail__number"+ >+ 1+ </span>+ <span+ class="cu-agent-step-rail__copy"+ >+ <span+ class="cu-agent-step-rail__title"+ >+ Provider+ </span>+ <span+ class="cu-agent-step-rail__description"+ >+ Register the redirect URI+ </span>+ </span>+ </button>+ <button+ class="cu-agent-step-rail__item"+ data-state="upcoming"+ type="button"+ >+ <span+ class="cu-agent-step-rail__number"+ >+ 2+ </span>+ <span+ class="cu-agent-step-rail__copy"+ >+ <span+ class="cu-agent-step-rail__title"+ >+ Credentials+ </span>+ <span+ class="cu-agent-step-rail__description"+ >+ Add client credentials+ </span>+ </span>+ </button>+ <button+ class="cu-agent-step-rail__item"+ data-state="upcoming"+ disabled=""+ type="button"+ >+ <span+ class="cu-agent-step-rail__number"+ >+ 3+ </span>+ <span+ class="cu-agent-step-rail__copy"+ >+ <span+ class="cu-agent-step-rail__title"+ >+ Install+ </span>+ <span+ class="cu-agent-step-rail__description"+ >+ Scopes and install+ </span>+ </span>+ </button>+ </aside>+ <section+ aria-labelledby="oauth-install-step-title"+ class="cu-agent-step-panel"+ >+ <div+ class="cu-agent-step-panel__header"+ >+ <h3+ class="cu-agent-step-panel__title"+ id="oauth-install-step-title"+ >+ Provider setup+ </h3>+ <p+ class="cu-agent-step-panel__subtitle"+ >+ Register this redirect URI in the provider’s OAuth app before you continue.+ </p>+ </div>+ <div+ class="cu-agent-step-panel__body"+ >+ <form+ class="cu-form-stack cu-agent-form-stack cu-agent-form-stack--wide"+ >+ <div+ class="cu-form-section"+ >+ <div+ class="cu-form-section__header"+ >+ <h3+ class="cu-form-section__title"+ >+ Register the OAuth app+ </h3>+ <p+ class="cu-form-section__description"+ >+ Create an OAuth app for+ <strong>+ </strong>+ and register the exact redirect URI below. control-api derives the callback id from the connector name.+ </p>+ </div>+ <div+ class="cu-field"+ >+ <label+ for="oauth-server-name"+ >+ Connector name+ </label>+ <input+ class="cu-input"+ id="oauth-server-name"+ placeholder="my-oauth-connector"+ value="acme"+ />+ <span+ class="cu-field__hint"+ >+ Used to derive the OAuth callback id. Lowercase letters, digits, and hyphens.+ </span>+ </div>+ <div+ class="cu-field"+ >+ <label+ for="oauth-derived-id"+ >+ Callback id (auto-derived)+ </label>+ <input+ class="cu-input cu-input--monospace"+ id="oauth-derived-id"+ readonly=""+ value="acme"+ />+ <span+ class="cu-field__hint"+ >+ control-api owns this id and checks it is unique; it cannot be typed.+ </span>+ </div>+ <div+ class="cu-field"+ >+ <label>+ Redirect URI+ </label>+ <div+ class="cu-table-actions"+ >+ <input+ aria-label="Redirect URI"+ class="cu-input cu-input--monospace"+ readonly=""+ value="https://oauth.example.com/api/v1/oauth-callback/acme"+ />+ <button+ aria-label="Copy redirect URI"+ class="cu-btn cu-btn--ghost cu-btn--sm cu-btn--icon"+ type="button"+ >+ <svg+ aria-hidden="true"+ fill="none"+ height="16"+ stroke="currentColor"+ stroke-linecap="round"+ stroke-linejoin="round"+ stroke-width="2"+ viewBox="0 0 24 24"+ width="16"+ >+ <rect+ height="14"+ rx="2"+ ry="2"+ width="14"+ x="8"+ y="8"+ />+ <path+ d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"+ />+ </svg>+ </button>+ </div>+ <span+ class="cu-field__hint"+ >+ Register this exact URI in the provider’s OAuth app.+ </span>+ </div>+ <p+ class="cu-field__hint"+ >+ <a+ href="https://console.cloud.google.com/apis/credentials"+ rel="noreferrer noopener"+ target="_blank"+ >+ OAuth app documentation+ </a>+ </p>+ </div>+ <div+ class="cu-create-actions"+ >+ <button+ class="cu-btn cu-btn--ghost cu-btn--sm"+ type="button"+ >+ Cancel+ </button>+ <button+ class="cu-btn cu-btn--primary cu-btn--sm"+ type="submit"+ >+ Continue+ </button>+ </div>+ </form>+ </div>+ </section>+</div>+`;diff --git a/control-ui/lib/__tests__/oauthGeneric.test.ts b/control-ui/lib/__tests__/oauthGeneric.test.tsnew file mode 100644index 000000000..006872d0a--- /dev/null+++ b/control-ui/lib/__tests__/oauthGeneric.test.ts@@ -0,0 +1,477 @@+import { describe, expect, it } from 'vitest'+import fc from 'fast-check'+import {+ CANVA_GENERIC_PREFILL,+ NOTION_BASIC_GENERIC_PREFILL,+ NOTION_GENERIC_PREFILL,+ NOTION_NO_S256_GENERIC_PREFILL,+} from '../../test/fixtures/genericDiscoveryPrefill'+import {+ GENERIC_WIZARD_DEFAULTS,+ applyDiscoveryPrefill,+ buildGenericSubmit,+ editEnumKnob,+ effectiveClientMode,+ extraParamsToRecord,+ genericFormIssues,+ genericFormOk,+ markEdited,+ readGenericImmutables,+ seedFromCatalog,+} from '../oauthGeneric'+import type {+ GenericConfigSuggestion,+ GenericDiscoveryPrefill,+ GenericFormState,+ GenericTouchKey,+} from '../oauthGeneric.types'++const KNOB_KEYS: GenericTouchKey[] = [+ 'authorizationEndpoint',+ 'tokenEndpoint',+ 'refreshEndpoint',+ 'resource',+ 'tokenRequestFormat',+ 'tokenAuthMethod',+ 'scopeSeparator',+ 'sendScope',+ 'usePkce',+ 'includeResponseType',+ 'supportsRefresh',+]++// ─── seedFromCatalog ────────────────────────────────────────────────────────++const suggestionArb: fc.Arbitrary<GenericConfigSuggestion> = fc.record(+ {+ authorizationEndpoint: fc.webUrl(),+ tokenEndpoint: fc.webUrl(),+ refreshEndpoint: fc.webUrl(),+ resource: fc.webUrl(),+ tokenRequestFormat: fc.constantFrom('form', 'json') as fc.Arbitrary<'form' | 'json'>,+ tokenAuthMethod: fc.constantFrom('body', 'basic') as fc.Arbitrary<'body' | 'basic'>,+ scopeSeparator: fc.constantFrom('space', 'comma') as fc.Arbitrary<'space' | 'comma'>,+ sendScope: fc.boolean(),+ usePkce: fc.boolean(),+ includeResponseType: fc.boolean(),+ supportsRefresh: fc.boolean(),+ },+ { requiredKeys: [] }+)++describe('seedFromCatalog (T2)', () => {+ it('always yields all 11 knobs defined, each value ∈ {suggested, default}', () => {+ fc.assert(+ fc.property(suggestionArb, suggestion => {+ const state = seedFromCatalog(GENERIC_WIZARD_DEFAULTS, suggestion)+ for (const key of KNOB_KEYS) {+ expect(state[key as keyof GenericFormState]).toBeDefined()+ }+ // Each enum/bool knob equals either the suggestion (when present) or the default.+ for (const key of ['tokenRequestFormat', 'tokenAuthMethod', 'scopeSeparator'] as const) {+ const expected = suggestion[key] ?? GENERIC_WIZARD_DEFAULTS[key]+ expect(state[key]).toBe(expected)+ }+ for (const key of [+ 'sendScope',+ 'usePkce',+ 'includeResponseType',+ 'supportsRefresh',+ ] as const) {+ const expected =+ typeof suggestion[key] === 'boolean' ? suggestion[key] : GENERIC_WIZARD_DEFAULTS[key]+ expect(state[key]).toBe(expected)+ }+ // A missing suggested endpoint falls back to the empty string, never undefined.+ for (const key of [+ 'authorizationEndpoint',+ 'tokenEndpoint',+ 'refreshEndpoint',+ 'resource',+ ] as const) {+ expect(typeof state[key]).toBe('string')+ }+ })+ )+ })++ it('defaults with no suggestion carry the D-A1 wizard defaults and a public client', () => {+ const state = seedFromCatalog(GENERIC_WIZARD_DEFAULTS)+ expect(state.tokenRequestFormat).toBe('form')+ expect(state.tokenAuthMethod).toBe('body')+ expect(state.scopeSeparator).toBe('space')+ expect(state.sendScope).toBe(true)+ expect(state.usePkce).toBe(true)+ expect(state.includeResponseType).toBe(true)+ expect(state.supportsRefresh).toBe(true)+ expect(state.clientMode).toBe('public')+ expect(state.touched.size).toBe(0)+ })++ it('a catalog that pins basic auth seeds a confidential client', () => {+ const state = seedFromCatalog(GENERIC_WIZARD_DEFAULTS, { tokenAuthMethod: 'basic' })+ expect(state.tokenAuthMethod).toBe('basic')+ expect(state.clientMode).toBe('confidential')+ })++ it('seeds scopes from the catalog scope list and marks their origin', () => {+ const state = seedFromCatalog(GENERIC_WIZARD_DEFAULTS, undefined, ['a', 'b'])+ expect(state.scopes).toEqual(['a', 'b'])+ expect(state.origin.scopes).toBe('catalog')+ })+})++// ─── applyDiscoveryPrefill ──────────────────────────────────────────────────++function baseState(overrides: Partial<GenericFormState> = {}): GenericFormState {+ return { ...seedFromCatalog(GENERIC_WIZARD_DEFAULTS), ...overrides }+}++const prefillArb: fc.Arbitrary<GenericDiscoveryPrefill> = fc.record({+ issuer: fc.webUrl(),+ endpoints: fc.record({ authorization: fc.webUrl(), token: fc.webUrl() }),+ resource: fc.option(fc.webUrl(), { nil: undefined }),+ scopesSupported: fc.array(fc.string({ minLength: 1 })),+ capabilities: fc.record({+ codeChallengeMethods: fc.array(fc.constantFrom('plain', 'S256')),+ tokenEndpointAuthMethods: fc.array(+ fc.constantFrom('client_secret_basic', 'client_secret_post', 'none')+ ),+ grantTypes: fc.array(fc.constantFrom('authorization_code', 'refresh_token')),+ }),+ suggested: fc.record({+ usePkce: fc.boolean(),+ tokenAuthMethod: fc.constantFrom('body', 'basic') as fc.Arbitrary<'body' | 'basic'>,+ supportsRefresh: fc.boolean(),+ }),+})++const touchedArb: fc.Arbitrary<ReadonlySet<GenericTouchKey>> = fc+ .subarray([...KNOB_KEYS, 'scopes'] as GenericTouchKey[])+ .map(keys => new Set(keys))++describe('applyDiscoveryPrefill (T2)', () => {+ it('is idempotent: apply(apply(s,d),d) ≡ apply(s,d)', () => {+ fc.assert(+ fc.property(prefillArb, touchedArb, (prefill, touched) => {+ const state = baseState({ touched, scopes: [] })+ const once = applyDiscoveryPrefill(state, prefill)+ const twice = applyDiscoveryPrefill(once, prefill)+ expect(twice).toEqual(once)+ })+ )+ })++ it('manual wins: an edited (touched) field is never overwritten', () => {+ fc.assert(+ fc.property(prefillArb, touchedArb, (prefill, touched) => {+ const state = baseState({+ touched,+ authorizationEndpoint: 'https://manual.example.com/authorize',+ tokenEndpoint: 'https://manual.example.com/token',+ tokenAuthMethod: 'body',+ usePkce: false,+ supportsRefresh: false,+ scopes: touched.has('scopes') ? ['kept'] : [],+ })+ const next = applyDiscoveryPrefill(state, prefill)+ for (const key of touched) {+ expect(next[key as keyof GenericFormState]).toEqual(state[key as keyof GenericFormState])+ }+ })+ )+ })++ it('no datum never overwrites: an empty capability leaves its field unchanged', () => {+ fc.assert(+ fc.property(prefillArb, prefill => {+ const state = baseState({ scopes: [] })+ const next = applyDiscoveryPrefill(state, prefill)+ if (prefill.capabilities.codeChallengeMethods.length === 0) {+ expect(next.usePkce).toBe(state.usePkce)+ }+ if (prefill.capabilities.tokenEndpointAuthMethods.length === 0) {+ expect(next.tokenAuthMethod).toBe(state.tokenAuthMethod)+ }+ if (prefill.capabilities.grantTypes.length === 0) {+ expect(next.supportsRefresh).toBe(state.supportsRefresh)+ }+ if (prefill.resource === undefined) {+ expect(next.resource).toBe(state.resource)+ }+ })+ )+ })++ it('scopes fill only when the current list is empty', () => {+ fc.assert(+ fc.property(+ prefillArb,+ fc.array(fc.string({ minLength: 1 }), { minLength: 1 }),+ (prefill, existing) => {+ const nonEmpty = applyDiscoveryPrefill(baseState({ scopes: existing }), prefill)+ expect(nonEmpty.scopes).toEqual(existing) // never overwrites a non-empty list++ const empty = applyDiscoveryPrefill(baseState({ scopes: [] }), prefill)+ if (prefill.scopesSupported.length > 0) {+ expect(empty.scopes).toEqual(prefill.scopesSupported)+ } else {+ expect(empty.scopes).toEqual([])+ }+ }+ )+ )+ })++ it('applies the detected endpoints and suggestions from a real pilot prefill', () => {+ const next = applyDiscoveryPrefill(baseState({ scopes: [] }), NOTION_GENERIC_PREFILL)+ expect(next.authorizationEndpoint).toBe('https://mcp.notion.com/authorize')+ expect(next.tokenEndpoint).toBe('https://mcp.notion.com/token')+ expect(next.resource).toBe('https://mcp.notion.com')+ expect(next.scopes).toEqual(['default'])+ expect(next.usePkce).toBe(true)+ expect(next.origin.authorizationEndpoint).toBe('detected')+ })++ it('flips a default when the AS advertises it: usePkce:false from a no-S256 AS', () => {+ const next = applyDiscoveryPrefill(baseState({ scopes: [] }), NOTION_NO_S256_GENERIC_PREFILL)+ expect(next.usePkce).toBe(false)+ expect(next.origin.usePkce).toBe('detected')+ })++ it('basic auth suggestion forces a confidential client', () => {+ const next = applyDiscoveryPrefill(+ baseState({ scopes: [], clientMode: 'public' }),+ NOTION_BASIC_GENERIC_PREFILL+ )+ expect(next.tokenAuthMethod).toBe('basic')+ expect(effectiveClientMode(next)).toBe('confidential')+ })++ it('storing a detected result changes no form field — only Apply does (invariant 8)', () => {+ const seeded = baseState({ scopes: [] })+ const withDetected = { ...seeded, detected: CANVA_GENERIC_PREFILL }+ // Every field except `detected` is identical: Detect stores, it never applies.+ expect({ ...withDetected, detected: null }).toEqual(seeded)+ })+})++// ─── genericFormIssues ──────────────────────────────────────────────────────++describe('genericFormIssues', () => {+ const valid = (): GenericFormState =>+ baseState({+ authorizationEndpoint: 'https://idp.example.com/authorize',+ tokenEndpoint: 'https://idp.example.com/token',+ scopes: ['openid'],+ })++ it('accepts a complete, valid form', () => {+ expect(genericFormOk(valid())).toBe(true)+ })++ it('requires the authorization and token endpoints', () => {+ const issues = genericFormIssues(baseState({ scopes: ['openid'] }))+ expect(issues.authorizationEndpoint).toBeTruthy()+ expect(issues.tokenEndpoint).toBeTruthy()+ })++ it('rejects a non-https endpoint', () => {+ const issues = genericFormIssues(valid())+ expect(issues.authorizationEndpoint).toBeUndefined()+ const bad = genericFormIssues({+ ...valid(),+ authorizationEndpoint: 'http://idp.example.com/authorize',+ })+ expect(bad.authorizationEndpoint).toMatch(/https/)+ })++ it('rejects a bare hostname without a dot', () => {+ const bad = genericFormIssues({ ...valid(), tokenEndpoint: 'https://localhost/token' })+ expect(bad.tokenEndpoint).toMatch(/fully-qualified/)+ })++ it('DA-4: sendScope with no scopes is an issue; turning sendScope off clears it', () => {+ const noScopes = { ...valid(), scopes: [] }+ expect(genericFormIssues(noScopes).scopes).toBeTruthy()+ expect(genericFormIssues({ ...noScopes, sendScope: false }).scopes).toBeUndefined()+ })++ it('basic auth on a public client is an issue', () => {+ const issues = genericFormIssues({ ...valid(), tokenAuthMethod: 'basic', clientMode: 'public' })+ expect(issues.tokenAuthMethod).toBeTruthy()+ expect(+ genericFormIssues({ ...valid(), tokenAuthMethod: 'basic', clientMode: 'confidential' })+ .tokenAuthMethod+ ).toBeUndefined()+ })++ it('bounds the extra authorize params (≤16, value ≤1024, unique keys)', () => {+ const many = Array.from({ length: 17 }, (_, i) => ({ id: `p${i}`, key: `k${i}`, value: 'v' }))+ expect(+ genericFormIssues({ ...valid(), extraAuthorizeParams: many }).extraAuthorizeParams+ ).toMatch(/16/)+ const dup = [+ { id: 'a', key: 'same', value: '1' },+ { id: 'b', key: 'same', value: '2' },+ ]+ expect(+ genericFormIssues({ ...valid(), extraAuthorizeParams: dup }).extraAuthorizeParams+ ).toMatch(/unique/)+ const longVal = [{ id: 'a', key: 'k', value: 'x'.repeat(1025) }]+ expect(+ genericFormIssues({ ...valid(), extraAuthorizeParams: longVal }).extraAuthorizeParams+ ).toMatch(/1024/)+ })+})++// ─── buildGenericSubmit ─────────────────────────────────────────────────────++describe('buildGenericSubmit', () => {+ it('sends the 10 required knobs explicitly and omits empty optionals; no secret for public', () => {+ const state = baseState({+ authorizationEndpoint: ' https://idp.example.com/authorize ',+ tokenEndpoint: 'https://idp.example.com/token',+ scopes: ['openid', 'offline_access'],+ })+ const submit = buildGenericSubmit(state, 'user')+ expect(submit.secret).toBeUndefined()+ expect(submit.scopes).toEqual(['openid', 'offline_access'])+ expect(submit.grantScope).toBe('user')+ // endpoints trimmed+ expect(submit.generic.authorizationEndpoint).toBe('https://idp.example.com/authorize')+ // required knobs present+ for (const key of [+ 'tokenRequestFormat',+ 'tokenAuthMethod',+ 'scopeSeparator',+ 'sendScope',+ 'usePkce',+ 'includeResponseType',+ 'supportsRefresh',+ ] as const) {+ expect(submit.generic[key]).toBeDefined()+ }+ // empty optionals omitted+ expect(submit.generic).not.toHaveProperty('refreshEndpoint')+ expect(submit.generic).not.toHaveProperty('resource')+ expect(submit.generic).not.toHaveProperty('extraAuthorizeParams')+ // never a provider / remote field+ expect(submit.generic).not.toHaveProperty('provider')+ })++ it('includes optionals when present and attaches a confidential secret', () => {+ const state = baseState({+ authorizationEndpoint: 'https://idp.example.com/authorize',+ tokenEndpoint: 'https://idp.example.com/token',+ refreshEndpoint: 'https://idp.example.com/refresh',+ resource: 'https://api.example.com',+ extraAuthorizeParams: [+ { id: 'a', key: 'audience', value: 'https://api.example.com' },+ { id: 'b', key: '', value: 'dropped' },+ ],+ scopes: ['openid'],+ })+ const submit = buildGenericSubmit(state, 'context', {+ mode: 'managed',+ clientId: 'cid',+ clientSecret: 'shh',+ })+ expect(submit.generic.refreshEndpoint).toBe('https://idp.example.com/refresh')+ expect(submit.generic.resource).toBe('https://api.example.com')+ expect(submit.generic.extraAuthorizeParams).toEqual({ audience: 'https://api.example.com' })+ expect(submit.secret).toEqual({ mode: 'managed', clientId: 'cid', clientSecret: 'shh' })+ })+})++describe('extraParamsToRecord', () => {+ it('drops blank keys and lets a later duplicate key win', () => {+ expect(+ extraParamsToRecord([+ { id: '1', key: ' a ', value: '1' },+ { id: '2', key: '', value: 'skip' },+ { id: '3', key: 'a', value: '2' },+ ])+ ).toEqual({ a: '2' })+ })+})++// ─── readGenericImmutables ──────────────────────────────────────────────────++describe('readGenericImmutables', () => {+ it('projects a confidential generic spec.oauth read-only', () => {+ const view = readGenericImmutables({+ source: 'generic',+ id: 'idp-abc',+ authorizationEndpoint: 'https://idp.example.com/authorize',+ tokenEndpoint: 'https://idp.example.com/token',+ tokenRequestFormat: 'form',+ tokenAuthMethod: 'basic',+ scopeSeparator: 'space',+ sendScope: true,+ usePkce: true,+ includeResponseType: true,+ supportsRefresh: true,+ clientIdRef: { name: 's', key: 'client_id' },+ clientSecretRef: { name: 's', key: 'client_secret' },+ extraAuthorizeParams: { audience: 'https://api.example.com' },+ })+ expect(view.clientMode).toBe('confidential')+ expect(view.authorizationEndpoint).toBe('https://idp.example.com/authorize')+ expect(view.tokenAuthMethod).toBe('basic')+ expect(view.extraAuthorizeParams).toEqual([+ expect.objectContaining({ key: 'audience', value: 'https://api.example.com' }),+ ])+ })++ it('infers a public client from the absence of refs and tolerates missing fields', () => {+ const view = readGenericImmutables({ source: 'generic', id: 'idp' })+ expect(view.clientMode).toBe('public')+ expect(view.authorizationEndpoint).toBe('')+ expect(view.sendScope).toBe(false)+ expect(view.extraAuthorizeParams).toEqual([])+ })+})++describe('markEdited', () => {+ it('marks a field touched and flips its origin to edited', () => {+ const state = markEdited(baseState(), 'authorizationEndpoint')+ expect(state.touched.has('authorizationEndpoint')).toBe(true)+ expect(state.origin.authorizationEndpoint).toBe('edited')+ })+})++describe('editEnumKnob', () => {+ it('sets the knob, marks it touched, and flips origin to edited', () => {+ const state = editEnumKnob(baseState(), 'scopeSeparator', 'comma')+ expect(state.scopeSeparator).toBe('comma')+ expect(state.touched.has('scopeSeparator')).toBe(true)+ expect(state.origin.scopeSeparator).toBe('edited')+ })++ it('selecting basic auth forces a confidential client (basic⇒confidential invariant)', () => {+ // Regression: a public/body form where the operator manually picks basic must not be+ // left with clientMode:'public' — the client-type toggle is then disabled (forced+ // confidential) and the form could never validate. editEnumKnob upholds the same+ // invariant seedFromCatalog and applyDiscoveryPrefill maintain.+ const start = baseState({ clientMode: 'public', tokenAuthMethod: 'body' })+ const next = editEnumKnob(start, 'tokenAuthMethod', 'basic')+ expect(next.tokenAuthMethod).toBe('basic')+ expect(next.clientMode).toBe('confidential')+ expect(+ genericFormIssues({+ ...next,+ authorizationEndpoint: 'https://idp.example.com/authorize',+ tokenEndpoint: 'https://idp.example.com/token',+ scopes: ['openid'],+ }).tokenAuthMethod+ ).toBeUndefined()+ })++ it('switching back to body keeps the (now confidential) client mode', () => {+ const basic = editEnumKnob(baseState({ clientMode: 'public' }), 'tokenAuthMethod', 'basic')+ const body = editEnumKnob(basic, 'tokenAuthMethod', 'body')+ expect(body.tokenAuthMethod).toBe('body')+ expect(body.clientMode).toBe('confidential')+ })+})diff --git a/control-ui/lib/__tests__/oauthInstall.test.ts b/control-ui/lib/__tests__/oauthInstall.test.tsindex 95d2dc92e..fea2da815 100644--- a/control-ui/lib/__tests__/oauthInstall.test.ts+++ b/control-ui/lib/__tests__/oauthInstall.test.ts@@ -83,6 +83,7 @@ describe('getCatalogOAuthBlock', () => {provider: 'google',grantScope: 'context',scopes: ['a.read', 'b.read'],+ // A malformed genericConfig (no recognised knob) is dropped defensively.genericConfig: { endpoints: {} },}))@@ -91,10 +92,36 @@ describe('getCatalogOAuthBlock', () => {grantScope: 'context',scopes: ['a.read', 'b.read'],})- // genericConfig is Slice-3-only and must never leak into Slice-1 state.expect(block).not.toHaveProperty('genericConfig')})+ it('conserves a well-formed generic catalog suggestion (E-19.6)', () => {+ // T3: at b9a846a98 getCatalogOAuthBlock dropped genericConfig entirely, so this+ // assertion fails there. The generic carril needs the catalog suggestion to seed+ // the wizard (the admin confirms, control-api arbitrates — S-4).+ const block = getCatalogOAuthBlock(+ entryWithOAuth({+ provider: 'generic',+ scopes: ['openid'],+ genericConfig: {+ authorizationEndpoint: 'https://idp.example.com/authorize',+ tokenEndpoint: 'https://idp.example.com/token',+ tokenAuthMethod: 'basic',+ usePkce: false,+ // Unknown keys are dropped; a wrong-typed knob is ignored.+ bogus: 'nope',+ sendScope: 'yes-please',+ },+ })+ )+ expect(block?.genericConfig).toEqual({+ authorizationEndpoint: 'https://idp.example.com/authorize',+ tokenEndpoint: 'https://idp.example.com/token',+ tokenAuthMethod: 'basic',+ usePkce: false,+ })+ })+it('returns null when there is no oauth block', () => {expect(getCatalogOAuthBlock(entryWithOAuth(undefined))).toBeNull()expect(getCatalogOAuthBlock({ mcp_server_meta: null } as RegistryEntry)).toBeNull()@@ -198,4 +225,44 @@ describe('extractOAuthImmutables', () => {extractOAuthImmutables({ oauth: { id: 'a', provider: 'slack', grantScope: 'x' } })).toEqual({ id: 'a', provider: 'slack', grantScope: '' })})++ it('surfaces a generic connector (source:generic, no provider) as non-null with knobs', () => {+ // T3: at b9a846a98 extractOAuthImmutables returned null for a generic CR (it required+ // a `provider`), so the edit view showed no immutables. It now returns a synthetic+ // `provider:'generic'` plus the read-only endpoints/knobs (D-B7).+ const result = extractOAuthImmutables({+ oauth: {+ source: 'generic',+ id: 'idp-abc',+ grantScope: 'user',+ authorizationEndpoint: 'https://idp.example.com/authorize',+ tokenEndpoint: 'https://idp.example.com/token',+ tokenRequestFormat: 'form',+ tokenAuthMethod: 'body',+ scopeSeparator: 'space',+ sendScope: true,+ usePkce: true,+ includeResponseType: true,+ supportsRefresh: true,+ },+ })+ expect(result).not.toBeNull()+ expect(result?.provider).toBe('generic')+ expect(result?.id).toBe('idp-abc')+ expect(result?.grantScope).toBe('user')+ expect(result?.generic?.authorizationEndpoint).toBe('https://idp.example.com/authorize')+ expect(result?.generic?.clientMode).toBe('public')+ })++ it('marks a generic connector with client refs as a confidential client', () => {+ const result = extractOAuthImmutables({+ oauth: {+ source: 'generic',+ id: 'idp-abc',+ clientIdRef: { name: 'idp-abc-oauth-client', key: 'client_id' },+ clientSecretRef: { name: 'idp-abc-oauth-client', key: 'client_secret' },+ },+ })+ expect(result?.generic?.clientMode).toBe('confidential')+ })})diff --git a/control-ui/lib/api.ts b/control-ui/lib/api.tsindex 57c856150..bf63a3f6e 100644--- a/control-ui/lib/api.ts+++ b/control-ui/lib/api.ts@@ -1,5 +1,6 @@'use client'+import type { GenericDiscoveryPrefill } from './oauthGeneric.types'import type {McpSecretSummary,OAuthCredentialManifest,@@ -3201,6 +3202,18 @@ export async function getOAuthCredentialManifest() as Promise<OAuthCredentialManifest>}+/**+ * Dry-run generic AS discovery (E-19.5, D-A6). Posts the operator-typed issuer/URL and+ * resolves to the prefill SUGGESTION the wizard offers on Apply. No writes. On failure+ * the thrown Error carries `.code`/`.body` (the `discovery_failed` detail kind or a+ * kernel §4 400 message), mapped to UI copy by `mapRemoteDiscoverError`.+ */+export async function discoverGenericOAuth(url: string): Promise<GenericDiscoveryPrefill> {+ return apiSend('POST', '/api/v1/admin/oauth/discover', {+ url,+ }) as Promise<GenericDiscoveryPrefill>+}+/*** Lists MCP Server Secrets as names + keys only — never values (E-16.1). The OAuth* install wizard's reference mode uses this to verify that a chosen Secret and itsdiff --git a/control-ui/lib/oauthGeneric.ts b/control-ui/lib/oauthGeneric.tsnew file mode 100644index 000000000..9f552ff18--- /dev/null+++ b/control-ui/lib/oauthGeneric.ts@@ -0,0 +1,422 @@+// Pure, testable state machine for the `source:'generic'` install wizard (S3-B4).+// The form state is the single source of truth; each event transforms it with a pure+// function. Nothing auto-applies: discovery/catalog SUGGEST, the operator confirms, and+// control-api arbitrates (S-4). This module owns no network and no React.+import type {+ GenericClientMode,+ GenericConfigSuggestion,+ GenericDiscoveryPrefill,+ GenericExtraParam,+ GenericFieldOrigin,+ GenericFormState,+ GenericImmutableView,+ GenericOAuthInstallSubmit,+ GenericOAuthKnobs,+ GenericTouchKey,+ GenericWizardDefaults,+} from './oauthGeneric.types'+import type { OAuthGrantScope, OAuthSecretInput } from './oauthInstall.types'++// The wizard defaults (§5.1 "Default wizard" column = D-A1 defaults). The server writes+// no defaults (fidelity to a CRD with none); the wizard is the sole default provider.+export const GENERIC_WIZARD_DEFAULTS: GenericWizardDefaults = {+ tokenRequestFormat: 'form',+ tokenAuthMethod: 'body',+ scopeSeparator: 'space',+ sendScope: true,+ usePkce: true,+ includeResponseType: true,+ supportsRefresh: true,+}++// The touch/origin keys, in a fixed order, so origin maps are always fully populated.+const TOUCH_KEYS: readonly GenericTouchKey[] = [+ 'authorizationEndpoint',+ 'tokenEndpoint',+ 'refreshEndpoint',+ 'resource',+ 'tokenRequestFormat',+ 'tokenAuthMethod',+ 'scopeSeparator',+ 'sendScope',+ 'usePkce',+ 'includeResponseType',+ 'supportsRefresh',+ 'scopes',+]++// The subset of fields that generic discovery can inform (§5.1, "fuentes ∋ discovery").+// Apply only ever touches these; every other field is catalog/manual only.+const DISCOVERY_FIELDS: readonly GenericTouchKey[] = [+ 'authorizationEndpoint',+ 'tokenEndpoint',+ 'resource',+ 'tokenAuthMethod',+ 'usePkce',+ 'supportsRefresh',+ 'scopes',+]++let paramCounter = 0++/** Stable, unique id for an extra-param row (non-index React key). */+function newParamId(): string {+ paramCounter += 1+ const rand =+ typeof globalThis.crypto?.randomUUID === 'function'+ ? globalThis.crypto.randomUUID()+ : Math.random().toString(36).slice(2)+ return `gxp-${paramCounter}-${rand}`+}++/** A fresh, empty extra-param row for the editor. */+export function newExtraParamRow(): GenericExtraParam {+ return { id: newParamId(), key: '', value: '' }+}++function extraParamsFromRecord(record: Record<string, string> | undefined): GenericExtraParam[] {+ if (!record) return []+ return Object.entries(record).map(([key, value]) => ({ id: newParamId(), key, value }))+}++/**+ * Fold the extra-param editor rows into the wire record. Rows with a blank key are+ * dropped (a half-typed row is not a param); a later duplicate key wins (last write).+ */+export function extraParamsToRecord(rows: readonly GenericExtraParam[]): Record<string, string> {+ const out: Record<string, string> = {}+ for (const row of rows) {+ const key = row.key.trim()+ if (key) out[key] = row.value+ }+ return out+}++function fullOrigin(value: GenericFieldOrigin): Record<GenericTouchKey, GenericFieldOrigin> {+ const origin = {} as Record<GenericTouchKey, GenericFieldOrigin>+ for (const key of TOUCH_KEYS) origin[key] = value+ return origin+}++/**+ * Mount-time seed (§5.3, "Montaje del wizard"). Each knob ← the catalog suggestion when+ * present and of the right shape, else the wizard default; `origin` records which. The+ * catalog SUGGESTS: an operator can still change anything afterwards. `clientMode` is+ * confidential when the catalog pins `tokenAuthMethod:'basic'` (a Basic client needs a+ * secret), else public (D-A5). `scopes` seed from the catalog's top-level scope list.+ */+export function seedFromCatalog(+ defaults: GenericWizardDefaults,+ suggestion?: GenericConfigSuggestion,+ catalogScopes?: readonly string[]+): GenericFormState {+ const s = suggestion ?? {}+ const origin = fullOrigin('default')++ function str(key: 'authorizationEndpoint' | 'tokenEndpoint' | 'refreshEndpoint' | 'resource') {+ const v = s[key]+ if (typeof v === 'string' && v.length > 0) {+ origin[key] = 'catalog'+ return v+ }+ return ''+ }+ function enumField<T extends string>(+ key: 'tokenRequestFormat' | 'tokenAuthMethod' | 'scopeSeparator',+ allowed: readonly T[],+ fallback: T+ ): T {+ const v = s[key]+ if (typeof v === 'string' && (allowed as readonly string[]).includes(v)) {+ origin[key] = 'catalog'+ return v as T+ }+ return fallback+ }+ function bool(key: 'sendScope' | 'usePkce' | 'includeResponseType' | 'supportsRefresh'): boolean {+ const v = s[key]+ if (typeof v === 'boolean') {+ origin[key] = 'catalog'+ return v+ }+ return defaults[key]+ }++ const tokenAuthMethod = enumField(+ 'tokenAuthMethod',+ ['body', 'basic'] as const,+ defaults.tokenAuthMethod+ )+ const scopes = (catalogScopes ?? []).filter(x => typeof x === 'string')+ if (scopes.length > 0) origin.scopes = 'catalog'++ return {+ authorizationEndpoint: str('authorizationEndpoint'),+ tokenEndpoint: str('tokenEndpoint'),+ refreshEndpoint: str('refreshEndpoint'),+ resource: str('resource'),+ tokenRequestFormat: enumField(+ 'tokenRequestFormat',+ ['form', 'json'] as const,+ defaults.tokenRequestFormat+ ),+ tokenAuthMethod,+ scopeSeparator: enumField(+ 'scopeSeparator',+ ['space', 'comma'] as const,+ defaults.scopeSeparator+ ),+ sendScope: bool('sendScope'),+ usePkce: bool('usePkce'),+ includeResponseType: bool('includeResponseType'),+ supportsRefresh: bool('supportsRefresh'),+ extraAuthorizeParams: extraParamsFromRecord(s.extraAuthorizeParams),+ scopes,+ // A Basic client needs a secret, so a catalog that pins basic implies confidential.+ clientMode: tokenAuthMethod === 'basic' ? 'confidential' : 'public',+ detected: null,+ touched: new Set<GenericTouchKey>(),+ origin,+ }+}++/** Record the operator's edit of a field: mark touched, flip origin to 'edited'. */+export function markEdited(state: GenericFormState, field: GenericTouchKey): GenericFormState {+ const touched = new Set(state.touched)+ touched.add(field)+ return { ...state, touched, origin: { ...state.origin, [field]: 'edited' } }+}++/**+ * Edit an enum knob, upholding the basic⇒confidential invariant that `seedFromCatalog`+ * and `applyDiscoveryPrefill` also maintain: selecting HTTP Basic client authentication+ * forces a confidential client (a Basic header needs a client secret). Without this, the+ * client-type toggle renders disabled (forced confidential via `effectiveClientMode`)+ * while `clientMode` stays `'public'`, so the form could never validate and the one+ * control that could fix it is disabled. Marks the edited field touched.+ */+export function editEnumKnob(+ state: GenericFormState,+ field: 'tokenRequestFormat' | 'tokenAuthMethod' | 'scopeSeparator',+ value: string+): GenericFormState {+ const next = markEdited({ ...state, [field]: value } as GenericFormState, field)+ if (field === 'tokenAuthMethod' && value === 'basic') {+ return { ...next, clientMode: 'confidential' }+ }+ return next+}++/**+ * Apply a discovery result (§5.3, "Apply"). Only ever called on an explicit operator+ * click — Detect alone stores `detected` and leaves the form untouched (invariant 8).+ * For each field discovery can inform: value ← detected, UNLESS the operator has already+ * edited it (`touched`) or discovery carries no datum for it ("sin dato nunca+ * sobrescribe"). `scopes` fill only when currently empty. Idempotent by construction:+ * Apply never marks a field touched, and re-applying the same result yields the same+ * values, so `apply(apply(s,d),d) === apply(s,d)`.+ */+export function applyDiscoveryPrefill(+ state: GenericFormState,+ prefill: GenericDiscoveryPrefill+): GenericFormState {+ const next: GenericFormState = { ...state, origin: { ...state.origin } }++ const set = <K extends GenericTouchKey>(field: K, value: GenericFormState[K]) => {+ if (state.touched.has(field)) return // manual wins+ ;(next[field] as GenericFormState[K]) = value+ next.origin[field] = 'detected'+ }++ set('authorizationEndpoint', prefill.endpoints.authorization)+ set('tokenEndpoint', prefill.endpoints.token)++ // "Sin dato nunca sobrescribe": each suggestion is gated on the AS actually having+ // advertised the underlying metadata, read off `capabilities` (the raw arrays).+ if (prefill.resource) set('resource', prefill.resource)+ if (prefill.capabilities.tokenEndpointAuthMethods.length > 0) {+ set('tokenAuthMethod', prefill.suggested.tokenAuthMethod)+ }+ if (prefill.capabilities.codeChallengeMethods.length > 0) {+ set('usePkce', prefill.suggested.usePkce)+ }+ if (prefill.capabilities.grantTypes.length > 0) {+ set('supportsRefresh', prefill.suggested.supportsRefresh)+ }++ // Scopes fill only when empty AND not operator-edited: an operator-typed or+ // catalog-seeded list is kept, and an explicitly cleared list is respected (§5.3,+ // "nunca sobre edited").+ if (+ !state.touched.has('scopes') &&+ state.scopes.length === 0 &&+ prefill.scopesSupported.length > 0+ ) {+ next.scopes = [...prefill.scopesSupported]+ next.origin.scopes = 'detected'+ }++ // `tokenAuthMethod` may have moved to 'basic'; a Basic client must be confidential.+ if (next.tokenAuthMethod === 'basic') next.clientMode = 'confidential'++ return next+}++const HAS_SPACE = /\s/++function urlIssue(raw: string, label: string): string | undefined {+ const value = raw.trim()+ if (HAS_SPACE.test(value)) return `${label} must not contain spaces.`+ let parsed: URL+ try {+ parsed = new URL(value)+ } catch {+ return `${label} must be an absolute https URL.`+ }+ if (parsed.protocol !== 'https:') return `${label} must use https.`+ if (!parsed.hostname.includes('.')) return `${label} must have a fully-qualified hostname.`+ return undefined+}++/**+ * Client-side FORM validation for the generic wizard (UX only — the 422 from control-api+ * is the authority). Returns a `field → message` map keyed by wizard field ids. Covers:+ * required/absolute-https endpoints, optional refresh/resource URLs, `basic ⇒+ * confidential`, `sendScope ⇒ ≥1 scope` (DA-4/GAP-6), and the extra-param bounds.+ */+export function genericFormIssues(state: GenericFormState): Record<string, string> {+ const issues: Record<string, string> = {}++ const authIssue = state.authorizationEndpoint.trim()+ ? urlIssue(state.authorizationEndpoint, 'Authorization endpoint')+ : 'Authorization endpoint is required.'+ if (authIssue) issues.authorizationEndpoint = authIssue++ const tokenIssue = state.tokenEndpoint.trim()+ ? urlIssue(state.tokenEndpoint, 'Token endpoint')+ : 'Token endpoint is required.'+ if (tokenIssue) issues.tokenEndpoint = tokenIssue++ if (state.refreshEndpoint.trim()) {+ const issue = urlIssue(state.refreshEndpoint, 'Refresh endpoint')+ if (issue) issues.refreshEndpoint = issue+ }+ if (state.resource.trim()) {+ const issue = urlIssue(state.resource, 'Resource')+ if (issue) issues.resource = issue+ }++ if (state.tokenAuthMethod === 'basic' && state.clientMode !== 'confidential') {+ issues.tokenAuthMethod =+ 'Basic client authentication requires a confidential client with a client secret.'+ }++ if (state.sendScope && state.scopes.length === 0) {+ issues.scopes = 'Add at least one scope, or turn off “Send scope” to authorize without one.'+ }++ const rows = state.extraAuthorizeParams+ const nonEmpty = rows.filter(r => r.key.trim())+ if (nonEmpty.length > 16) {+ issues.extraAuthorizeParams = 'At most 16 extra authorize params are allowed.'+ } else if (nonEmpty.some(r => r.value.length > 1024)) {+ issues.extraAuthorizeParams = 'An extra authorize param value must be 1024 characters or fewer.'+ } else {+ const keys = nonEmpty.map(r => r.key.trim())+ if (new Set(keys).size !== keys.length) {+ issues.extraAuthorizeParams = 'Extra authorize param keys must be unique.'+ }+ }++ return issues+}++/** True when the generic form has no client-side blocking issue. */+export function genericFormOk(state: GenericFormState): boolean {+ return Object.keys(genericFormIssues(state)).length === 0+}++/**+ * Build the `body.oauth` sub-object for a generic install (§5.1 knob→wire). Sends the 10+ * required knobs explicitly plus the optional ones only when present. `secret` is+ * attached only for a confidential client (the caller passes it, or nothing for public).+ */+export function buildGenericSubmit(+ state: GenericFormState,+ grantScope: OAuthGrantScope,+ secret?: OAuthSecretInput+): GenericOAuthInstallSubmit {+ const generic: GenericOAuthKnobs = {+ authorizationEndpoint: state.authorizationEndpoint.trim(),+ tokenEndpoint: state.tokenEndpoint.trim(),+ tokenRequestFormat: state.tokenRequestFormat,+ tokenAuthMethod: state.tokenAuthMethod,+ scopeSeparator: state.scopeSeparator,+ sendScope: state.sendScope,+ usePkce: state.usePkce,+ includeResponseType: state.includeResponseType,+ supportsRefresh: state.supportsRefresh,+ }+ const refresh = state.refreshEndpoint.trim()+ if (refresh) generic.refreshEndpoint = refresh+ const resource = state.resource.trim()+ if (resource) generic.resource = resource+ const extra = extraParamsToRecord(state.extraAuthorizeParams)+ if (Object.keys(extra).length > 0) generic.extraAuthorizeParams = extra++ const submit: GenericOAuthInstallSubmit = {+ scopes: state.scopes,+ grantScope,+ generic,+ }+ if (secret) submit.secret = secret+ return submit+}++function asString(value: unknown): string {+ return typeof value === 'string' ? value : ''+}+function asBool(value: unknown): boolean {+ return value === true+}++/**+ * Read the immutable generic knobs off an installed connector's `spec.oauth` for the+ * read-only edit view (D-B7). `clientMode` is inferred from the presence of the paired+ * client refs (confidential) vs their absence (public, DA-1). Tolerant of a malformed CR+ * (missing/extra fields) — the edit view must never crash on unexpected data (§9 risk 7).+ */+export function readGenericImmutables(oauth: Record<string, unknown>): GenericImmutableView {+ const extraRaw = oauth.extraAuthorizeParams+ const extraAuthorizeParams: GenericExtraParam[] =+ extraRaw && typeof extraRaw === 'object' && !Array.isArray(extraRaw)+ ? Object.entries(extraRaw as Record<string, unknown>).map(([key, value]) => ({+ id: newParamId(),+ key,+ value: asString(value),+ }))+ : []+ const hasSecret =+ (oauth.clientSecretRef !== undefined && oauth.clientSecretRef !== null) ||+ (oauth.clientIdRef !== undefined && oauth.clientIdRef !== null)+ return {+ authorizationEndpoint: asString(oauth.authorizationEndpoint),+ tokenEndpoint: asString(oauth.tokenEndpoint),+ refreshEndpoint: asString(oauth.refreshEndpoint),+ resource: asString(oauth.resource),+ tokenRequestFormat: asString(oauth.tokenRequestFormat),+ tokenAuthMethod: asString(oauth.tokenAuthMethod),+ scopeSeparator: asString(oauth.scopeSeparator),+ sendScope: asBool(oauth.sendScope),+ usePkce: asBool(oauth.usePkce),+ includeResponseType: asBool(oauth.includeResponseType),+ supportsRefresh: asBool(oauth.supportsRefresh),+ clientMode: hasSecret ? 'confidential' : 'public',+ extraAuthorizeParams,+ }+}++/** The effective client mode: `basic` token auth forces confidential regardless of toggle. */+export function effectiveClientMode(state: GenericFormState): GenericClientMode {+ return state.tokenAuthMethod === 'basic' ? 'confidential' : state.clientMode+}diff --git a/control-ui/lib/oauthGeneric.types.ts b/control-ui/lib/oauthGeneric.types.tsnew file mode 100644index 000000000..82aa19548--- /dev/null+++ b/control-ui/lib/oauthGeneric.types.ts@@ -0,0 +1,150 @@+// Wire + form types for the `source:'generic'` install carril (S3-B4 / DEC-28).+// The generic carril is discriminated by `mcp_server_meta.oauth.provider === 'generic'`+// (a string sentinel, never a baked provider) and writes `spec.oauth.source:'generic'`+// with an explicit set of 11 wire knobs — a 1:1 mirror of the control-api install-side+// schema (`GenericOAuthKnobsSchema`) and the CRD generic block. Nothing here is a+// decision module: each knob independently selects one fixed wire behaviour.+import type { OAuthGrantScope, OAuthSecretInput } from './oauthInstall.types'++// The 11 wire knobs sent under `body.oauth.generic`. Mirror of control-api's+// `GenericOAuthKnobs` (src/oauth/genericKnobs.ts). `extraAuthorizeParams` is a plain+// map on the wire; the form models it as an ordered list (see GenericExtraParam).+export type GenericOAuthKnobs = {+ authorizationEndpoint: string+ tokenEndpoint: string+ refreshEndpoint?: string+ resource?: string+ tokenRequestFormat: 'form' | 'json'+ tokenAuthMethod: 'body' | 'basic'+ scopeSeparator: 'space' | 'comma'+ sendScope: boolean+ usePkce: boolean+ includeResponseType: boolean+ supportsRefresh: boolean+ extraAuthorizeParams?: Record<string, string>+}++// A catalog-supplied suggestion (E-19.6): every knob optional — the catalog SUGGESTS,+// the admin confirms, control-api arbitrates (S-4). Mirror of `GenericConfigSuggestion`.+export type GenericConfigSuggestion = Partial<GenericOAuthKnobs>++// Wire returned by POST /admin/oauth/discover (E-19.5, §5.2). Mirror of control-api's+// `GenericDiscoveryPrefill`. `resource` is present only when discovery reached the AS+// through a protected-resource-metadata document. `capabilities` are the raw AS+// advertisements (shown in the "Detected" panel); `suggested` are the deterministic,+// documented derivations the wizard offers on Apply.+export type GenericDiscoveryPrefill = {+ issuer: string+ endpoints: { authorization: string; token: string }+ resource?: string+ scopesSupported: string[]+ capabilities: {+ codeChallengeMethods: string[]+ tokenEndpointAuthMethods: string[]+ grantTypes: string[]+ }+ suggested: {+ usePkce: boolean+ tokenAuthMethod: 'body' | 'basic'+ supportsRefresh: boolean+ }+}++// The confidential/public client selector. `basic` token auth forces `confidential`+// (a Basic auth header needs a client secret).+export type GenericClientMode = 'public' | 'confidential'++// The provenance of each field's current value, surfaced as a badge so the operator+// can audit where every value came from (S-4: catalog suggests, discovery suggests,+// the admin confirms — the origin stays visible).+export type GenericFieldOrigin = 'default' | 'catalog' | 'detected' | 'edited'++// Fields that participate in touched-tracking + origin badges. `extraAuthorizeParams`+// is excluded: it has no standard discovery metadata and is catalog/manual only.+export type GenericTouchKey =+ | 'authorizationEndpoint'+ | 'tokenEndpoint'+ | 'refreshEndpoint'+ | 'resource'+ | 'tokenRequestFormat'+ | 'tokenAuthMethod'+ | 'scopeSeparator'+ | 'sendScope'+ | 'usePkce'+ | 'includeResponseType'+ | 'supportsRefresh'+ | 'scopes'++// One extra authorize-param row. `id` is a stable key assigned at row creation so the+// list renders with a non-index React key even as rows reorder/remove.+export type GenericExtraParam = {+ id: string+ key: string+ value: string+}++// The full generic wizard state. It is the SINGLE source of truth: every event+// (mount, edit, Apply) transforms it with a pure function; nothing auto-applies (S-4).+export type GenericFormState = {+ authorizationEndpoint: string+ tokenEndpoint: string+ refreshEndpoint: string+ resource: string+ tokenRequestFormat: 'form' | 'json'+ tokenAuthMethod: 'body' | 'basic'+ scopeSeparator: 'space' | 'comma'+ sendScope: boolean+ usePkce: boolean+ includeResponseType: boolean+ supportsRefresh: boolean+ extraAuthorizeParams: GenericExtraParam[]+ scopes: string[]+ clientMode: GenericClientMode+ // Last successful discovery result. Held until the operator clicks Apply; Detect+ // alone never mutates the form (invariant 8).+ detected: GenericDiscoveryPrefill | null+ // Fields the operator has edited — an edited field is never overwritten by Apply.+ touched: ReadonlySet<GenericTouchKey>+ // Where each field's current value came from (badge source).+ origin: Record<GenericTouchKey, GenericFieldOrigin>+}++// The knob defaults the wizard seeds a fresh generic form with (§5.1, "Default wizard"+// column). Endpoints/resource default empty; the booleans/enums carry the D-A1 defaults.+export type GenericWizardDefaults = {+ tokenRequestFormat: 'form' | 'json'+ tokenAuthMethod: 'body' | 'basic'+ scopeSeparator: 'space' | 'comma'+ sendScope: boolean+ usePkce: boolean+ includeResponseType: boolean+ supportsRefresh: boolean+}++// Read-only projection of an installed generic connector's `spec.oauth` for the edit+// view (D-B7). Everything is create-only (GENERIC-IMM / GENERIC-SECRET-IMM): a change+// means delete + recreate.+export type GenericImmutableView = {+ authorizationEndpoint: string+ tokenEndpoint: string+ refreshEndpoint: string+ resource: string+ tokenRequestFormat: string+ tokenAuthMethod: string+ scopeSeparator: string+ sendScope: boolean+ usePkce: boolean+ includeResponseType: boolean+ supportsRefresh: boolean+ clientMode: GenericClientMode+ extraAuthorizeParams: GenericExtraParam[]+}++// The `oauth` sub-object the generic branch attaches to POST /admin/registry/install.+// `secret` is absent for a public client (DA-1); `generic` carries the wire knobs.+export type GenericOAuthInstallSubmit = {+ scopes: string[]+ grantScope: OAuthGrantScope+ secret?: OAuthSecretInput+ generic: GenericOAuthKnobs+}diff --git a/control-ui/lib/oauthInstall.ts b/control-ui/lib/oauthInstall.tsindex 5a01a73e3..984487f5e 100644--- a/control-ui/lib/oauthInstall.ts+++ b/control-ui/lib/oauthInstall.ts@@ -1,4 +1,6 @@import type { RegistryEntry } from './api'+import { readGenericImmutables } from './oauthGeneric'+import type { GenericConfigSuggestion, GenericImmutableView } from './oauthGeneric.types'import type {CatalogOAuthBlock,McpSecretSummary,@@ -22,6 +24,61 @@ export function oauthCallbackBaseUrl(): string {const GRANT_SCOPES: ReadonlySet<string> = new Set<OAuthGrantScope>(['user', 'context'])+const GENERIC_STRING_KNOBS = [+ 'authorizationEndpoint',+ 'tokenEndpoint',+ 'refreshEndpoint',+ 'resource',+] as const+const GENERIC_ENUM_KNOBS: Record<string, readonly string[]> = {+ tokenRequestFormat: ['form', 'json'],+ tokenAuthMethod: ['body', 'basic'],+ scopeSeparator: ['space', 'comma'],+}+const GENERIC_BOOL_KNOBS = [+ 'sendScope',+ 'usePkce',+ 'includeResponseType',+ 'supportsRefresh',+] as const++/**+ * Defensively parse the catalog's `genericConfig` suggestion (E-19.6): keep only known+ * knob keys with the right primitive type; drop anything unexpected. Returns undefined+ * when nothing usable survives, so a malformed suggestion never reaches the wizard or+ * crashes the render (§9 risk 7). The catalog only SUGGESTS — control-api arbitrates.+ */+function parseGenericConfig(raw: unknown): GenericConfigSuggestion | undefined {+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined+ const src = raw as Record<string, unknown>+ const out: GenericConfigSuggestion = {}++ for (const key of GENERIC_STRING_KNOBS) {+ const v = src[key]+ if (typeof v === 'string' && v.length > 0) out[key] = v+ }+ for (const [key, allowed] of Object.entries(GENERIC_ENUM_KNOBS)) {+ const v = src[key]+ if (typeof v === 'string' && allowed.includes(v)) {+ ;(out as Record<string, unknown>)[key] = v+ }+ }+ for (const key of GENERIC_BOOL_KNOBS) {+ const v = src[key]+ if (typeof v === 'boolean') out[key] = v+ }+ const extra = src.extraAuthorizeParams+ if (extra && typeof extra === 'object' && !Array.isArray(extra)) {+ const record: Record<string, string> = {}+ for (const [k, v] of Object.entries(extra as Record<string, unknown>)) {+ if (typeof v === 'string') record[k] = v+ }+ if (Object.keys(record).length > 0) out.extraAuthorizeParams = record+ }++ return Object.keys(out).length > 0 ? out : undefined+}+/*** Preview mirror of control-api's `deriveOAuthClientId` (routes/admin/registry.ts).* The operator NEVER types `oauth.id`; control-api derives and validates it at@@ -54,8 +111,10 @@ export function buildOAuthRedirectUri(base: string | undefined, oauthId: string)/*** Extracts and shallow-validates the frozen `mcp_server_meta.oauth` block. Returns* null when the entry declares no OAuth (the caller then uses the ordinary- * connector install). Only fields the wizard understands survive; `genericConfig`- * is dropped (Slice 1, S-4).+ * connector install). Only fields the wizard understands survive. For a+ * `provider:'generic'` entry the catalog's `genericConfig` suggestion is parsed+ * defensively and kept (E-19.6); the wizard seeds from it, the admin confirms, and+ * control-api arbitrates (S-4).*/export function getCatalogOAuthBlock(entry: RegistryEntry | null | undefined@@ -72,6 +131,8 @@ export function getCatalogOAuthBlock(if (Array.isArray(block.scopes)) {result.scopes = block.scopes.filter((s): s is string => typeof s === 'string')}+ const genericConfig = parseGenericConfig(block.genericConfig)+ if (genericConfig) result.genericConfig = genericConfigreturn result}@@ -109,17 +170,22 @@ export function scopesAreSatisfied(scopes: readonly string[]): boolean {// The OAuth fields that are CEL-immutable on the mcpserver CRD (D-B7): a change// means delete + recreate, so the edit form shows them read-only. `scopes` is-// deliberately absent — it is editable (D-B6).+// deliberately absent — it is editable (D-B6). `generic` is present only for the+// `source:'generic'` carril: its endpoints and wire knobs are all create-only+// (GENERIC-IMM / GENERIC-SECRET-IMM) and shown read-only alongside the base fields.export type OAuthImmutableFields = {id: stringprovider: stringgrantScope: OAuthGrantScope | ''+ generic?: GenericImmutableView}/*** Reads the immutable OAuth fields off an installed McpServer's `spec.oauth` for a* read-only display in the edit form (D-B7). Returns null when the server carries- * no OAuth block.+ * no OAuth block. A generic connector has no `provider` (it is discriminated by+ * `source:'generic'`, DEC-28); it is surfaced with a synthetic `provider:'generic'`+ * label plus its read-only endpoints/knobs.*/export function extractOAuthImmutables(spec: Record<string, unknown> | null | undefined@@ -127,15 +193,22 @@ export function extractOAuthImmutables(const raw = spec?.oauthif (!raw || typeof raw !== 'object' || Array.isArray(raw)) return nullconst oauth = raw as Record<string, unknown>- const provider = typeof oauth.provider === 'string' ? oauth.provider : ''- if (!provider) return nullconst grantScope =oauth.grantScope === 'user' || oauth.grantScope === 'context' ? oauth.grantScope : ''- return {- id: typeof oauth.id === 'string' ? oauth.id : '',- provider,- grantScope,+ const id = typeof oauth.id === 'string' ? oauth.id : ''++ if (oauth.source === 'generic') {+ return {+ id,+ provider: 'generic',+ grantScope,+ generic: readGenericImmutables(oauth),+ }}++ const provider = typeof oauth.provider === 'string' ? oauth.provider : ''+ if (!provider) return null+ return { id, provider, grantScope }}/**diff --git a/control-ui/lib/oauthInstall.types.ts b/control-ui/lib/oauthInstall.types.tsindex 04f87dad4..01a965f42 100644--- a/control-ui/lib/oauthInstall.types.ts+++ b/control-ui/lib/oauthInstall.types.ts@@ -2,16 +2,20 @@// The submit shape mirrors the frozen control-api contract// (routes/admin/registry.ts InstallOAuthInputSchema): `oauth.id` is NEVER sent —// control-api derives and validates it (D-B5).+import type { GenericConfigSuggestion, GenericOAuthKnobs } from './oauthGeneric.types'export type OAuthGrantScope = 'user' | 'context'// The frozen catalog block carried under `mcp_server_meta.oauth` (S1-U1 contract).-// `genericConfig` is Slice-3-only and deliberately not modelled here: Slice 1-// serves only the 8 baked providers and never reads generic config (S-4).+// `genericConfig` is the Slice-3 generic-carril suggestion (E-19.6): a partial set of+// wire knobs the catalog SUGGESTS for a `provider:'generic'` entry. It is parsed+// defensively and never auto-applied — the wizard seeds from it, the admin confirms,+// and control-api arbitrates (S-4). A baked (non-generic) entry carries none.export type CatalogOAuthBlock = {provider: stringgrantScope?: OAuthGrantScopescopes?: string[]+ genericConfig?: GenericConfigSuggestion}export type OAuthSecretMode = 'managed' | 'reference'@@ -35,11 +39,14 @@ export type OAuthReferenceSecretInput = {export type OAuthSecretInput = OAuthManagedSecretInput | OAuthReferenceSecretInput-// The `oauth` sub-object attached to POST /admin/registry/install.+// The `oauth` sub-object attached to POST /admin/registry/install. `secret` is optional+// because a public generic client (DA-1) carries none; a baked install always sends it.+// `generic` is present only for the `provider:'generic'` carril (S3-B4).export type OAuthInstallSubmit = {scopes?: string[]grantScope?: OAuthGrantScope- secret: OAuthSecretInput+ secret?: OAuthSecretInput+ generic?: GenericOAuthKnobs}// GET /admin/oauth/providers/:id/credential-manifest response.diff --git a/control-ui/package-lock.json b/control-ui/package-lock.jsonindex 2f7f229cf..d7ae0683f 100644--- a/control-ui/package-lock.json+++ b/control-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-ui",- "version": "0.1.609",+ "version": "0.1.610","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-ui",- "version": "0.1.609",+ "version": "0.1.610","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/frontend-components": "file:../packages/frontend-components",diff --git a/control-ui/package.json b/control-ui/package.jsonindex 38857b5dc..71611322d 100644--- a/control-ui/package.json+++ b/control-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-ui",- "version": "0.1.609",+ "version": "0.1.610","private": true,"scripts": {"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",diff --git a/control-ui/test/fixtures/__tests__/genericDiscoveryPrefill.contract.test.ts b/control-ui/test/fixtures/__tests__/genericDiscoveryPrefill.contract.test.tsnew file mode 100644index 000000000..a28a80bcf--- /dev/null+++ b/control-ui/test/fixtures/__tests__/genericDiscoveryPrefill.contract.test.ts@@ -0,0 +1,78 @@+import { describe, expect, it } from 'vitest'+import type { GenericDiscoveryPrefill } from '../../../lib/oauthGeneric.types'+import { GENERIC_PREFILL_CASES } from '../genericDiscoveryPrefill'++/**+ * Reproduces the producer's projection (control-api discovery.ts+ * `buildGenericDiscoveryPrefill`, spec 19 §5.2) from the verbatim raw probe bytes and+ * asserts each hand-derived `GenericDiscoveryPrefill` fixture equals it. A fixture value+ * that drifts from the real server bytes fails here, so the fixtures cannot silently+ * encode an invented shape (T1).+ */+function projectPrefill(prmJson: string, asJson: string): GenericDiscoveryPrefill {+ const prm = JSON.parse(prmJson) as Record<string, unknown>+ const as = JSON.parse(asJson) as Record<string, unknown>++ const stringArray = (value: unknown): string[] =>+ Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string') : []+ const definedStringArray = (value: unknown): string[] | undefined =>+ Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string') : undefined++ const codeChallengeMethods = stringArray(as.code_challenge_methods_supported)+ const tokenEndpointAuthMethods = stringArray(as.token_endpoint_auth_methods_supported)+ const grantTypes = stringArray(as.grant_types_supported)+ const scopesSupported =+ definedStringArray(prm.scopes_supported) ?? definedStringArray(as.scopes_supported) ?? []++ const tokenAuthMethod: 'body' | 'basic' =+ tokenEndpointAuthMethods.includes('client_secret_basic') &&+ !tokenEndpointAuthMethods.includes('client_secret_post')+ ? 'basic'+ : 'body'++ const prefill: GenericDiscoveryPrefill = {+ issuer: as.issuer as string,+ endpoints: {+ authorization: as.authorization_endpoint as string,+ token: as.token_endpoint as string,+ },+ scopesSupported,+ capabilities: { codeChallengeMethods, tokenEndpointAuthMethods, grantTypes },+ suggested: {+ usePkce: codeChallengeMethods.includes('S256'),+ tokenAuthMethod,+ // deriveQuirks fail-closed refresh rule: grant_types_supported ∋ refresh_token.+ supportsRefresh: grantTypes.includes('refresh_token'),+ },+ }+ // resource is present only via the PRM path; these pilots all resolve through the PRM.+ if (typeof prm.resource === 'string') prefill.resource = prm.resource+ return prefill+}++describe('generic discovery prefill fixtures match the real probe bytes (T1)', () => {+ for (const { name, prm, as, fixture } of GENERIC_PREFILL_CASES) {+ it(`${name}: fixture equals the producer projection of the raw bytes`, () => {+ expect(fixture).toEqual(projectPrefill(prm, as))+ })+ }++ it('the S256-bearing pilots suggest usePkce:true; the S256-less variant suggests false', () => {+ for (const name of ['notion', 'linear', 'sentry', 'canva']) {+ const c = GENERIC_PREFILL_CASES.find(x => x.name === name)!+ expect(c.fixture.suggested.usePkce).toBe(true)+ }+ expect(+ GENERIC_PREFILL_CASES.find(x => x.name === 'notion-no-s256')!.fixture.suggested.usePkce+ ).toBe(false)+ })++ it('basic auth is suggested only when the AS advertises basic without post', () => {+ expect(+ GENERIC_PREFILL_CASES.find(x => x.name === 'notion-basic')!.fixture.suggested.tokenAuthMethod+ ).toBe('basic')+ expect(+ GENERIC_PREFILL_CASES.find(x => x.name === 'notion')!.fixture.suggested.tokenAuthMethod+ ).toBe('body')+ })+})diff --git a/control-ui/test/fixtures/genericDiscoveryPrefill.ts b/control-ui/test/fixtures/genericDiscoveryPrefill.tsnew file mode 100644index 000000000..4246947ad--- /dev/null+++ b/control-ui/test/fixtures/genericDiscoveryPrefill.ts@@ -0,0 +1,215 @@+/**+ * Producer fixtures — the `GenericDiscoveryPrefill` wire POST /admin/oauth/discover+ * returns for the generic carril (spec 19 §5.2, S3-B4). control-ui cannot run+ * control-api's discovery in this package, so each prefill below is DERIVED FROM THE+ * REAL SERVER PROBE BYTES: the verbatim PRM/AS JSON strings live in the sibling+ * `remoteMcpDiscovery.ts` (live probes 2026-09-20, control-api's own T1 fixtures) and the+ * projection here is the one the producer applies (control-api+ * src/oauth/discovery.ts `buildGenericDiscoveryPrefill`, §5.2). DA-3: the issuer-first+ * self-hosted path is covered by these real pilot authorization servers, which expose+ * RFC 8414 / OpenID metadata — no invented JSON.+ *+ * The colocated contract test re-parses the verbatim raw bytes and reproduces the+ * projection, so a hand-typed value that drifts from the real bytes fails there.+ */+import type { GenericDiscoveryPrefill } from '../../lib/oauthGeneric.types'+import {+ CANVA_AS_JSON,+ CANVA_PRM_JSON,+ LINEAR_AS_JSON,+ LINEAR_PRM_JSON,+ NOTION_AS_JSON,+ NOTION_PRM_JSON,+ SENTRY_AS_JSON,+ SENTRY_PRM_JSON,+} from './remoteMcpDiscovery'++// ─── Derived-from-real AS byte variants (documented subtractions, nothing invented) ──++/**+ * Notion's AS with S256 removed from `code_challenge_methods_supported` (leaving the+ * real `plain`). The producer then suggests `usePkce:false` while still reporting that+ * the AS advertised a code-challenge method — the case that makes Apply flip a default.+ */+export const NOTION_NO_S256_AS_JSON = ((): string => {+ const as = JSON.parse(NOTION_AS_JSON) as Record<string, unknown>+ as.code_challenge_methods_supported = ['plain']+ return JSON.stringify(as)+})()++/**+ * Notion's AS with the token-endpoint auth methods narrowed to `client_secret_basic`+ * only — the documented subtraction that pushes the producer's `tokenAuthMethod`+ * suggestion to `basic` (advertises basic and NOT post).+ */+export const NOTION_BASIC_AS_JSON = ((): string => {+ const as = JSON.parse(NOTION_AS_JSON) as Record<string, unknown>+ as.token_endpoint_auth_methods_supported = ['client_secret_basic']+ return JSON.stringify(as)+})()++// ─── `prefill` fixtures (hand-derived; locked to the bytes by the contract test) ─────++/** Notion — PKCE S256, both auth methods (→ body), refresh supported. */+export const NOTION_GENERIC_PREFILL: GenericDiscoveryPrefill = {+ issuer: 'https://mcp.notion.com',+ endpoints: {+ authorization: 'https://mcp.notion.com/authorize',+ token: 'https://mcp.notion.com/token',+ },+ resource: 'https://mcp.notion.com',+ scopesSupported: ['default'],+ capabilities: {+ codeChallengeMethods: ['plain', 'S256'],+ tokenEndpointAuthMethods: ['client_secret_basic', 'client_secret_post', 'none'],+ grantTypes: [+ 'authorization_code',+ 'refresh_token',+ 'urn:ietf:params:oauth:grant-type:jwt-bearer',+ ],+ },+ suggested: { usePkce: true, tokenAuthMethod: 'body', supportsRefresh: true },+}++/** Linear — scopes from the PRM, resource carries a /mcp path. */+export const LINEAR_GENERIC_PREFILL: GenericDiscoveryPrefill = {+ issuer: 'https://mcp.linear.app',+ endpoints: {+ authorization: 'https://mcp.linear.app/authorize',+ token: 'https://mcp.linear.app/token',+ },+ resource: 'https://mcp.linear.app/mcp',+ scopesSupported: ['read', 'write'],+ capabilities: {+ codeChallengeMethods: ['S256'],+ tokenEndpointAuthMethods: ['client_secret_basic', 'client_secret_post', 'none'],+ grantTypes: [+ 'authorization_code',+ 'refresh_token',+ 'urn:ietf:params:oauth:grant-type:jwt-bearer',+ ],+ },+ suggested: { usePkce: true, tokenAuthMethod: 'body', supportsRefresh: true },+}++/** Sentry — S256, refresh supported. */+export const SENTRY_GENERIC_PREFILL: GenericDiscoveryPrefill = {+ issuer: 'https://mcp.sentry.dev',+ endpoints: {+ authorization: 'https://mcp.sentry.dev/oauth/authorize',+ token: 'https://mcp.sentry.dev/oauth/token',+ },+ resource: 'https://mcp.sentry.dev/mcp',+ scopesSupported: ['org:read', 'project:write', 'team:write', 'event:write'],+ capabilities: {+ codeChallengeMethods: ['S256'],+ tokenEndpointAuthMethods: ['client_secret_basic', 'client_secret_post', 'none'],+ grantTypes: ['authorization_code', 'refresh_token'],+ },+ suggested: { usePkce: true, tokenAuthMethod: 'body', supportsRefresh: true },+}++/** Canva — AS has no scopes_supported, so scopes come from the PRM (16 of them). */+export const CANVA_GENERIC_PREFILL: GenericDiscoveryPrefill = {+ issuer: 'https://mcp.canva.com',+ endpoints: {+ authorization: 'https://mcp.canva.com/authorize',+ token: 'https://mcp.canva.com/token',+ },+ resource: 'https://mcp.canva.com',+ scopesSupported: [+ 'profile:read',+ 'design:meta:read',+ 'design:content:write',+ 'design:content:read',+ 'folder:read',+ 'folder:write',+ 'brandtemplate:content:read',+ 'brandtemplate:meta:read',+ 'brandtemplate:content:write',+ 'comment:write',+ 'comment:read',+ 'asset:read',+ 'asset:write',+ 'brandkit:read',+ 'help:answers:read',+ 'help:answers:write',+ ],+ capabilities: {+ codeChallengeMethods: ['plain', 'S256'],+ tokenEndpointAuthMethods: ['client_secret_basic', 'client_secret_post', 'none'],+ grantTypes: [+ 'authorization_code',+ 'refresh_token',+ 'urn:ietf:params:oauth:grant-type:jwt-bearer',+ ],+ },+ suggested: { usePkce: true, tokenAuthMethod: 'body', supportsRefresh: true },+}++/** Notion minus S256 — the producer suggests usePkce:false (Apply flips the default). */+export const NOTION_NO_S256_GENERIC_PREFILL: GenericDiscoveryPrefill = {+ issuer: 'https://mcp.notion.com',+ endpoints: {+ authorization: 'https://mcp.notion.com/authorize',+ token: 'https://mcp.notion.com/token',+ },+ resource: 'https://mcp.notion.com',+ scopesSupported: ['default'],+ capabilities: {+ codeChallengeMethods: ['plain'],+ tokenEndpointAuthMethods: ['client_secret_basic', 'client_secret_post', 'none'],+ grantTypes: [+ 'authorization_code',+ 'refresh_token',+ 'urn:ietf:params:oauth:grant-type:jwt-bearer',+ ],+ },+ suggested: { usePkce: false, tokenAuthMethod: 'body', supportsRefresh: true },+}++/** Notion narrowed to client_secret_basic only — the producer suggests tokenAuthMethod:basic. */+export const NOTION_BASIC_GENERIC_PREFILL: GenericDiscoveryPrefill = {+ issuer: 'https://mcp.notion.com',+ endpoints: {+ authorization: 'https://mcp.notion.com/authorize',+ token: 'https://mcp.notion.com/token',+ },+ resource: 'https://mcp.notion.com',+ scopesSupported: ['default'],+ capabilities: {+ codeChallengeMethods: ['plain', 'S256'],+ tokenEndpointAuthMethods: ['client_secret_basic'],+ grantTypes: [+ 'authorization_code',+ 'refresh_token',+ 'urn:ietf:params:oauth:grant-type:jwt-bearer',+ ],+ },+ suggested: { usePkce: true, tokenAuthMethod: 'basic', supportsRefresh: true },+}++// Raw-byte source pairing for the contract test.+export const GENERIC_PREFILL_CASES: Array<{+ name: string+ prm: string+ as: string+ fixture: GenericDiscoveryPrefill+}> = [+ { name: 'notion', prm: NOTION_PRM_JSON, as: NOTION_AS_JSON, fixture: NOTION_GENERIC_PREFILL },+ { name: 'linear', prm: LINEAR_PRM_JSON, as: LINEAR_AS_JSON, fixture: LINEAR_GENERIC_PREFILL },+ { name: 'sentry', prm: SENTRY_PRM_JSON, as: SENTRY_AS_JSON, fixture: SENTRY_GENERIC_PREFILL },+ { name: 'canva', prm: CANVA_PRM_JSON, as: CANVA_AS_JSON, fixture: CANVA_GENERIC_PREFILL },+ {+ name: 'notion-no-s256',+ prm: NOTION_PRM_JSON,+ as: NOTION_NO_S256_AS_JSON,+ fixture: NOTION_NO_S256_GENERIC_PREFILL,+ },+ {+ name: 'notion-basic',+ prm: NOTION_PRM_JSON,+ as: NOTION_BASIC_AS_JSON,+ fixture: NOTION_BASIC_GENERIC_PREFILL,+ },+]