diff --git a/src/application/ClientConfigurationDocument.test.ts b/src/application/ClientConfigurationDocument.test.ts new file mode 100644 index 000000000..88958895d --- /dev/null +++ b/src/application/ClientConfigurationDocument.test.ts @@ -0,0 +1,105 @@ +import { describe, expect, it } from "vitest"; + +import { + clientConfigurationServersKey, + clientRegistrationEntry, + parseClientConfiguration, + serializeClientConfiguration, +} from "./ClientConfigurationDocument.js"; + +describe.each([ + "json", + "vscode", + "copilot_cli", + "opencode", + "commandcode", +] as const)("%s client configuration BOM handling", (format) => { + const serversKey = clientConfigurationServersKey(format); + + it.each(["", "\uFEFF"])("parses a document with prefix %j", (bom) => { + const registration = clientRegistrationEntry(format, ["rea", "mcp"], {}); + const document = { [serversKey]: { rea: registration } }; + + expect( + parseClientConfiguration(`${bom}${JSON.stringify(document)}`, format), + ).toEqual({ document, servers: document[serversKey], serversKey }); + }); + + it.each(["", "\uFEFF"])( + "reports malformed JSON at the original offset with prefix %j", + (bom) => { + const text = `${bom}{\r\n "${serversKey}": {"rea": @}\r\n}`; + + expect(() => parseClientConfiguration(text, format)).toThrow( + new SyntaxError( + `Invalid JSON/JSONC at offset ${text.indexOf("@")}: InvalidSymbol`, + ), + ); + }, + ); + + it.each([ + ["\uFEFF\uFEFF{}", 1], + [" \uFEFF{}", 1], + ['{"setting":\uFEFFtrue}', 11], + ['\uFEFF{"setting":\uFEFFtrue}', 12], + ] as const)("rejects a nonleading BOM in %j", (text, offset) => { + expect(() => parseClientConfiguration(text, format)).toThrow( + new SyntaxError(`Invalid JSON/JSONC at offset ${offset}: InvalidSymbol`), + ); + }); + + it.each(["", "\uFEFF"])( + "preserves prefix %j and unrelated bytes across add, update, and removal", + (bom) => { + const prefix = `${bom}{\r\n // Keep \uFEFF in comments.\r\n "label": "left\uFEFFright",\r\n "${serversKey}": {\r\n // Other server.\r\n "other": {\r\n "command": "other\uFEFFtool"\r\n },\r\n`; + const suffix = ' },\r\n "theme": "dark",\r\n}\r\n'; + const original = `${prefix}${suffix}`; + let text = original; + + for (const registration of [ + clientRegistrationEntry(format, ["rea", "mcp"], {}), + clientRegistrationEntry(format, ["rea-next", "mcp"], { + LABEL: "left\uFEFFright", + }), + undefined, + ]) { + const parsed = parseClientConfiguration(text, format); + const servers = { ...parsed.servers }; + if (registration === undefined) delete servers.rea; + else servers.rea = registration; + const document = { ...parsed.document, [serversKey]: servers }; + + text = serializeClientConfiguration(document, format, text, "rea"); + + expect(parseClientConfiguration(text, format)).toEqual({ + document, + servers, + serversKey, + }); + expect(Buffer.from(text.slice(0, prefix.length))).toEqual( + Buffer.from(prefix), + ); + expect(Buffer.from(text.slice(-suffix.length))).toEqual( + Buffer.from(suffix), + ); + expect(text.replaceAll("\r\n", "")).not.toContain("\n"); + } + + expect(text).toBe(original); + }, + ); +}); + +describe("TOML client configuration BOM handling", () => { + it("retains the TOML parser's existing leading-BOM rejection", () => { + const text = '[mcp_servers.rea]\ncommand = "rea"\n'; + + expect(parseClientConfiguration(text, "toml").servers).toEqual({ + rea: { command: "rea" }, + }); + expect(() => parseClientConfiguration(`\uFEFF${text}`, "toml")).toThrow( + "Invalid TOML document", + ); + }); +}); diff --git a/src/application/ClientConfigurationDocument.ts b/src/application/ClientConfigurationDocument.ts index e896f651f..6eb2da3a8 100644 --- a/src/application/ClientConfigurationDocument.ts +++ b/src/application/ClientConfigurationDocument.ts @@ -66,7 +66,9 @@ const parseDocument = ( ): Record => { if (format === "toml") return objectSchema.parse(parseToml(text)); const errors: ParseError[] = []; - const document = parseJsonc(text, errors, { allowTrailingComma: true }); + // Accept a UTF-8 BOM without shifting diagnostics or editing the original text. + const jsonText = text.startsWith("\uFEFF") ? ` ${text.slice(1)}` : text; + const document = parseJsonc(jsonText, errors, { allowTrailingComma: true }); const firstError = errors[0]; if (firstError !== undefined) throw new SyntaxError( diff --git a/tests/boundary/filesystem/clientConfigurationBom.test.ts b/tests/boundary/filesystem/clientConfigurationBom.test.ts new file mode 100644 index 000000000..9ca72642d --- /dev/null +++ b/tests/boundary/filesystem/clientConfigurationBom.test.ts @@ -0,0 +1,130 @@ +import { mkdir, readFile, readdir, writeFile } from "node:fs/promises"; +import { dirname, join } from "node:path"; + +import { describe, expect, it } from "vitest"; + +import { + clientConfigurationServersKey, + clientRegistrationEntry, + parseClientConfiguration, +} from "../../../src/application/ClientConfigurationDocument.js"; +import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js"; +import { + clientConfigurationAligned, + configureClientConfiguration, + inspectClientConfiguration, +} from "../../../src/application/SetupClientConfiguration.js"; +import { supportedClients } from "../../../src/application/SupportedClients.js"; +import { PRODUCT_IDENTITY } from "../../../src/identity.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; + +describe.each([ + "claude_code", + "vscode", + "copilot_cli", + "opencode", + "commandcode", +])("client configuration for %s", (name) => { + it.each(["", "\uFEFF"])( + "preflights, configures, and reads back prefix %j in an isolated home", + async (bom) => { + const home = await createTestTempDirectory("rea-client-config-bom-"); + const client = supportedClients(home, "linux", {}).find( + (candidate) => candidate.name === name, + ); + if (client?.format === undefined) throw new Error(`missing ${name}`); + const serversKey = clientConfigurationServersKey(client.format); + const original = `${bom}// Keep the client preferences.\r\n${JSON.stringify( + { + label: "left\uFEFFright", + [serversKey]: { other: { command: "other" } }, + theme: "dark", + }, + null, + 2, + ).replaceAll("\n", "\r\n")}\r\n`; + await mkdir(dirname(client.configPath), { recursive: true }); + await writeFile(client.configPath, original); + const currentCommandPath = join(home, "rea"); + + for (const command of [ + ["npx", "-y", PRODUCT_IDENTITY.registrationPackageSpecifier, "mcp"], + [currentCommandPath, "mcp"], + ]) { + expect(await inspectClientConfiguration(client, {}, command)).toEqual({ + status: "update", + backupPath: `${client.configPath}.rea.backup`, + }); + expect(await clientConfigurationAligned(client, {}, command)).toBe( + false, + ); + expect(await configureClientConfiguration(client, {}, command)).toEqual( + { + status: "configured", + backupPath: `${client.configPath}.rea.backup`, + }, + ); + const updated = await readFile(client.configPath, "utf8"); + expect( + updated.startsWith(`${bom}// Keep the client preferences.\r\n`), + ).toBe(true); + expect( + parseClientConfiguration(updated, client.format).document, + ).toEqual({ + label: "left\uFEFFright", + [serversKey]: { + other: { command: "other" }, + rea: clientRegistrationEntry(client.format, command, {}), + }, + theme: "dark", + }); + expect(await clientConfigurationAligned(client, {}, command)).toBe( + true, + ); + expect(await inspectClientConfiguration(client, {}, command)).toEqual({ + status: "already_current", + }); + expect( + await readClientRegistrationStatuses(home, currentCommandPath, { + platform: "linux", + environment: {}, + }), + ).toEqual([ + { + client: name, + config_path: client.configPath, + state: "aligned", + command, + remediation: null, + }, + ]); + expect(await configureClientConfiguration(client, {}, command)).toEqual( + { + status: "unchanged", + }, + ); + expect(await readFile(client.configPath)).toEqual(Buffer.from(updated)); + expect(await readFile(`${client.configPath}.rea.backup`)).toEqual( + Buffer.from(original), + ); + } + }, + ); +}); + +it("rejects malformed BOM-prefixed JSON without writing or backing it up", async () => { + const home = await createTestTempDirectory("rea-client-config-bom-invalid-"); + const configPath = join(home, "mcp.json"); + const client = { name: "vscode", format: "vscode", configPath } as const; + const original = '\uFEFF{"servers": {"rea": @}}'; + await writeFile(configPath, original); + + expect( + await inspectClientConfiguration(client, {}, ["rea", "mcp"]), + ).toMatchObject({ status: "invalid" }); + expect( + await configureClientConfiguration(client, {}, ["rea", "mcp"]), + ).toEqual({ status: "failed", reason: "readback" }); + expect(await readFile(configPath)).toEqual(Buffer.from(original)); + expect(await readdir(home)).toEqual(["mcp.json"]); +});