Skip to content
Draft
Show file tree
Hide file tree
Changes from all 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
14 changes: 13 additions & 1 deletion apps/cursor/src/actions/create-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import { revalidatePath } from "next/cache";
import { z } from "zod";
import { resolveGithubRepoIdFromRepository } from "@/lib/github-plugin/parse";
import { InsertPluginError, insertPlugin } from "@/lib/plugins/insert";
import { pluginScanLimit } from "@/lib/rate-limit";
import { ActionError, authActionClient } from "./safe-action";
Expand Down Expand Up @@ -62,6 +63,12 @@ export const createPluginAction = authActionClient
);
}

// Never trust a client-supplied github_repo_id — resolve from the
// repository URL via GitHub so squatters cannot block idempotent imports.
const githubRepoId = await resolveGithubRepoIdFromRepository(repository, {
maxWaitMs: 3000,
});

let result: { id: string; slug: string };
try {
result = await insertPlugin(
Expand All @@ -74,7 +81,12 @@ export const createPluginAction = authActionClient
keywords,
components,
},
{ ownerId: userId, source: "user", skipScan: false },
{
ownerId: userId,
source: "user",
skipScan: false,
githubRepoId,
},
Comment thread
cursor[bot] marked this conversation as resolved.
);
} catch (err) {
if (err instanceof InsertPluginError) {
Expand Down
34 changes: 9 additions & 25 deletions apps/cursor/src/actions/star-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@

import { revalidatePath } from "next/cache";
import { z } from "zod";
import { createClient as createAdminClient } from "@/utils/supabase/admin-client";
import { createClient } from "@/utils/supabase/server";
import { authActionClient } from "./safe-action";
import { ActionError, authActionClient } from "./safe-action";

export const starPluginAction = authActionClient
.metadata({
Expand All @@ -16,32 +15,17 @@ export const starPluginAction = authActionClient
slug: z.string(),
}),
)
.action(async ({ parsedInput: { pluginId, slug }, ctx: { userId } }) => {
.action(async ({ parsedInput: { pluginId, slug } }) => {
// User-scoped client so `auth.uid()` inside the SECURITY DEFINER RPC
// authorizes against the caller, not the service role.
const supabase = await createClient();

const { data: existing } = await supabase
.from("plugin_stars")
.select("plugin_id")
.eq("plugin_id", pluginId)
.eq("user_id", userId)
.maybeSingle();
const { error } = await supabase.rpc("toggle_plugin_star", {
plugin_id_input: pluginId,
});

const admin = await createAdminClient();

if (existing) {
await supabase
.from("plugin_stars")
.delete()
.eq("plugin_id", pluginId)
.eq("user_id", userId);

await admin.rpc("decrement_star_count", { plugin_id_input: pluginId });
} else {
await supabase
.from("plugin_stars")
.insert({ plugin_id: pluginId, user_id: userId });

await admin.rpc("increment_star_count", { plugin_id_input: pluginId });
if (error) {
throw new ActionError(`Failed to update star: ${error.message}`);
}

revalidatePath("/");
Expand Down
195 changes: 162 additions & 33 deletions apps/cursor/src/actions/update-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,100 @@ const componentSchema = z.object({
metadata: z.record(z.string(), z.unknown()).optional(),
});

type ComponentInput = z.infer<typeof componentSchema>;

type ExistingComponent = {
type: string;
name: string;
slug: string;
description: string | null;
content: string | null;
metadata: Record<string, unknown> | null;
sort_order: number;
};

function slugify(value: string): string {
return value
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "");
}

function componentKey(type: string, slug: string): string {
return `${type}:${slug}`;
}

// Only fields that affect the install payload — cosmetic edits to name,
// description, or sort_order must not trigger a rescan. MCP install links and
// configs can live in metadata, so compare the metadata that will be saved.
function fingerprintComponent(c: {
type: string;
slug?: string | null;
name: string;
content?: string | null;
metadata?: Record<string, unknown> | null;
}): string {
const slug = c.slug || slugify(c.name);
return JSON.stringify({
type: c.type,
slug,
content: c.content ?? "",
metadata: c.metadata ?? {},
});
}

function resolveComponentMetadata(
comp: ComponentInput,
prevByKey: Map<string, ExistingComponent>,
): Record<string, unknown> {
const slug = comp.slug || slugify(comp.name);
const submitted = comp.metadata;
if (submitted && Object.keys(submitted).length > 0) {
return submitted;
}
const prev = prevByKey.get(componentKey(comp.type, slug));
return prev?.metadata ?? {};
}

function installRelevantChanged(
prevComponents: ExistingComponent[],
prevRepository: string | null,
nextComponents: ComponentInput[],
nextRepository: string | null,
): boolean {
if ((prevRepository ?? null) !== (nextRepository ?? null)) {
return true;
}

if (prevComponents.length !== nextComponents.length) {
return true;
}

const prevSorted = [...prevComponents]
.sort((a, b) => a.sort_order - b.sort_order)
.map(fingerprintComponent)
.sort();
const prevByKey = new Map(
prevComponents.map((c) => [
componentKey(c.type, c.slug || slugify(c.name)),
c,
]),
);
const nextSorted = nextComponents
.map((component) =>
fingerprintComponent({
...component,
metadata: resolveComponentMetadata(component, prevByKey),
}),
)
.sort();

for (let i = 0; i < prevSorted.length; i++) {
if (prevSorted[i] !== nextSorted[i]) return true;
}
return false;
}
Comment thread
cursor[bot] marked this conversation as resolved.

export const updatePluginAction = authActionClient
.metadata({
actionName: "update-plugin",
Expand Down Expand Up @@ -62,7 +156,9 @@ export const updatePluginAction = authActionClient

const { data: existing, error: fetchError } = await supabase
.from("plugins")
.select("id, owner_id, slug")
.select(
"id, owner_id, slug, repository, github_repo_id, active, plugin_components(type, name, slug, description, content, metadata, sort_order)",
)
.eq("id", id)
.single();

Expand All @@ -83,16 +179,45 @@ export const updatePluginAction = authActionClient
);
}

// Source URL is pinned to the parsed GitHub repo so an owner can't keep
// the verified-looking badge while swapping the install payload.
const repositoryLocked = existing.github_repo_id != null;
const effectiveRepository = repositoryLocked
? (existing.repository ?? null)
: (repository ?? null);

const prevComponents = (existing.plugin_components ??
[]) as ExistingComponent[];

const installChanged = installRelevantChanged(
prevComponents,
existing.repository ?? null,
components,
effectiveRepository,
);

const shouldRescan = installChanged;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Scan quota on cosmetic edits

Medium Severity · Logic Bug

pluginScanLimit (5/hour per user per firewall config) still runs on every update before shouldRescan is computed. Cosmetic-only saves no longer enqueue scans, but they still consume the scan rate limit and can block further edits with “Too many plugin updates in the last hour.”

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 1ccb658. Configure here.

const updatePayload: Record<string, unknown> = {
name,
description,
logo: logo || null,
repository: effectiveRepository,
homepage: homepage || null,
keywords: keywords || [],
};

if (shouldRescan && existing.active) {
updatePayload.active = false;
updatePayload.scan_status = "pending";
updatePayload.flag_summary = null;
updatePayload.flag_reasons = [];
updatePayload.flag_severity = null;
updatePayload.flagged_at = null;
}
Comment thread
cursor[bot] marked this conversation as resolved.

const { error: updateError } = await supabase
.from("plugins")
.update({
name,
description,
logo: logo || null,
repository: repository || null,
homepage: homepage || null,
keywords: keywords || [],
})
.update(updatePayload)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Delist before components saved

High Severity · Logic Bug

When an install-relevant edit runs on an active plugin, the row is set active=false and scan fields reset before components are deleted and re-inserted. If the component insert fails after the delete succeeds, the plugin stays delisted with no components, even though the action returns an error.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 1ccb658. Configure here.

.eq("id", id);

if (updateError) {
Expand All @@ -117,25 +242,24 @@ export const updatePluginAction = authActionClient
);
}

type ComponentInput = z.infer<typeof componentSchema>;
const componentRows = components.map(
(comp: ComponentInput, i: number) => ({
plugin_id: id,
type: comp.type,
name: comp.name,
slug:
comp.slug ||
comp.name
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, ""),
description: comp.description || null,
content: comp.content || null,
metadata: comp.metadata || {},
sort_order: i,
}),
const prevByKey = new Map(
prevComponents.map((c) => [
componentKey(c.type, c.slug || slugify(c.name)),
c,
]),
);

const componentRows = components.map((comp, i) => ({
plugin_id: id,
type: comp.type,
name: comp.name,
slug: comp.slug || slugify(comp.name),
description: comp.description || null,
content: comp.content || null,
metadata: resolveComponentMetadata(comp, prevByKey),
sort_order: i,
}));

const { error: compError } = await supabase
.from("plugin_components")
.insert(componentRows);
Expand All @@ -145,17 +269,22 @@ export const updatePluginAction = authActionClient
`Failed to save plugin components: ${compError.message}`,
);
}

try {
await enqueuePluginScan(id);
kickDrainAfterResponse();
} catch (queueError) {
console.error("Failed to enqueue plugin scan", queueError);
if (shouldRescan) {
try {
await enqueuePluginScan(id);
kickDrainAfterResponse();
} catch (queueError) {
console.error("Failed to enqueue plugin scan", queueError);
}
}

revalidatePath("/");
revalidatePath(`/plugins/${existing.slug}`);

return { slug: existing.slug };
return {
slug: existing.slug,
rescanQueued: shouldRescan,
repositoryLocked,
};
},
);
20 changes: 15 additions & 5 deletions apps/cursor/src/components/forms/edit-plugin-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ export function EditPluginForm({ data }: { data: PluginRow }) {
const [description, setDescription] = useState(data.description ?? "");
const [logo, setLogo] = useState<string | null>(data.logo);
const [repository, setRepository] = useState(data.repository ?? "");
const repositoryLocked = data.github_repo_id != null;
const [homepage, setHomepage] = useState(data.homepage ?? "");
const [keywords, setKeywords] = useState(data.keywords.join(", "));
const [components, setComponents] = useState<EditableComponent[]>(
Expand Down Expand Up @@ -127,7 +128,9 @@ export function EditPluginForm({ data }: { data: PluginRow }) {
name: name.trim(),
description: description.trim(),
logo,
repository: repository.trim() || null,
repository: repositoryLocked
? (data.repository ?? null)
: repository.trim() || null,
homepage: homepage.trim() || null,
keywords: keywords
.split(",")
Expand All @@ -139,7 +142,6 @@ export function EditPluginForm({ data }: { data: PluginRow }) {
slug: slugify(c.name),
description: c.description.trim() || undefined,
content: c.content.trim() || undefined,
metadata: {},
})),
});
};
Expand Down Expand Up @@ -183,15 +185,23 @@ export function EditPluginForm({ data }: { data: PluginRow }) {
<label className="mb-1.5 block text-sm font-medium">
Repository URL
<span className="ml-1 font-normal text-muted-foreground">
(optional)
{repositoryLocked ? "(locked to GitHub source)" : "(optional)"}
</span>
</label>
<Input
value={repository}
onChange={(e) => setRepository(e.target.value)}
onChange={(e) => !repositoryLocked && setRepository(e.target.value)}
readOnly={repositoryLocked}
placeholder="https://github.com/you/your-plugin"
className="border-border placeholder:text-[#878787]"
className="border-border placeholder:text-[#878787] read-only:cursor-not-allowed read-only:opacity-70"
/>
{repositoryLocked && (
<p className="mt-1.5 text-xs text-muted-foreground">
This plugin was imported from GitHub, so the Source link is locked
to that repository to keep the displayed source consistent with
the install payload.
</p>
)}
</div>
<div>
<label className="mb-1.5 block text-sm font-medium">
Expand Down
1 change: 1 addition & 0 deletions apps/cursor/src/components/forms/plugin-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ type ParsedPlugin = {
author_name?: string;
author_url?: string;
author_avatar?: string;
github_repo_id?: number;
components: ParsedComponent[];
};

Expand Down
Loading