fix: harden plugin command registration + telegram menu guard (#31997) (thanks @liuxiaopai-ai)

This commit is contained in:
Peter Steinberger
2026-03-02 19:04:19 +00:00
parent 0958d11478
commit ee68fa86b5
3 changed files with 79 additions and 5 deletions

View File

@@ -0,0 +1,61 @@
import { afterEach, describe, expect, it } from "vitest";
import {
clearPluginCommands,
getPluginCommandSpecs,
listPluginCommands,
registerPluginCommand,
} from "./commands.js";
afterEach(() => {
clearPluginCommands();
});
describe("registerPluginCommand", () => {
it("rejects malformed runtime command shapes", () => {
const invalidName = registerPluginCommand(
"demo-plugin",
// Runtime plugin payloads are untyped; guard at boundary.
{
name: undefined as unknown as string,
description: "Demo",
handler: async () => ({ text: "ok" }),
},
);
expect(invalidName).toEqual({
ok: false,
error: "Command name must be a string",
});
const invalidDescription = registerPluginCommand("demo-plugin", {
name: "demo",
description: undefined as unknown as string,
handler: async () => ({ text: "ok" }),
});
expect(invalidDescription).toEqual({
ok: false,
error: "Command description must be a string",
});
});
it("normalizes command metadata for downstream consumers", () => {
const result = registerPluginCommand("demo-plugin", {
name: " demo_cmd ",
description: " Demo command ",
handler: async () => ({ text: "ok" }),
});
expect(result).toEqual({ ok: true });
expect(listPluginCommands()).toEqual([
{
name: "demo_cmd",
description: "Demo command",
pluginId: "demo-plugin",
},
]);
expect(getPluginCommandSpecs()).toEqual([
{
name: "demo_cmd",
description: "Demo command",
},
]);
});
});

View File

@@ -119,23 +119,36 @@ export function registerPluginCommand(
return { ok: false, error: "Command handler must be a function" };
}
const validationError = validateCommandName(command.name);
if (typeof command.name !== "string") {
return { ok: false, error: "Command name must be a string" };
}
if (typeof command.description !== "string") {
return { ok: false, error: "Command description must be a string" };
}
const name = command.name.trim();
const description = command.description.trim();
if (!description) {
return { ok: false, error: "Command description cannot be empty" };
}
const validationError = validateCommandName(name);
if (validationError) {
return { ok: false, error: validationError };
}
const key = `/${command.name.toLowerCase()}`;
const key = `/${name.toLowerCase()}`;
// Check for duplicate registration
if (pluginCommands.has(key)) {
const existing = pluginCommands.get(key)!;
return {
ok: false,
error: `Command "${command.name}" already registered by plugin "${existing.pluginId}"`,
error: `Command "${name}" already registered by plugin "${existing.pluginId}"`,
};
}
pluginCommands.set(key, { ...command, pluginId });
pluginCommands.set(key, { ...command, name, description, pluginId });
logVerbose(`Registered plugin command: ${key} (plugin: ${pluginId})`);
return { ok: true };
}