Skip to content
Merged
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
60 changes: 60 additions & 0 deletions ProcessMaker/Managers/PluginManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,14 @@
*/
class PluginManager
{
/**
* Shown when the cloned repository has no plugin code yet, which is the normal state of a
* brand-new repository that the coding agent has not pushed the skeleton to.
*/
public const EMPTY_REPOSITORY_MESSAGE = 'The repository has no plugin code yet (there is no composer.json). '
. 'Push the plugin skeleton to it first (use "Copy prompt" in the Create Plugin dialog and let your '
. 'coding agent do it), then install again.';

/**
* Plugin directory created by the current install attempt.
* Removed if that attempt fails before setup finishes.
Expand Down Expand Up @@ -128,6 +136,12 @@ private function installPluginFiles(string $repoUrl, ?string $branch, ?string $t
$this->markNewInstallForRollback($pluginPath);
$this->cloneRepository($authenticatedRepoUrl, $pluginPath, $repoName, $userId, $repoUrl);

// An empty remote clones fine but `git checkout <branch>` would then fail with an obscure message.
if ($this->isEmptyGitRepository($pluginPath)) {
$this->logError(self::EMPTY_REPOSITORY_MESSAGE, $repoName, $userId);
throw new RuntimeException(self::EMPTY_REPOSITORY_MESSAGE);
}

if ($branch) {
$this->logRunning("Checking out branch: {$branch}", $repoName, $userId);
$this->checkoutBranch($pluginPath, $branch, $repoName, $userId);
Expand Down Expand Up @@ -851,6 +865,47 @@ protected function checkoutTag(string $pluginPath, string $tag, string $repoName
}
}

/**
* True when the plugin directory is a git clone without any commit (an empty remote).
*/
protected function isEmptyGitRepository(string $pluginPath): bool
{
if (!is_dir($pluginPath . '/.git')) {
return false;
}

return !Process::path($pluginPath)->timeout(30)->run(['git', 'rev-parse', '--verify', 'HEAD'])->successful();
}

/**
* True when the git clone only holds what hosting sites add to a new repository
* ("Initialize with README / license / .gitignore"), so there is no plugin code yet.
*/
protected function hasOnlyPlaceholderFiles(string $pluginPath): bool
{
if (!is_dir($pluginPath . '/.git')) {
return false;
}

$result = Process::path($pluginPath)->timeout(30)->run(['git', 'ls-files']);
if (!$result->successful()) {
return false;
}

$files = array_filter(array_map('trim', explode("\n", $result->output())));
if ($files === []) {
return false;
}

foreach ($files as $file) {
if (!preg_match('/^(README|LICENSE|LICENCE|COPYING|\.gitignore|\.gitattributes)(\.[A-Za-z]+)?$/i', $file)) {
return false;
}
}

return true;
}

/**
* Validate that the plugin has a valid composer.json structure.
*
Expand All @@ -863,6 +918,11 @@ protected function validatePlugin(string $pluginPath, string $repoName, ?int $us
$composerJsonPath = $pluginPath . '/composer.json';

if (!file_exists($composerJsonPath)) {
if ($this->isEmptyGitRepository($pluginPath) || $this->hasOnlyPlaceholderFiles($pluginPath)) {
$this->logError(self::EMPTY_REPOSITORY_MESSAGE, $repoName, $userId);
throw new RuntimeException(self::EMPTY_REPOSITORY_MESSAGE);
}

$this->logError('composer.json not found in plugin: ' . $pluginPath, $repoName, $userId);
throw new RuntimeException("composer.json not found in plugin: {$pluginPath}");
}
Expand Down
74 changes: 54 additions & 20 deletions resources/js/admin/plugins/Plugins.vue
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,13 @@
</div>
</div>
</div>
<small class="tw-block tw-text-gray-500 tw-mt-2">
{{
$t(
"The token is only used by ProcessMaker to clone private repositories. It is never included in the copied prompt."
)
}}
</small>
</b-collapse>

<div class="tw-grid tw-grid-cols-1 md:tw-grid-cols-2 tw-gap-3 tw-mb-3">
Expand Down Expand Up @@ -307,6 +314,15 @@
</div>
</div>

<p class="tw-text-xs tw-text-gray-500 tw-mb-3 tw-leading-relaxed">
<i class="fas fa-info-circle tw-mr-1" aria-hidden="true" />
{{
$t(
"New plugin? Use an empty repository (no README), copy the prompt and let your agent push the skeleton first, then save."
)
}}
</p>

<plugin-output
:user-id="userId"
:waiting="isRunning"
Expand All @@ -332,7 +348,7 @@
<p class="tw-text-sm tw-text-gray-600 tw-mb-4 tw-leading-relaxed">
{{
$t(
"Copy a ready-to-paste setup prompt for Claude, Cursor, or any coding agent. It connects this instance over MCP, loads ProcessMaker skills, and points the agent at the right endpoints."
"Copy a ready-to-paste setup prompt for Claude, Cursor, or any coding agent. It installs the prerequisites, creates your plugin from the skeleton, pushes it to the repository above, and connects this instance over MCP."
)
}}
</p>
Expand Down Expand Up @@ -456,7 +472,28 @@
</div>
</div>

<div class="tw-flex tw-flex-col sm:tw-flex-row tw-gap-2 tw-mt-5">
<fieldset class="tw-mt-4 tw-mb-0 tw-border-0 tw-p-0">
<legend class="tw-text-sm tw-font-medium tw-text-gray-700 tw-mb-1 tw-w-auto">
{{ $t("Project type") }}
</legend>
<div class="tw-flex tw-flex-col sm:tw-flex-row tw-gap-x-4 tw-gap-y-1">
<label
v-for="option in MCP_PROFILES"
:key="option.value"
class="tw-flex tw-items-center tw-gap-2 tw-text-sm tw-text-gray-700 tw-mb-0 tw-cursor-pointer"
>
<input
v-model="mcpProfile"
type="radio"
name="mcp-profile"
:value="option.value"
/>
{{ $t(option.label) }}
</label>
</div>
</fieldset>

<div class="tw-flex tw-flex-col sm:tw-flex-row tw-gap-2 tw-mt-4">
<button
type="button"
class="create-plugin-copy-prompt-btn tw-flex-1"
Expand Down Expand Up @@ -588,6 +625,7 @@ import Pagination from "../../components/common/Pagination";
import DataLoading from "../../components/common/DataLoading.vue";
import debounce from "lodash/debounce";
import PluginOutput from "./components/PluginOutput.vue";
import { buildMcpSetupPrompt } from "./mcpSetupPrompt";

const props = defineProps({
permission: {
Expand All @@ -614,6 +652,11 @@ const plugin = reactive({

const showGitCredentials = ref(false);
const showMcpPrompt = ref(false);
const MCP_PROFILES = [
{ value: "pm4", label: "PM4 only" },
{ value: "migration", label: "PM3 → PM4 migration" },
];
const mcpProfile = ref("pm4");
const promptCopied = ref(false);
const mcpFlowAnimating = ref(false);
const mcpStage = ref("idle");
Expand Down Expand Up @@ -1003,25 +1046,15 @@ const validatePluginForm = () => {
return Object.keys(nextErrors).length === 0;
};

// The Git token (plugin.gitToken) is deliberately not passed: it must never reach the prompt.
const mcpPrompt = computed(() => {
const origin = window.location.origin;
return [
"Configure my environment to use ProcessMaker MCP with this instance.",
"",
`Base URL: ${origin}`,
"MCP endpoints:",
`- ${origin}/mcp/screens`,
`- ${origin}/mcp/processes`,
`- ${origin}/mcp/data-connectors`,
`- ${origin}/mcp/flow-genies`,
"",
"1. Add ProcessMaker skills: npx skills add processmaker/skills",
"2. Connect the ProcessMaker MCP server(s) in my AI client (Cursor, Claude, VS Code, etc.) using OAuth against this instance.",
"3. Call get-mcp-guidance before other ProcessMaker MCP tools, then load only matching skills.",
"4. Help me install, develop, and use ProcessMaker plugins with these MCP tools.",
"",
"Do not invent MCP tool names; discover them from the connected servers.",
].join("\n");
return buildMcpSetupPrompt({
origin: window.location.origin,
repoUrl: plugin.url,
branch: plugin.branch,
username: plugin.gitUsername,
profile: mcpProfile.value,
});
});

const copyMcpPrompt = () => {
Expand Down Expand Up @@ -1319,6 +1352,7 @@ const resetValues = () => {
isDone.value = false;
promptCopied.value = false;
showMcpPrompt.value = false;
mcpProfile.value = "pm4";
initCustomModalButtons();
};

Expand Down
112 changes: 112 additions & 0 deletions resources/js/admin/plugins/mcpSetupPrompt.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
/**
* Builds the "Coding Agent Setup" prompt shown in the Create Plugin dialog.
*
* Pure functions, no Vue or DOM access, so the logic can be checked on its own.
*
* The prompt must never contain secrets: the Git token typed in the dialog is only used by
* ProcessMaker to clone private repositories and is deliberately not an input here, and any
* credentials embedded in the repository URL are stripped before it is used.
*/

export const MCP_ENDPOINT_PATHS = [
"/mcp/processes",
"/mcp/screens",
"/mcp/data-connectors",
"/mcp/flow-genies",
];

export const MCP_PROFILE_VALUES = ["pm4", "migration"];

// Values are typed by the user and end up inside a prompt, so drop all whitespace
// (URLs, branches and usernames never contain any) to keep each value on one line.
const clean = (value) => String(value ?? "").replace(/\s+/g, "");

/**
* Drops HTTP userinfo (https://user:secret@host/..., https://token@host/...) from a URL.
* Same two passes as PluginManager::redactHttpUserInfoFromString() in core: a pasted clone URL
* with credentials must never reach the prompt, the clipboard or the agent transcript.
*/
export function stripUrlUserInfo(value) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔒 Agentic Security Review

Severity: MEDIUM

Description: stripUrlUserInfo() does not remove HTTP userinfo when the pasted clone URL has an unencoded @ in the username. The first replace requires user:password with no @ in either part, and the second replace deletes only through the first @ and does not run again. https://user@domain.com:ghp_secret@github.com/org/repo.git therefore becomes https://domain.com:[REDACTED]@github.com/org/repo.git. That residual is still a normal user:password URL (username domain.com, password ghp_secret, host github.com). buildMcpSetupPrompt() writes it to PLUGIN_REPO, and Copy prompt / View prompt publish that string.

Impact: A manage-plugins admin who pastes an email-style clone URL (a form the Repository URL field accepts) and then copies the setup prompt still puts a live git password or PAT on the clipboard and into Claude, Cursor, or another agent. The prompt is built to be pasted there, and its own rules say a git token must not enter that chat. The separate Token field is excluded; this path leaks the credential embedded in plugin.url. Git and the WHATWG URL parser both treat the leftover URL as authenticated userinfo, so the agent can reuse it.

Remediation: Parse the repository URL with the URL constructor and rebuild it with username and password cleared, repeating until both are empty. If parsing fails or the serialized URL still contains userinfo, omit PLUGIN_REPO from the prompt instead of embedding it. Do not treat the two-pass userinfo regular expression as the redaction gate.

return clean(value)
.replace(/:\/\/[^/\s:@]+:[^/\s@]+@/g, "://")
.replace(/:\/\/[^/\s@]+@/g, "://");
}

/**
* Same rule as PluginManager::extractRepoName() in core: core installs the plugin as
* storage/plugins/{repoName} and runs `{repoName}:install`, so the plugin folder created
* from package-skeleton must carry exactly this name.
*/
export function extractRepoName(repoUrl) {
const url = clean(repoUrl).replace(/(\.git|\/)$/, "");
const match = url.match(/\/([^/]+)$/);
return match ? match[1] : "";
}

/** True for an https URL that has a path (https://host/org/repo), the only kind core installs. */
export function isUsableRepoUrl(repoUrl) {
try {
const parsed = new URL(clean(repoUrl));
return parsed.protocol === "https:" && parsed.pathname.replace(/\/+$/, "") !== "";
} catch (e) {
return false;
}
}

/**
* @param {object} options
* @param {string} options.origin ProcessMaker instance URL (window.location.origin)
* @param {string} [options.repoUrl]
* @param {string} [options.branch]
* @param {string} [options.username]
* @param {string} [options.profile] "pm4" or "migration"
* @returns {string}
*/
export function buildMcpSetupPrompt({
origin,
repoUrl = "",
branch = "",
username = "",
profile = "pm4",
}) {
const base = clean(origin).replace(/\/+$/, "");
const url = stripUrlUserInfo(repoUrl);
const repoName = isUsableRepoUrl(url) ? extractRepoName(url) : "";

const values = [
["PM_BASE_URL", base],
["PLUGIN_REPO", url || "<ask me for the repository URL>"],
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
["PLUGIN_NAME", repoName || "<repository name>"],
["PLUGIN_BRANCH", clean(branch) || "main"],
["GIT_USERNAME", clean(username) || "<my local git config>"],
["PROFILE", MCP_PROFILE_VALUES.includes(profile) ? profile : "pm4"],
];
const width = Math.max(...values.map(([name]) => name.length));

return [
"Set up a ProcessMaker plugin workspace for this instance.",
"",
"Values (PLUGIN_NAME must equal the repository name):",
...values.map(([name, value]) => ` ${name.padEnd(width)} = ${value}`),
"",
"Before anything else, check `git --version` and `node -v` (Node >= 22; 24 is recommended).",
"If one is missing, show me the install command for my OS and wait for my confirmation before running it.",
"",
"Then install the setup skill and follow it with the values above:",
" npx skills add processmaker/skills -y --skill pm4-plugin-setup",
"",
"The skill checks PHP and Composer, scaffolds the plugin from package-skeleton, builds it,",
"commits it (including the public/ folder) and pushes it to PLUGIN_REPO with my local git credentials.",
"",
"MCP endpoints (authorize them with OAuth in my IDE; no token is needed):",
...MCP_ENDPOINT_PATHS.map((path) => ` - ${base}${path}`),
"",
"Rules:",
"- Never ask me to paste a git token or an API token in this chat.",
" Tell me to add my ProcessMaker API token to .env as PM_SYNC_TOKEN myself.",
"- Call get-mcp-guidance before other ProcessMaker MCP tools, then load only the matching skills.",
"- Do not invent MCP tool names; discover them from the connected servers.",
"- When you are done, summarize what passed and tell me to open Admin > Plugins, click Plugin,",
" enter PLUGIN_REPO and PLUGIN_BRANCH, and click Save.",
].join("\n");
}
Loading
Loading