Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 88 additions & 6 deletions mcpjam-inspector/client/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,48 @@ function clearHostedCallbackRetryState() {
}
}

const OAUTH_DEBUGGER_SECRET_PATTERNS = [
/\b(access_token|refresh_token|id_token|client_secret|clientSecret|code_verifier|code|state)\b(\s*[:=]\s*)("[^"]*"|'[^']*'|[^\s&,;]+)/gi,
/\bBearer\s+[A-Za-z0-9._~+/=-]+\b/gi,
/\bBasic\s+[A-Za-z0-9+/=._~-]+\b/gi,
];

function sanitizeOAuthDebuggerText(value: string | null | undefined): string {
if (!value) {
return "";
}

return OAUTH_DEBUGGER_SECRET_PATTERNS.reduce(
(sanitized, pattern) =>
sanitized.replace(pattern, (...args) => {
const key = typeof args[1] === "string" ? args[1] : undefined;
const separator = typeof args[2] === "string" ? args[2] : undefined;
return key && separator ? `${key}${separator}[redacted]` : "[redacted]";
}),
value,
);
}

function sanitizeOAuthDebuggerError(error: Error | null) {
return {
name: sanitizeOAuthDebuggerText(error?.name ?? "Error"),
message: sanitizeOAuthDebuggerText(error?.message ?? "Unknown error"),
stack: sanitizeOAuthDebuggerText(error?.stack),
};
}

function formatOAuthDebuggerErrorDetails(error: Error | null): string {
const sanitized = sanitizeOAuthDebuggerError(error);
return [
"OAuth Debugger error",
`Name: ${sanitized.name}`,
`Message: ${sanitized.message}`,
sanitized.stack ? `Stack:\n${sanitized.stack}` : "",
]
.filter(Boolean)
.join("\n\n");
}

function BillingHandoffLoading({ overlay = false }: { overlay?: boolean }) {
return (
<div
Expand Down Expand Up @@ -2139,12 +2181,52 @@ export default function App() {

{activeTab === "oauth-flow" && (
<ErrorBoundary
fallback={
<div className="flex items-center justify-center h-full text-muted-foreground">
Something went wrong in the OAuth Debugger. Try refreshing the
page.
</div>
}
fallback={({ error, reset }) => {
const copyDetails = () => {
const details = formatOAuthDebuggerErrorDetails(error);
void navigator.clipboard
?.writeText(details)
.then(() => toast.success("Copied OAuth debugger error"))
.catch(() =>
Comment on lines +2187 to +2190
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Guard clipboard write before chaining

When navigator.clipboard is unavailable (e.g., insecure context or restricted browser), navigator.clipboard?.writeText(details) evaluates to undefined, and the following .then(...) access throws a TypeError. This makes the “Copy details” action crash instead of gracefully reporting that copy is unavailable.

Useful? React with 👍 / 👎.

toast.error("Could not copy OAuth debugger error"),
);
Comment on lines +2187 to +2192
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

# First, check if the file exists and get its basic info
git ls-files | grep -E "mcpjam-inspector/client.*App\.tsx"

Repository: MCPJam/inspector

Length of output: 96


🏁 Script executed:

# Get the specific lines mentioned in the review (2187-2192)
if [ -f "mcpjam-inspector/client/src/App.tsx" ]; then
  echo "=== Lines 2187-2192 ===" 
  sed -n '2185,2195p' "mcpjam-inspector/client/src/App.tsx"
fi

Repository: MCPJam/inspector

Length of output: 539


🏁 Script executed:

# Get broader context around copyDetails function
if [ -f "mcpjam-inspector/client/src/App.tsx" ]; then
  echo "=== Searching for copyDetails function ===" 
  grep -n "copyDetails" "mcpjam-inspector/client/src/App.tsx" | head -20
fi

Repository: MCPJam/inspector

Length of output: 230


Prevent unhandled errors when Clipboard API is unavailable.

navigator.clipboard?.writeText() returns undefined when the API is unavailable, and chaining .then() on undefined throws a TypeError, breaking the copy action in restricted environments.

🛠️ Safe async handling
-                const copyDetails = () => {
+                const copyDetails = async () => {
                   const details = formatOAuthDebuggerErrorDetails(error);
-                  void navigator.clipboard
-                    ?.writeText(details)
-                    .then(() => toast.success("Copied OAuth debugger error"))
-                    .catch(() =>
-                      toast.error("Could not copy OAuth debugger error"),
-                    );
+                  try {
+                    if (!navigator.clipboard?.writeText) {
+                      throw new Error("Clipboard API unavailable");
+                    }
+                    await navigator.clipboard.writeText(details);
+                    toast.success("Copied OAuth debugger error");
+                  } catch {
+                    toast.error("Could not copy OAuth debugger error");
+                  }
                 };
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@mcpjam-inspector/client/src/App.tsx` around lines 2187 - 2192, The current
call to navigator.clipboard?.writeText(details) may return undefined and cause a
TypeError when chaining .then(); update the copy logic to first test that
navigator.clipboard and navigator.clipboard.writeText are available (or wrap the
result with Promise.resolve) before calling .then/.catch, and if unavailable
immediately call toast.error("Could not copy OAuth debugger error"); locate the
snippet using navigator.clipboard?.writeText(details) and the toast.success /
toast.error calls to implement the guard and safe async handling.

};

return (
<div className="flex h-full items-center justify-center p-6">
<div className="max-w-md space-y-4 text-center">
<AlertTriangle className="mx-auto size-10 text-destructive" />
<div className="space-y-2">
<h2 className="text-lg font-semibold">
OAuth Debugger crashed
</h2>
<p className="text-sm text-muted-foreground">
{sanitizeOAuthDebuggerError(error).message}
</p>
</div>
<div className="flex justify-center gap-2">
<Button variant="outline" onClick={reset}>
Try again
</Button>
<Button variant="outline" onClick={copyDetails}>
Copy details
</Button>
</div>
</div>
</div>
);
}}
onError={(error, errorInfo) => {
const sanitizedError = sanitizeOAuthDebuggerError(error);
posthog.capture("oauth_debugger_error_boundary", {
name: sanitizedError.name,
message: sanitizedError.message,
stack: sanitizedError.stack,
componentStack: sanitizeOAuthDebuggerText(
errorInfo.componentStack,
),
});
}}
>
<OAuthFlowTab
serverConfigs={appState.servers}
Expand Down
53 changes: 52 additions & 1 deletion mcpjam-inspector/client/src/__tests__/App.hosted-oauth.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ const {
mockHeader,
mockHostedShellGateState,
mockMCPSidebar,
mockOAuthFlowTabState,
mockOrganizationsTab,
mockPosthogCapture,
mockPosthogState,
Expand Down Expand Up @@ -121,6 +122,10 @@ const {
| "logged-out",
},
mockMCPSidebar: vi.fn(() => <div />),
mockOAuthFlowTabState: {
shouldThrow: false,
error: new Error("OAuth debugger failed"),
},
mockOrganizationsTab: vi.fn(() => <div />),
mockPosthogCapture: vi.fn(),
mockPosthogState: {
Expand Down Expand Up @@ -289,7 +294,12 @@ vi.mock("../components/AuthTab", () => ({
AuthTab: () => <div />,
}));
vi.mock("../components/OAuthFlowTab", () => ({
OAuthFlowTab: () => <div />,
OAuthFlowTab: () => {
if (mockOAuthFlowTabState.shouldThrow) {
throw mockOAuthFlowTabState.error;
}
return <div data-testid="oauth-flow-tab" />;
},
}));
vi.mock("../components/xaa/XAAFlowTab", () => ({
XAAFlowTab: () => <div data-testid="xaa-flow-tab">XAA Debugger Tab</div>,
Expand Down Expand Up @@ -426,6 +436,8 @@ describe("App hosted OAuth callback handling", () => {
));
mockMCPSidebar.mockReset();
mockMCPSidebar.mockImplementation(() => <div data-testid="mcp-sidebar" />);
mockOAuthFlowTabState.shouldThrow = false;
mockOAuthFlowTabState.error = new Error("OAuth debugger failed");
mockPosthogCapture.mockReset();
mockAppBuilderTabMounts.mockReset();
mockCompleteHostedOAuthCallback.mockImplementation(
Expand Down Expand Up @@ -502,6 +514,45 @@ describe("App hosted OAuth callback handling", () => {
});
});

it("captures and copies sanitized OAuth Debugger boundary errors", async () => {
clearHostedOAuthPendingState();
clearChatboxSession();
localStorage.clear();
sessionStorage.clear();
window.history.replaceState({}, "", "/#oauth-flow");
mockOAuthFlowTabState.shouldThrow = true;
mockOAuthFlowTabState.error = new Error(
"token exchange failed client_secret=super-secret Bearer access-token",
);
const writeText = vi.fn().mockResolvedValue(undefined);
vi.stubGlobal("navigator", {
...window.navigator,
clipboard: { writeText },
});

render(<App />);

expect(await screen.findByText("OAuth Debugger crashed")).toBeInTheDocument();
expect(mockPosthogCapture).toHaveBeenCalledWith(
"oauth_debugger_error_boundary",
expect.objectContaining({
message: expect.stringContaining("[redacted]"),
}),
);
expect(
JSON.stringify(mockPosthogCapture.mock.calls),
).not.toContain("super-secret");

fireEvent.click(screen.getByRole("button", { name: /copy details/i }));

await waitFor(() => {
expect(writeText).toHaveBeenCalledWith(
expect.not.stringContaining("super-secret"),
);
});
expect(writeText.mock.calls[0]?.[0]).toContain("[redacted]");
});

it("uses hosted completion for guest chatbox session callbacks", async () => {
mockConvexAuthState.isAuthenticated = false;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,9 @@ export function AddServerModal({
if (initialData.clientSecret) {
formState.setClientSecret(initialData.clientSecret);
}
if (initialData.hasClientSecret) {
formState.setHasStoredClientSecret(true);
}
} else if (initialData.headers) {
const authorizationHeader = getAuthorizationHeaderValue(
initialData.headers,
Expand Down Expand Up @@ -399,6 +402,9 @@ export function AddServerModal({
if (!checked) {
formState.setClientId("");
formState.setClientSecret("");
if (formState.hasStoredClientSecret) {
formState.setClearClientSecret(true);
}
formState.setClientIdError(null);
formState.setClientSecretError(null);
}
Expand All @@ -412,9 +418,18 @@ export function AddServerModal({
clientSecret={formState.clientSecret}
onClientSecretChange={(value) => {
formState.setClientSecret(value);
if (value.trim()) {
formState.setClearClientSecret(false);
}
const error = formState.validateClientSecret(value);
formState.setClientSecretError(error);
}}
hasStoredClientSecret={formState.hasStoredClientSecret}
clearClientSecret={formState.clearClientSecret}
onClearClientSecret={() => formState.setClearClientSecret(true)}
onUndoClearClientSecret={() =>
formState.setClearClientSecret(false)
}
clientIdError={formState.clientIdError}
clientSecretError={formState.clientSecretError}
/>
Expand Down Expand Up @@ -452,6 +467,7 @@ export function AddServerModal({
onAddHeader: formState.addCustomHeader,
onRemoveHeader: formState.removeCustomHeader,
onUpdateHeader: formState.updateCustomHeader,
headersWarning: formState.oauthAuthorizationHeaderWarning,
}
: {})}
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,15 @@ import { HOSTED_MODE } from "@/lib/config";
interface EditServerFormContentProps {
formState: ReturnType<typeof useServerForm>;
isDuplicateServerName: boolean;
workspaceId?: string | null;
hostedServerId?: string | null;
}

export function EditServerFormContent({
formState,
isDuplicateServerName,
workspaceId = null,
hostedServerId = null,
}: EditServerFormContentProps) {
const hostedUrlPlaceholder = "https://example.com/mcp";

Expand Down Expand Up @@ -155,6 +159,9 @@ export function EditServerFormContent({
if (!checked) {
formState.setClientId("");
formState.setClientSecret("");
if (formState.hasStoredClientSecret) {
formState.setClearClientSecret(true);
}
formState.setClientIdError(null);
formState.setClientSecretError(null);
}
Expand All @@ -168,11 +175,22 @@ export function EditServerFormContent({
clientSecret={formState.clientSecret}
onClientSecretChange={(value) => {
formState.setClientSecret(value);
if (value.trim()) {
formState.setClearClientSecret(false);
}
const error = formState.validateClientSecret(value);
formState.setClientSecretError(error);
}}
hasStoredClientSecret={formState.hasStoredClientSecret}
clearClientSecret={formState.clearClientSecret}
onClearClientSecret={() => formState.setClearClientSecret(true)}
onUndoClearClientSecret={() =>
formState.setClearClientSecret(false)
}
clientIdError={formState.clientIdError}
clientSecretError={formState.clientSecretError}
workspaceId={workspaceId}
hostedServerId={hostedServerId}
/>
</div>
)}
Expand Down Expand Up @@ -220,6 +238,7 @@ export function EditServerFormContent({
onAddHeader: formState.addCustomHeader,
onRemoveHeader: formState.removeCustomHeader,
onUpdateHeader: formState.updateCustomHeader,
headersWarning: formState.oauthAuthorizationHeaderWarning,
}
: {})}
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,8 @@ export function ServerDetailModal({
<EditServerFormContent
formState={formState}
isDuplicateServerName={isDuplicateServerName}
workspaceId={workspaceId}
hostedServerId={hostedServerId}
/>
</div>
</TabsContent>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -142,4 +142,53 @@ describe("AuthenticationSection", () => {
screen.getByText("Client ID Metadata Documents (CIMD)"),
).toBeInTheDocument();
});

it("shows stored client secret metadata with clear and undo actions", () => {
const onClearClientSecret = vi.fn();
const onUndoClearClientSecret = vi.fn();
const props = {
serverUrl: "https://example.com/mcp",
authType: "oauth" as const,
onAuthTypeChange: vi.fn(),
showAuthSettings: true,
bearerToken: "",
onBearerTokenChange: vi.fn(),
oauthScopesInput: "",
onOauthScopesChange: vi.fn(),
oauthProtocolMode: "2025-11-25" as const,
onOauthProtocolModeChange: vi.fn(),
oauthRegistrationMode: "preregistered" as const,
onOauthRegistrationModeChange: vi.fn(),
useCustomClientId: true,
onUseCustomClientIdChange: vi.fn(),
clientId: "client-id",
onClientIdChange: vi.fn(),
clientSecret: "",
onClientSecretChange: vi.fn(),
hasStoredClientSecret: true,
clientIdError: null,
clientSecretError: null,
onClearClientSecret,
onUndoClearClientSecret,
};

const { rerender } = render(<AuthenticationSection {...props} />);

fireEvent.click(screen.getByRole("button", { name: /advanced settings/i }));

expect(
screen.getByPlaceholderText("Enter a new value to replace."),
).toBeInTheDocument();

fireEvent.click(screen.getByRole("button", { name: "Clear" }));
expect(onClearClientSecret).toHaveBeenCalledTimes(1);

rerender(<AuthenticationSection {...props} clearClientSecret={true} />);

expect(
screen.getByText("Saved client secret will be removed when you save."),
).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Undo" }));
expect(onUndoClearClientSecret).toHaveBeenCalledTimes(1);
});
});
Loading
Loading