mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-10 20:46:28 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Agents use Apps through a gateway that checks identity, company access, and action policies. > - Personal pasted credentials can point to company secrets. Setup can show success while the gateway rejects every call. > - Several OAuth methods also omit the scopes needed for their supported write actions. > - This pull request gives setup, health checks, and invocation the same credential rules. Owners repair existing connections by reconnecting. > - New connections request reviewed permissions for their supported actions. Read-only choices remain available under Advanced. > - Agents can use the connections people give them, while existing consent, identity boundaries, and action restrictions remain enforced. ## Linked Issues or Issue Description Refs #14009 and #14008. This addresses the personal-credential defect. The separate GitHub organization-identity selection defect is outside this change. Related work: #13942 fixed part of new personal-key setup. #14200 independently fixes legacy personal reconnect and protects managed-agent profile credentials during removal. This PR covers that ownership invariant across key and secret-URL setup, reconnect, health, discovery, and invocation, and keeps owner reconnect as the repair path. #14059 tracks requested versus provider-asserted OAuth scopes; it remains separate work. I searched open PRs and issues for Zapier, Airtable scopes, connector writes, and personal credential failures. **What happened?** A Zapier secret URL saved through personal setup can become a company secret referenced by a user grant. Health checks bypass the gateway's ownership check, so the connection appears healthy but calls fail with `grant_credential_invalid`. Custom-header paths can also receive a duplicate `credentials.` prefix. Omitted OAuth scopes make write access depend on provider defaults. **Expected behavior** Personal invocation credentials belong to the selected user. Setup, health, and actual calls enforce the same rule. New connections request documented permissions for supported read and write actions. Existing tokens gain no permissions without provider consent. **Steps to reproduce** 1. Connect Zapier or a generic secret URL with the personal identity. 2. Allow an agent to use the connection and complete setup. 3. Invoke a tool through a run-scoped gateway. The legacy layout fails ownership validation despite successful setup. **Paperclip version or commit** The implementation started from `44736c9c7c67b7b646ead9d51721db10f5b83835` and was rebased onto master at `94e8dec56`. **Deployment mode** Built from source. Regression tests use isolated PostgreSQL fixtures and controlled MCP transports. ## What Changed - Share credential writing, ownership validation, and canonical paths across initial setup, resume, reconnect, rotation, health, discovery, and gateway calls. Keep OAuth client-registration secrets separate from invocation credentials. - Existing personal connections with company-scoped credentials require owner reconnect with a fresh key or secret URL. Reconnect creates a correctly owned value and updates the existing grant and declarations. There is no automatic ownership backfill or new startup hook. - Preserve PostgreSQL timestamp precision when reconnect checks whether a grant changed. Previously, converting the timestamp to a JavaScript Date could reject reconnect with a false concurrent-change error. - Protect credentials used by other grants, connections, bindings, managed-agent profiles, routine triggers, or secret proposals from connection removal. - Review all 117 tool methods, including 84 OAuth methods. Record explicit scopes or documented provider-default exceptions with official evidence. Add Airtable's seven scopes, Hugging Face repository/job scopes, and other documented MCP permissions. - Prefer available write-capable methods. Put explicit read-only choices under Advanced. Explain pasted-key permissions and offer reconnect for missing OAuth consent. Preserve existing grants, policies, Google availability gates, and curated scope allowlists. - Reconnect generic secret URLs and custom headers using their stored credential fields. Refresh the catalog after setup, correct reconnect feedback and error guidance, and let Cancel exit invalid setup while Save & exit retains draft-saving behavior. - Apply ownership checks to the new GitHub repository/skill connection picker. Align the permission audit with the Google scope reductions merged on master. - Add run-scoped gateway, ownership, owner-reconnect, OAuth URL, insufficient-scope, UI, and catalog-wide regression coverage. Update the connector playbook and permission audit. ## Verification Latest commit `97bc0b86e0eae0ec892e4ac44beff1a66164b20e` passes all CI/status gates (55 completed check runs, no failures or pending checks) and has a completed Greptile review at **5/5 with no outstanding findings**. GitHub reports the PR as mergeable/CLEAN. - **Embedded browser:** used the actual server and built UI from this worktree, a fresh isolated database, and local HTTP MCP fixtures. Completed personal bearer-key, secret-URL, and custom-header setup; reproduced the legacy ownership failure; reconnected through the owner’s form; and completed writes afterward. Read-back was verified for bearer-key and secret-URL connections. Public organization-wide setup appeared immediately in Browse without reload. Zapier URL validation/Cancel and Google’s enrollment gate were also exercised. - **Persistence and invocation:** verified user ownership, canonical `credentials.authorization` / `remote.url` / `headers.X-Api-Key` declarations, and unchanged connection/grant identity. The old company secrets retain their ownership. Separate HTTP calls through an actual run-scoped gateway session completed a write and read-back. - **Backend coverage:** the final gateway suite passes all 82 cases, including catalog Zapier and generic inline reconnect. It checks company/user isolation, canonical declarations, same-endpoint URL validation, fresh credentials, retained restrictions, and real gateway read/write execution using fixture transport. A timestamp with PostgreSQL microseconds covers the former false reconnect conflict. - **Local checks:** 368 catalog, gateway, repository, and UI tests passed before the final extra Zapier case; 49 GitHub skill access tests also passed. All three Apps browser regressions pass, including reconnect through the actual form and catalog visibility without reload. Full `pnpm -r typecheck`, `pnpm build`, server typecheck after the final patch, and token gates passed. Full tool-access service runs hit varying 15-second Google fixture timeouts; both affected cases and the updated reconnect assertion pass in isolation (3 tests). The complete test matrix passes in CI on this head. - **Verification limits:** no live provider account was available for Zapier/Airtable/OAuth consent or account-bound write proof. Public metadata and local fixtures do not establish provider consent. The original development database clone failed on a pre-existing missing `tool_connections_transport_check` constraint; browser acceptance used a fresh isolated database created by the normal CLI onboarding flow. ## Risks - Existing broken personal connections stay unusable until their owner reconnects. Health, discovery, and invocation return an actionable ownership error; startup does not rewrite credential ownership. - Scope changes affect new authorization requests. Providers may still require resource selection, account roles, paid plans, or app verification. Existing consent and action restrictions remain unchanged. - Shared credentials are retained rather than reassigned or revoked. Provider-default exceptions and unavailable live checks are documented in `doc/connections/CONNECTOR-PERMISSION-AUDIT.md`. - No new endpoint, database table, lockfile change, or CI workflow change is included. ## Model Used OpenAI Codex, based on GPT-6, with reasoning, code editing, shell execution, web research, and browser tools. The exact deployment model ID and context window were not exposed in this session. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
629 lines
23 KiB
TypeScript
629 lines
23 KiB
TypeScript
import { useState } from "react";
|
||
import { useMutation } from "@tanstack/react-query";
|
||
import { ArrowUpRight, ChevronRight, Loader2, Lock } from "lucide-react";
|
||
import type {
|
||
AppDefinition,
|
||
ConnectionGrant,
|
||
ToolConnection,
|
||
ToolConnectionCredentialPolicy,
|
||
} from "@paperclipai/shared";
|
||
import { connectionCredentialConfigPath, credentialConfigPath, getAvailableConnectionMethod, humanizeConnectionDisplayName } from "@paperclipai/shared";
|
||
import { toolsApi } from "@/api/tools";
|
||
import { Button } from "@/components/ui/button";
|
||
import {
|
||
Collapsible,
|
||
CollapsibleContent,
|
||
CollapsibleTrigger,
|
||
} from "@/components/ui/collapsible";
|
||
import { Input } from "@/components/ui/input";
|
||
import { ToggleSwitch } from "@/components/ui/toggle-switch";
|
||
import { useToast } from "@/context/ToastContext";
|
||
import { redactUrlSecrets } from "@/lib/redact-url-secrets";
|
||
import { navigateTopLevel } from "@/lib/browserNavigation";
|
||
import { prepareOAuthNavigation, savePendingCloudHandoff } from "@/lib/oauthHandoff";
|
||
import { cn } from "@/lib/utils";
|
||
import { Link } from "@/lib/router";
|
||
import type { AppDetailSectionProps } from "./types";
|
||
import { RevokeGrantDialog } from "./IdentitiesSection";
|
||
|
||
export function AdvancedPanel({
|
||
connection,
|
||
appName,
|
||
galleryEntry,
|
||
removing,
|
||
onRemove,
|
||
onReplaced,
|
||
canReplaceCredential = true,
|
||
credentialUnavailableMessage = "You don't have permission to replace this identity's credential.",
|
||
appToggleDisabled,
|
||
onToggleApp,
|
||
identityGrant = null,
|
||
identityCurrentUserId = null,
|
||
identityProviderName,
|
||
credentialPolicy,
|
||
identityActionPending = false,
|
||
onReconnectIdentity,
|
||
onRevokeIdentity,
|
||
}: Pick<AppDetailSectionProps, "connection" | "appName" | "galleryEntry"> & {
|
||
removing: boolean;
|
||
onRemove: () => void;
|
||
onReplaced: () => void;
|
||
canReplaceCredential?: boolean;
|
||
credentialUnavailableMessage?: string;
|
||
appToggleDisabled: boolean;
|
||
onToggleApp: () => void;
|
||
identityGrant?: ConnectionGrant | null;
|
||
identityCurrentUserId?: string | null;
|
||
identityProviderName?: string;
|
||
credentialPolicy?: ToolConnectionCredentialPolicy;
|
||
identityActionPending?: boolean;
|
||
onReconnectIdentity?: () => void;
|
||
onRevokeIdentity?: (grant: ConnectionGrant) => void;
|
||
}) {
|
||
return (
|
||
<div className="space-y-4 border-t border-border pt-8">
|
||
<TechnicalDetails connection={connection} />
|
||
<DangerZone
|
||
appName={appName}
|
||
connection={connection}
|
||
galleryEntry={galleryEntry}
|
||
removing={removing}
|
||
onRemove={onRemove}
|
||
onReplaced={onReplaced}
|
||
canReplaceCredential={canReplaceCredential}
|
||
credentialUnavailableMessage={credentialUnavailableMessage}
|
||
toggleDisabled={appToggleDisabled}
|
||
onToggleConnection={onToggleApp}
|
||
identityGrant={identityGrant}
|
||
identityCurrentUserId={identityCurrentUserId}
|
||
identityProviderName={identityProviderName ?? appName}
|
||
credentialPolicy={credentialPolicy}
|
||
identityActionPending={identityActionPending}
|
||
onReconnectIdentity={onReconnectIdentity}
|
||
onRevokeIdentity={onRevokeIdentity}
|
||
/>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
function connectionMethodUnavailable(connection: ToolConnection, galleryEntry: AppDefinition | null): boolean {
|
||
const methodKey = connection.config?.connectionMethodKey;
|
||
return typeof methodKey === "string"
|
||
&& methodKey.length > 0
|
||
&& !!galleryEntry
|
||
&& Array.isArray(galleryEntry.methods)
|
||
&& !getAvailableConnectionMethod(galleryEntry, methodKey);
|
||
}
|
||
|
||
function KeySection({
|
||
connection,
|
||
galleryEntry,
|
||
onReplaced,
|
||
canReplace,
|
||
unavailableMessage,
|
||
}: {
|
||
connection: ToolConnection;
|
||
galleryEntry: AppDefinition | null;
|
||
onReplaced: () => void;
|
||
canReplace: boolean;
|
||
unavailableMessage: string;
|
||
}) {
|
||
const [open, setOpen] = useState(false);
|
||
return (
|
||
<section>
|
||
<div className="flex items-center justify-between">
|
||
<div className="flex items-start gap-3">
|
||
<Lock className="mt-0.5 h-4 w-4 text-muted-foreground" />
|
||
<div>
|
||
<h2 className="text-sm font-medium text-foreground">Reconnect</h2>
|
||
<p className="mt-0.5 text-xs text-muted-foreground">
|
||
{canReplace ? "Replace the stored credential." : unavailableMessage}
|
||
</p>
|
||
</div>
|
||
</div>
|
||
{canReplace && !open && (
|
||
<Button size="sm" variant="outline" onClick={() => setOpen(true)}>
|
||
Reconnect
|
||
</Button>
|
||
)}
|
||
</div>
|
||
{open && (
|
||
<div className="pt-4">
|
||
<ReconnectForm
|
||
connection={connection}
|
||
galleryEntry={galleryEntry}
|
||
onCancel={() => setOpen(false)}
|
||
onReconnected={() => {
|
||
setOpen(false);
|
||
onReplaced();
|
||
}}
|
||
/>
|
||
</div>
|
||
)}
|
||
</section>
|
||
);
|
||
}
|
||
|
||
export function ReconnectCard({
|
||
connection,
|
||
galleryEntry,
|
||
onReconnected,
|
||
onReconnect,
|
||
canReconnect = true,
|
||
reconnectUnavailableMessage,
|
||
}: {
|
||
connection: ToolConnection;
|
||
galleryEntry: AppDefinition | null;
|
||
onReconnected: () => void;
|
||
onReconnect?: () => void;
|
||
canReconnect?: boolean;
|
||
reconnectUnavailableMessage?: string;
|
||
}) {
|
||
const { pushToast } = useToast();
|
||
const reconnectOAuth = useMutation({
|
||
// Reconnect is not a new identity choice. Personal-only connections must
|
||
// put the replacement token back on the signed-in user's existing grant;
|
||
// shared and legacy fallback connections keep using the organization slot.
|
||
mutationFn: () => connection.credentialPolicy === "per_user"
|
||
? toolsApi.startOAuth(connection.id, { asCurrentUser: true })
|
||
: toolsApi.startOAuth(connection.id),
|
||
onSuccess: async (start) => {
|
||
try {
|
||
const target = await prepareOAuthNavigation(start);
|
||
if (target.kind === "reauthentication" && start.handoff) {
|
||
savePendingCloudHandoff(start.handoff.session);
|
||
}
|
||
navigateTopLevel(target.url);
|
||
} catch (error) {
|
||
pushToast({
|
||
title: "Couldn’t start sign-in",
|
||
body: error instanceof Error ? error.message : "Please try again.",
|
||
tone: "error",
|
||
});
|
||
}
|
||
},
|
||
onError: (error) =>
|
||
pushToast({
|
||
title: "Couldn’t start sign-in",
|
||
body: error instanceof Error ? error.message : "Please try again.",
|
||
tone: "error",
|
||
}),
|
||
});
|
||
const verifyVercel = useMutation({
|
||
mutationFn: () => toolsApi.checkConnectionHealth(connection.id),
|
||
onSuccess: () => {
|
||
pushToast({
|
||
title: "Vercel credential verified",
|
||
body: `${humanizeConnectionDisplayName(connection)} is back online.`,
|
||
tone: "success",
|
||
});
|
||
onReconnected();
|
||
},
|
||
onError: (error) => pushToast({
|
||
title: "Credential still needs attention",
|
||
body: error instanceof Error ? error.message : "Review the connector in Vercel Connect and try again.",
|
||
tone: "error",
|
||
}),
|
||
});
|
||
const oauth = connection.authKind === "oauth";
|
||
const managedByVercel = connection.credentialSource === "vercel_connect";
|
||
const methodUnavailable = connectionMethodUnavailable(connection, galleryEntry);
|
||
|
||
return (
|
||
<div className="flex flex-col gap-4 rounded-lg border border-amber-500/50 bg-amber-500/10 px-4 py-3">
|
||
<div className="min-w-0">
|
||
<h2 className="text-sm font-semibold text-amber-900 dark:text-amber-100">
|
||
{methodUnavailable ? "Connection no longer supported" : oauth ? "Reconnect required" : "This app needs reconnecting"}
|
||
</h2>
|
||
<p className="mt-0.5 text-sm text-amber-800 dark:text-amber-200">
|
||
{methodUnavailable
|
||
? "Add a supported connection from Connectors, then remove this connection."
|
||
: connection.healthMessage?.trim() || (oauth
|
||
? "Authorization expired or was revoked. Sign in again to restore access."
|
||
: "The key stopped working. Paste a new one to get it back online.")}
|
||
</p>
|
||
</div>
|
||
<div className="shrink-0">
|
||
{!canReconnect ? (
|
||
<p className="text-sm text-amber-800 dark:text-amber-200">
|
||
{reconnectUnavailableMessage ?? "You don't have permission to reconnect this identity."}
|
||
</p>
|
||
) : methodUnavailable ? (
|
||
<Button size="sm" variant="outline" asChild>
|
||
<Link to={`/apps/connect?source=${encodeURIComponent(galleryEntry!.slug)}`}>
|
||
Add supported connection
|
||
</Link>
|
||
</Button>
|
||
) : onReconnect ? (
|
||
<Button size="sm" variant="outline" onClick={onReconnect}>Reconnect</Button>
|
||
) : managedByVercel && !oauth ? (
|
||
<div className="flex items-center gap-2">
|
||
<Button type="button" size="sm" variant="outline" asChild>
|
||
<a href="https://vercel.com/connect" target="_blank" rel="noreferrer">
|
||
Manage in Vercel <ArrowUpRight className="ml-1.5 h-3.5 w-3.5" />
|
||
</a>
|
||
</Button>
|
||
<Button
|
||
type="button"
|
||
size="sm"
|
||
disabled={verifyVercel.isPending}
|
||
onClick={() => verifyVercel.mutate()}
|
||
>
|
||
{verifyVercel.isPending && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}
|
||
Check again
|
||
</Button>
|
||
</div>
|
||
) : oauth ? (
|
||
<Button
|
||
type="button"
|
||
size="sm"
|
||
disabled={reconnectOAuth.isPending}
|
||
onClick={() => reconnectOAuth.mutate()}
|
||
>
|
||
{reconnectOAuth.isPending && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}
|
||
{reconnectOAuth.isPending ? "Opening sign-in…" : "Reconnect"}
|
||
</Button>
|
||
) : (
|
||
<ReconnectForm connection={connection} galleryEntry={galleryEntry} onReconnected={onReconnected} />
|
||
)}
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
function ReconnectForm({
|
||
connection,
|
||
galleryEntry,
|
||
onCancel,
|
||
onReconnected,
|
||
}: {
|
||
connection: ToolConnection;
|
||
galleryEntry: AppDefinition | null;
|
||
onCancel?: () => void;
|
||
onReconnected: () => void;
|
||
}) {
|
||
const { pushToast } = useToast();
|
||
const methodKey = typeof connection.config?.connectionMethodKey === "string"
|
||
? connection.config.connectionMethodKey
|
||
: null;
|
||
const method = galleryEntry && Array.isArray(galleryEntry.methods)
|
||
? getAvailableConnectionMethod(galleryEntry, methodKey)
|
||
: null;
|
||
const galleryFields = (method?.credentialFields ?? []).map((field) => ({
|
||
...field,
|
||
configPath: credentialConfigPath(field, method),
|
||
helpUrl: method?.consoleLinks?.keys ?? method?.consoleLinks?.docs ?? "",
|
||
}));
|
||
const fields = galleryFields.length > 0 ? galleryFields : (connection.credentialRefs ?? [])
|
||
.filter((ref) => ref.placement === "header" || ref.placement === "url")
|
||
.map((ref) => ({
|
||
configPath: connectionCredentialConfigPath(ref),
|
||
label: ref.placement === "url" ? "MCP server URL" : ref.prefix === "Bearer " ? "App key" : ref.key ?? ref.name,
|
||
helpUrl: "",
|
||
required: true,
|
||
}));
|
||
const [values, setValues] = useState<Record<string, string>>({});
|
||
const [single, setSingle] = useState("");
|
||
const usesFields = fields.length > 0;
|
||
|
||
const reconnect = useMutation({
|
||
mutationFn: () => {
|
||
const credentialValues = usesFields
|
||
? values
|
||
: { "credentials.authorization": single.trim() };
|
||
return toolsApi.reconnectConnection(connection.id, credentialValues);
|
||
},
|
||
onSuccess: (result) => {
|
||
const healthy =
|
||
result.connection.healthStatus === "ok" || result.connection.healthStatus === "healthy" || result.connection.healthStatus === "unknown";
|
||
if (healthy) {
|
||
pushToast({
|
||
title: "Reconnected",
|
||
body: `${humanizeConnectionDisplayName(connection)} is back online.`,
|
||
tone: "success",
|
||
});
|
||
onReconnected();
|
||
} else {
|
||
pushToast({
|
||
title: "Still not working",
|
||
body: result.connection.healthMessage?.trim() || "That key didn't check out. Try another.",
|
||
tone: "error",
|
||
});
|
||
}
|
||
},
|
||
onError: (error) =>
|
||
pushToast({
|
||
title: "That key didn't work",
|
||
body: error instanceof Error ? error.message : "Check the key and try again.",
|
||
tone: "error",
|
||
}),
|
||
});
|
||
|
||
const filled = usesFields
|
||
? fields.every((f) => f.required === false || (values[f.configPath]?.trim().length ?? 0) > 0)
|
||
: single.trim().length > 0;
|
||
|
||
if (connection.credentialSource === "vercel_connect") {
|
||
return (
|
||
<p className="text-sm text-muted-foreground">
|
||
Credentials for this connection are managed in Vercel Connect.
|
||
</p>
|
||
);
|
||
}
|
||
|
||
return (
|
||
<div className="space-y-3">
|
||
{usesFields ? (
|
||
fields.map((field) => (
|
||
<div key={field.configPath}>
|
||
<label className="text-xs font-medium text-foreground">{field.label}</label>
|
||
<Input
|
||
type="password"
|
||
aria-label={field.label}
|
||
autoComplete="off"
|
||
value={values[field.configPath] ?? ""}
|
||
onChange={(e) => setValues({ ...values, [field.configPath]: e.target.value })}
|
||
placeholder="****************"
|
||
className="mt-1 h-10 font-mono"
|
||
/>
|
||
{field.helpUrl && (
|
||
<a
|
||
href={field.helpUrl}
|
||
target="_blank"
|
||
rel="noreferrer"
|
||
className="mt-1 inline-flex items-center gap-1 text-xs font-semibold text-foreground underline underline-offset-2"
|
||
>
|
||
Where do I find this? <ArrowUpRight className="h-3 w-3" />
|
||
</a>
|
||
)}
|
||
</div>
|
||
))
|
||
) : (
|
||
<Input
|
||
type="password"
|
||
aria-label="App key"
|
||
autoComplete="off"
|
||
value={single}
|
||
onChange={(e) => setSingle(e.target.value)}
|
||
placeholder="Paste your new key"
|
||
className="h-10 font-mono"
|
||
/>
|
||
)}
|
||
<div className="flex items-center gap-2">
|
||
<Button size="sm" disabled={!filled || reconnect.isPending} onClick={() => reconnect.mutate()}>
|
||
{reconnect.isPending && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}
|
||
{reconnect.isPending ? "Checking..." : "Check & reconnect"}
|
||
</Button>
|
||
{onCancel && (
|
||
<Button size="sm" variant="ghost" onClick={onCancel} disabled={reconnect.isPending}>
|
||
Cancel
|
||
</Button>
|
||
)}
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
function TechnicalDetails({ connection }: { connection: ToolConnection }) {
|
||
const [open, setOpen] = useState(false);
|
||
return (
|
||
<Collapsible open={open} onOpenChange={setOpen} asChild>
|
||
<section>
|
||
<CollapsibleTrigger asChild>
|
||
<button type="button" className="flex w-full items-center gap-3 py-1 text-left">
|
||
<span className="min-w-0 flex-1 text-sm font-medium text-foreground">Connection details</span>
|
||
<ChevronRight
|
||
className={cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform", open && "rotate-90")}
|
||
/>
|
||
</button>
|
||
</CollapsibleTrigger>
|
||
<CollapsibleContent>
|
||
<dl className="mt-4 grid gap-2 pb-2 text-xs sm:grid-cols-(--gtc-59)">
|
||
<dt className="text-muted-foreground">Address</dt>
|
||
<dd className="break-all font-mono text-foreground">{connectionAddress(connection)}</dd>
|
||
<dt className="text-muted-foreground">Type</dt>
|
||
<dd className="text-foreground">{connectionTransportLabel(connection.transport)}</dd>
|
||
</dl>
|
||
</CollapsibleContent>
|
||
</section>
|
||
</Collapsible>
|
||
);
|
||
}
|
||
|
||
export function DangerZone({
|
||
appName,
|
||
connection,
|
||
galleryEntry = null,
|
||
removing,
|
||
onRemove,
|
||
onReplaced,
|
||
canReplaceCredential = true,
|
||
credentialUnavailableMessage = "You don't have permission to replace this identity's credential.",
|
||
toggleDisabled = false,
|
||
onToggleConnection,
|
||
identityGrant = null,
|
||
identityCurrentUserId = null,
|
||
identityProviderName = appName,
|
||
credentialPolicy,
|
||
identityActionPending = false,
|
||
onReconnectIdentity,
|
||
onRevokeIdentity,
|
||
}: {
|
||
appName: string;
|
||
connection?: ToolConnection;
|
||
galleryEntry?: AppDefinition | null;
|
||
removing: boolean;
|
||
onRemove: () => void;
|
||
onReplaced?: () => void;
|
||
canReplaceCredential?: boolean;
|
||
credentialUnavailableMessage?: string;
|
||
toggleDisabled?: boolean;
|
||
onToggleConnection?: () => void;
|
||
identityGrant?: ConnectionGrant | null;
|
||
identityCurrentUserId?: string | null;
|
||
identityProviderName?: string;
|
||
credentialPolicy?: ToolConnectionCredentialPolicy;
|
||
identityActionPending?: boolean;
|
||
onReconnectIdentity?: () => void;
|
||
onRevokeIdentity?: (grant: ConnectionGrant) => void;
|
||
}) {
|
||
const [open, setOpen] = useState(false);
|
||
const [confirming, setConfirming] = useState(false);
|
||
const [revokeTarget, setRevokeTarget] = useState<ConnectionGrant | null>(null);
|
||
const paused = connection
|
||
? connection.enabled === false || connection.status === "disabled"
|
||
: false;
|
||
const methodUnavailable = connection ? connectionMethodUnavailable(connection, galleryEntry) : false;
|
||
|
||
return (
|
||
<Collapsible
|
||
open={open}
|
||
onOpenChange={(nextOpen) => {
|
||
setOpen(nextOpen);
|
||
if (!nextOpen) setConfirming(false);
|
||
}}
|
||
asChild
|
||
>
|
||
<section>
|
||
<CollapsibleTrigger asChild>
|
||
<button
|
||
type="button"
|
||
className="flex w-full items-center gap-3 py-1 text-left"
|
||
>
|
||
<span className="min-w-0 flex-1 text-sm font-medium text-destructive">Danger zone</span>
|
||
<ChevronRight
|
||
className={cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform", open && "rotate-90")}
|
||
/>
|
||
</button>
|
||
</CollapsibleTrigger>
|
||
|
||
<CollapsibleContent>
|
||
<div className="mt-3 divide-y divide-border border-t border-border">
|
||
{connection && onToggleConnection ? (
|
||
<div className="flex items-center justify-between gap-4 py-4">
|
||
<h2 className="text-sm font-medium text-foreground">Pause connection</h2>
|
||
<ToggleSwitch
|
||
aria-label="Pause connection"
|
||
checked={paused}
|
||
disabled={toggleDisabled}
|
||
onCheckedChange={onToggleConnection}
|
||
size="lg"
|
||
/>
|
||
</div>
|
||
) : null}
|
||
|
||
{connection && !methodUnavailable && connection.authKind !== "oauth" ? (
|
||
<div className="py-4">
|
||
<KeySection
|
||
connection={connection}
|
||
galleryEntry={galleryEntry}
|
||
onReplaced={onReplaced ?? (() => undefined)}
|
||
canReplace={canReplaceCredential}
|
||
unavailableMessage={credentialUnavailableMessage}
|
||
/>
|
||
</div>
|
||
) : null}
|
||
|
||
{connection?.authKind === "oauth" && !methodUnavailable && (onReconnectIdentity || !canReplaceCredential) ? (
|
||
<div className="flex flex-wrap items-center justify-between gap-3 py-4">
|
||
<div>
|
||
<p className="text-sm font-medium text-foreground">Reconnect</p>
|
||
<p className="text-xs text-muted-foreground">
|
||
{canReplaceCredential
|
||
? `Sign in to ${identityProviderName} again.`
|
||
: credentialUnavailableMessage}
|
||
</p>
|
||
</div>
|
||
{canReplaceCredential && onReconnectIdentity ? (
|
||
<Button
|
||
size="sm"
|
||
variant="outline"
|
||
disabled={identityActionPending}
|
||
onClick={onReconnectIdentity}
|
||
>
|
||
{identityActionPending ? <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" /> : null}
|
||
Reconnect
|
||
</Button>
|
||
) : null}
|
||
</div>
|
||
) : null}
|
||
|
||
{identityGrant?.capabilities?.canRevoke
|
||
&& identityGrant.status !== "revoked"
|
||
&& onRevokeIdentity ? (
|
||
<div className="flex flex-wrap items-center justify-between gap-3 py-4">
|
||
<div>
|
||
<p className="text-sm font-medium text-foreground">Revoke identity</p>
|
||
<p className="text-xs text-muted-foreground">
|
||
Disconnect the identity currently used by this app.
|
||
</p>
|
||
</div>
|
||
<Button
|
||
variant="destructive"
|
||
size="sm"
|
||
onClick={() => setRevokeTarget(identityGrant)}
|
||
>
|
||
Revoke
|
||
</Button>
|
||
</div>
|
||
) : null}
|
||
|
||
<div className="flex flex-wrap items-center justify-between gap-3 py-4">
|
||
<div>
|
||
<p className="text-sm font-medium text-foreground">Remove this app</p>
|
||
<p className="text-xs text-muted-foreground">
|
||
{`Deletes credentials for ${appName} and removes agent access. Reconnecting requires a new sign-in or key.`}
|
||
</p>
|
||
</div>
|
||
{confirming ? (
|
||
<div className="flex items-center gap-2">
|
||
<Button variant="ghost" size="sm" onClick={() => setConfirming(false)} disabled={removing}>
|
||
Cancel
|
||
</Button>
|
||
<Button variant="destructive" size="sm" onClick={onRemove} disabled={removing}>
|
||
{removing && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}
|
||
Yes, remove it
|
||
</Button>
|
||
</div>
|
||
) : (
|
||
<Button variant="destructive" size="sm" onClick={() => setConfirming(true)}>
|
||
Remove app
|
||
</Button>
|
||
)}
|
||
</div>
|
||
</div>
|
||
</CollapsibleContent>
|
||
|
||
{revokeTarget && credentialPolicy ? (
|
||
<RevokeGrantDialog
|
||
grant={revokeTarget}
|
||
providerName={identityProviderName}
|
||
pending={identityActionPending}
|
||
credentialPolicy={credentialPolicy}
|
||
isOwnIdentity={revokeTarget.kind === "user" && revokeTarget.subjectUserId === identityCurrentUserId}
|
||
onCancel={() => setRevokeTarget(null)}
|
||
onConfirm={() => {
|
||
onRevokeIdentity?.(revokeTarget);
|
||
setRevokeTarget(null);
|
||
}}
|
||
/>
|
||
) : null}
|
||
</section>
|
||
</Collapsible>
|
||
);
|
||
}
|
||
|
||
export function connectionAddress(connection: ToolConnection): string {
|
||
const config = connection.config ?? connection.transportConfig ?? {};
|
||
const value = config.url ?? config.endpoint ?? config.remoteUrl;
|
||
if (typeof value === "string" && value.trim().length > 0) return redactUrlSecrets(value);
|
||
if (connection.transport === "local_stdio") return "Local command";
|
||
return "Not set";
|
||
}
|
||
|
||
export function connectionTransportLabel(transport: ToolConnection["transport"]): string {
|
||
if (transport === "mcp_remote") return "Remote HTTP";
|
||
if (transport === "local_stdio") return "Local command";
|
||
return "Unknown";
|
||
}
|