diff --git a/docs/architecture/tla/CommandFrontmatter.NoBomStrip.cfg b/docs/architecture/tla/Frontmatter.NoBomStrip.cfg similarity index 100% rename from docs/architecture/tla/CommandFrontmatter.NoBomStrip.cfg rename to docs/architecture/tla/Frontmatter.NoBomStrip.cfg diff --git a/docs/architecture/tla/CommandFrontmatter.None.cfg b/docs/architecture/tla/Frontmatter.None.cfg similarity index 100% rename from docs/architecture/tla/CommandFrontmatter.None.cfg rename to docs/architecture/tla/Frontmatter.None.cfg diff --git a/docs/architecture/tla/CommandFrontmatter.cfg b/docs/architecture/tla/Frontmatter.cfg similarity index 100% rename from docs/architecture/tla/CommandFrontmatter.cfg rename to docs/architecture/tla/Frontmatter.cfg diff --git a/docs/architecture/tla/CommandFrontmatter.tla b/docs/architecture/tla/Frontmatter.tla similarity index 62% rename from docs/architecture/tla/CommandFrontmatter.tla rename to docs/architecture/tla/Frontmatter.tla index da5496a177..6f85db78c5 100644 --- a/docs/architecture/tla/CommandFrontmatter.tla +++ b/docs/architecture/tla/Frontmatter.tla @@ -1,16 +1,19 @@ ----- MODULE CommandFrontmatter ---- -\* Models parseCommandFrontmatter (src/services/command/commands.ts). -\* Both callers, scanCommandDirectory and tryLoadCommand, use it. The property test covers both. -\* Source: the header language in a workspace command file. Sink: the gray-matter engine call. -\* Failure: a command file header selects an executable engine and the extension runs its code. +---- MODULE Frontmatter ---- +\* Models parseFrontmatter (src/utils/safeFrontmatter.ts). +\* Callers: scanCommandDirectory, tryLoadCommand and SkillsManager (load, read, update). One guard serves all. +\* Source: the header language in a workspace command or skill file. Sink: the gray-matter engine call. +\* Failure: a file header selects an executable engine and the extension runs its code. \* Invariant: NoExecutableEngine. gray-matter is an oracle. Only the header language is modeled. \* Expect: Fixed holds. None fails at once. NoBomStrip fails with a BOM and an executable header. \* Result: Fixed holds in 6 states. None fails in 1 state. NoBomStrip fails in 1 state, with a BOM. \* Replay: gray-matter runs a js header in the real library. The guard in the code stops it. -\* Not modeled: the YAML and JSON parsers. The command body. +\* Not modeled: the YAML and JSON parsers. The file body. \* Cost: TLC runs in under 1 second. Agent time is not measured. -\* Review: 1 covered (bot thread on double BOM, PR 2455), 0 added, 0 gap. +\* Review: 1 covered (bot thread on double BOM, PR 2455), 0 added, 1 gap. +\* Gap: PR 2456 bot thread on uppercase YAML. The spec models safety only, not false rejects. A test covers it. \* Replay: two BOMs do not run code in gray-matter. It is a false alarm. A test case stays. +\* Skills: the skill caller is the same input domain. The skill path was unguarded before this change. +\* Property test: src/utils/__tests__/safeFrontmatter.spec.ts. Caller tests: SkillsManager.spec.ts, frontmatter-commands.spec.ts. CONSTANT Variant \* "Fixed", "None" or "NoBomStrip" diff --git a/src/services/command/__tests__/frontmatter-commands.spec.ts b/src/services/command/__tests__/frontmatter-commands.spec.ts index 582e95cffa..c46c643f26 100644 --- a/src/services/command/__tests__/frontmatter-commands.spec.ts +++ b/src/services/command/__tests__/frontmatter-commands.spec.ts @@ -516,7 +516,7 @@ Deploy the app.` }) }) -// Invariant NoExecutableEngine (docs/architecture/tla/CommandFrontmatter.tla): no header runs code. +// Invariant NoExecutableEngine (docs/architecture/tla/Frontmatter.tla): no header runs code. // Exercise the real parser through both public loading paths. describe.each(["discovery", "individual"])("%s frontmatter security", (entryPoint) => { async function load(content: string) { diff --git a/src/services/command/commands.ts b/src/services/command/commands.ts index 7294e19eb5..530c54eb82 100644 --- a/src/services/command/commands.ts +++ b/src/services/command/commands.ts @@ -1,7 +1,7 @@ import fs from "fs/promises" import * as path from "path" import { Dirent } from "fs" -import matter from "gray-matter" +import { parseFrontmatter } from "../../utils/safeFrontmatter" import { getGlobalRooDirectory, getProjectRooDirectoryForCwd } from "../roo-config" import { getBuiltInCommands, getBuiltInCommand } from "./built-in-commands" @@ -10,19 +10,6 @@ import { getBuiltInCommands, getBuiltInCommand } from "./built-in-commands" */ const MAX_DEPTH = 5 -/** Parse command metadata only after rejecting document-selected executable engines. */ -function parseCommandFrontmatter(content: string) { - // gray-matter strips a leading BOM before detecting the opening delimiter. - const input = content.replace(/^\uFEFF/, "") - if (matter.test(input)) { - const { name: language } = matter.language(input) - if (language && !["yaml", "yml", "json"].includes(language.toLowerCase())) { - throw new Error(`Unsupported command frontmatter language: ${language}`) - } - } - return matter(content) -} - export interface Command { name: string content: string @@ -234,7 +221,7 @@ async function tryLoadCommand( try { // Try to parse frontmatter with gray-matter - parsed = parseCommandFrontmatter(content) + parsed = parseFrontmatter(content) description = typeof parsed.data.description === "string" && parsed.data.description.trim() ? parsed.data.description.trim() @@ -319,7 +306,7 @@ async function scanCommandDirectory( try { // Try to parse frontmatter with gray-matter - parsed = parseCommandFrontmatter(content) + parsed = parseFrontmatter(content) description = typeof parsed.data.description === "string" && parsed.data.description.trim() ? parsed.data.description.trim() diff --git a/src/services/skills/SkillsManager.ts b/src/services/skills/SkillsManager.ts index 92ff4e0e09..09809a9bcc 100644 --- a/src/services/skills/SkillsManager.ts +++ b/src/services/skills/SkillsManager.ts @@ -2,6 +2,7 @@ import * as fs from "fs/promises" import * as path from "path" import * as vscode from "vscode" import matter from "gray-matter" +import { parseFrontmatter } from "../../utils/safeFrontmatter" import type { ClineProvider } from "../../core/webview/ClineProvider" import { getGlobalRooDirectory, getGlobalAgentsDirectory, getProjectAgentsDirectoryForCwd } from "../roo-config" @@ -316,7 +317,7 @@ export class SkillsManager { try { // Use gray-matter to parse frontmatter - const { data: frontmatter } = matter(fileContent) + const { data: frontmatter } = parseFrontmatter(fileContent) // Validate required fields (only name and description for now) if (!frontmatter.name || typeof frontmatter.name !== "string") { @@ -490,7 +491,7 @@ export class SkillsManager { // Read skill content from disk const fileContent = await fs.readFile(skill.path, "utf-8") - const { content: body } = matter(fileContent) + const { content: body } = parseFrontmatter(fileContent) return { ...skill, @@ -945,7 +946,7 @@ Add your skill instructions here. // Read the current SKILL.md file const fileContent = await fs.readFile(skill.path, "utf-8") - const { data: frontmatter, content: body } = matter(fileContent) + const { data: frontmatter, content: body } = parseFrontmatter(fileContent) // Update the frontmatter with new modeSlugs if (newModeSlugs && newModeSlugs.length > 0) { @@ -959,7 +960,7 @@ Add your skill instructions here. } // Serialize back to SKILL.md format - const newContent = matter.stringify(body, frontmatter) + const newContent = matter.stringify({ content: body }, frontmatter) await fs.writeFile(skill.path, newContent, "utf-8") // Refresh skills list diff --git a/src/services/skills/__tests__/SkillsManager.spec.ts b/src/services/skills/__tests__/SkillsManager.spec.ts index 1d6727605e..68fe0ecd67 100644 --- a/src/services/skills/__tests__/SkillsManager.spec.ts +++ b/src/services/skills/__tests__/SkillsManager.spec.ts @@ -177,6 +177,47 @@ describe("SkillsManager", () => { await skillsManager.dispose() }) + it.each(["javascript", "js", "JS"])("blocks executable %s metadata in skill operations", async (language) => { + const skillDir = p(projectSkillsDir, "example") + mockDirectoryExists.mockImplementation(async (dir: string) => dir === projectSkillsDir) + mockRealpath.mockImplementation(async (value: string) => value) + mockReaddir.mockImplementation(async (dir: string) => (dir === projectSkillsDir ? ["example"] : [])) + mockStat.mockResolvedValue({ isDirectory: () => true }) + mockFileExists.mockResolvedValue(true) + const instructions = `---${language}\n(globalThis.frontmatterExecuted(), {})\n---\nInstructions` + const valid = `---\nname: example\ndescription: Example skill\n---\n${instructions}` + mockReadFile.mockResolvedValue(valid) + await skillsManager.discoverSkills() + expect((await skillsManager.getSkillContent("example"))?.instructions).toBe(instructions) + + const executed = vi.fn() + vi.stubGlobal("frontmatterExecuted", executed) + try { + await skillsManager.updateSkillModes("example", "project", ["code"]) + expect(mockWriteFile).toHaveBeenCalledWith( + p(skillDir, "SKILL.md"), + expect.stringContaining(instructions), + "utf-8", + ) + mockWriteFile.mockClear() + mockReadFile.mockResolvedValue( + `---${language}\n(globalThis.frontmatterExecuted(), {name: "example", description: "Example"})\n---\nBody`, + ) + await expect(skillsManager.getSkillContent("example")).rejects.toThrow("Unsupported frontmatter language") + await expect(skillsManager.updateSkillModes("example", "project", ["code"])).rejects.toThrow( + "Unsupported frontmatter language", + ) + expect(mockWriteFile).not.toHaveBeenCalled() + await skillsManager.discoverSkills() + expect(skillsManager.getSkillsMetadata().some((skill) => skill.path === p(skillDir, "SKILL.md"))).toBe( + false, + ) + expect(executed).not.toHaveBeenCalled() + } finally { + vi.unstubAllGlobals() + } + }) + describe("discoverSkills", () => { it("should discover skills from global directory", async () => { const pdfSkillDir = p(globalSkillsDir, "pdf-processing") diff --git a/src/utils/__tests__/safeFrontmatter.spec.ts b/src/utils/__tests__/safeFrontmatter.spec.ts new file mode 100644 index 0000000000..c6fb91fea2 --- /dev/null +++ b/src/utils/__tests__/safeFrontmatter.spec.ts @@ -0,0 +1,53 @@ +import { parseFrontmatter } from "../safeFrontmatter" + +describe("parseFrontmatter", () => { + it.each(["", "yaml", "yml", "json", "YAML", "YML"])("accepts data-only %s metadata", (language) => { + const metadata = language.toLowerCase() === "json" ? '{"name":"example"}' : "name: example" + expect(parseFrontmatter(`---${language}\n${metadata}\n---\nBody`)).toMatchObject({ + data: { name: "example" }, + content: "Body", + }) + }) + + it.each(["javascript", "js", "JavaScript", "JS", " javascript ", "toml"])( + "rejects %s before executing metadata, including with a BOM", + (language) => { + for (const prefix of ["", "\uFEFF"]) { + const executed = vi.fn() + vi.stubGlobal("frontmatterExecuted", executed) + try { + expect(() => + parseFrontmatter( + `${prefix}---${language}\r\n(globalThis.frontmatterExecuted(), {})\r\n---\r\nBody`, + ), + ).toThrow("Unsupported frontmatter language") + expect(executed).not.toHaveBeenCalled() + } finally { + vi.unstubAllGlobals() + } + } + }, + ) + + it("does not strip a second BOM and expose an unchecked selector", () => { + const executed = vi.fn() + vi.stubGlobal("frontmatterExecuted", executed) + try { + parseFrontmatter("\uFEFF\uFEFF---js\n(globalThis.frontmatterExecuted(), {})\n---\nBody") + expect(executed).not.toHaveBeenCalled() + } finally { + vi.unstubAllGlobals() + } + }) + + it("accepts data-only metadata after a BOM", () => { + expect(parseFrontmatter("\uFEFF---yaml\nname: example\n---\nBody")).toMatchObject({ + data: { name: "example" }, + content: "Body", + }) + }) + + it("preserves Markdown without metadata", () => { + expect(parseFrontmatter("# Heading\nBody").content).toBe("# Heading\nBody") + }) +}) diff --git a/src/utils/safeFrontmatter.ts b/src/utils/safeFrontmatter.ts new file mode 100644 index 0000000000..5229e470de --- /dev/null +++ b/src/utils/safeFrontmatter.ts @@ -0,0 +1,16 @@ +import matter from "gray-matter" + +/** Parse Markdown metadata without allowing document-selected executable engines. */ +export function parseFrontmatter(content: string) { + // gray-matter strips a leading BOM before detecting the opening delimiter. + const normalized = content.replace(/^\uFEFF/, "") + if (normalized.startsWith("---") && normalized[3] !== "-") { + const { name } = matter.language(normalized) + if (name && !["yaml", "yml", "json"].includes(name.toLowerCase())) { + throw new Error(`Unsupported frontmatter language: ${name}`) + } + } + + // Passing options also bypasses gray-matter's shared, input-only parse cache. + return matter(content, { language: "yaml" }) +}